title: SQLAlchemy: query using tables in two MySQL schemas
body: <p>I have to do some queries on tables that happen to be spread in two different schemas in the same MySQL instance. Using SQL, this is easy, just prefixing the table name with the schema name (assume a and be are the schema names):</p>
  
  <pre><code>SELECT upeople.id AS upeople_id 
  FROM a.upeople JOIN b.changes ON upeople.id = changes.changed_by
  </code></pre>
  
  <p>In SQLAlchemy, it seems this can be used using two engines. And after reading documentation, it seems to me that the following code should work (the bingings doing the tricky part of using two different schema names):</p>
  
  <pre><code>from sqlalchemy import create_engine
  from sqlalchemy.ext.declarative import declarative_base, DeferredReflection
  from sqlalchemy.orm import sessionmaker
  from sqlalchemy.orm.query import Query
  
  Base = declarative_base(cls=DeferredReflection)
  BaseId = declarative_base(cls=DeferredReflection)
  
  class Changes(Base):
      __tablename__ = 'changes'
  
  class UPeople(BaseId):
      __tablename__ = 'upeople'
  
  database='mysql://jgb:XXX@localhost/a'
  id_database='mysql://jgb:XXX@localhost/b'
  
  engine = create_engine(database)
  id_engine = create_engine(id_database)
  Base.prepare(engine)
  BaseId.prepare(id_engine)
  bindings = {Changes: engine,
              UPeople: id_engine}
  Session = sessionmaker(binds=bindings)
  session = Session()
  q = session.query(UPeople.id).join(Changes,
                                     UPeople.id == Changes.changed_by)
  print q
  </code></pre>
  
  <p>But it doesn't. When I execute q (eg q.all()) it fails. "print q" shows a query with no schema names:</p>
  
  <pre><code>SELECT upeople.id AS upeople_id 
  FROM upeople JOIN changes ON upeople.id = changes.changed_by
  </code></pre>
  
  <p>instead of what I expected:</p>
  
  <pre><code>SELECT upeople.id AS upeople_id 
  FROM a.upeople JOIN b.changes ON upeople.id = changes.changed_by
  </code></pre>
  
  <p>What am I missing here?</p>
  
  <p>BTW, I have found that by adding <strong>table_args</strong> such as in:</p>
  
  <pre><code>class Changes(Base):
      __tablename__ = 'changes'
      __table_args__ = {'schema': 'a'}
  </code></pre>
  
  <p>(for both tables), it works. But wonder why the other code doesn't... In addition, I don't have the schema names at the moment of declaring the classes for the tables, with means I cannot use the <strong>table_args</strong> trick anyway...</p>
  
  <p>So, summarizing: how to query using tables from two schemas, the "good way", and if possible in a way that I don't need to include the name when declaring Table classes, but later, when engines and session are defined?</p>