CData Python Connector for Google Analytics

Build 20.0.7587

Executing JOINs

Implicit Joining

Mapped classes of related Google Analytics objects are joined implicitly if there is a singular foreign key relationship. After importing the necessary objects, a relationship is established between your two mapped classes, as in the example below:

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Integer, DateTime, ForeignKey
from sqlalchemy.orm import sessionmaker, relationship

Base = declarative_base()
class Contact(Base):
	__tablename__ = "Contact"
	Id = Column(Integer, primary_key=True)
	LastName = Column(String)
	Email = Column(String)
	BirthDate = Column(DateTime)
	AccountId = Column(String, ForeignKey("Account.Id"))
	Account_Link = relationship("Account", back_populates="Contact_Link")

class Account(Base):
	__tablename__ = "Account"
	Id = Column(String, primary_key=True)
	LastName = Column(String)
	BillingCity = Column(String)
	NumberOfEmployees = Column(Integer)
	Contact_Link = relationship("Contact", order_by=Contact.Id, back_populates="Account_Link")

Once the relationship is established, the tables are queried simultaneously using the session's "query()" method, as below:

for Ac, Ct in session.query(Account, Contact).filter(Account.Id == Contact.AccountId):
  print("AccountId: ", Ac.Id)
  print("AccountName: ", Ac.Name)
  print("ContactId: ", Ct.Id)
  print("ContactLastName: ", Ct.LastName)

Other Join Forms

There may come situations where mapped classes have either no foreign keys or multiple foreign keys. In such situations, different forms of the JOIN query may be needed to accommodate them. Using the earlier classes as examples, the following JOIN queries are possible as well:

  • Explicit condition (necessary if there are no foreign keys in your mapped classes):
    for Ac, Ct in session.query(Account, Contact).join(Contact, Account.Id == Contact.AccountId)
  • Left-to-Right Relationship:
    for Ac, Ct in session.query(Account, Contact).join(Account.Contact_Link)
  • Left-to-Right Relationship with explicit target:
    for Ac, Ct in session.query(Account, Contact).join(Contact, Account.Contact_Link)
  • String form of a Left-to-Right Relationship:
    for Ac, Ct in session.query(Account, Contact).join("Contact_Link")

Copyright (c) 2020 CData Software, Inc. - All rights reserved.
Build 20.0.7587