On Dec 3, 2009, at 2:39 PM, Victor Olex wrote:
By database we refer to a separate instance (could be on another
server) of equvalent database i.e. production and development
environments.
Using sqlalchemy.ext.declarative, what would be a correct pattern to
enable one model to connect to two equivalent databases?
Consider:
--- model.py ---
Base = declarative_base()
metadata = Base.metadata
class MyTable(Base):
__tablename__ = 'my_table'
id = Column(Integer, primary_key=True, nullable=False)
description = Column(CHAR(length=100), nullable=False)
_Session = sessionmaker()
def make_session(uri):
metadata.bind = engine
session = Session(bind=engine)
return session
--- program.py --
import model
copy some data between databases
srcdb = model.make_session(srcdb_uri)
destdb = model.make_session(srcdb_uri)
items = srcdb.query(model.MyTable).all()
for i in items:
destdb.merge(i)
destdb.commit()
---
We have two distinct sessions bound to to different databases but
because metadata is a module level variable it gets rebound to the
database of last call.
never bind your metadata to an engine if you do not require this functionality.
it is an entirely optional convenience feature.
Also I am somewhat unclear on the difference between metadata binding
to engine and session binding to engine, especially when they end up
different. What is relevance of MetaData binding?
it is discussed here:
http://www.sqlalchemy.org/docs/05/metadata.html#binding-metadata-to-an-engine-or-connection
in the upcoming 0.6 documentation, I've expounded upon this a bit:
http://www.sqlalchemy.org/docs/06/metadata.html#binding-metadata-to-an-engine-or-connection
Should you use bind ? It’s probably best to start without it. If you find
yourself constantly needing to specify the same Engine object throughout the
entire application, consider binding as a convenience feature which is
applicable to applications that don’t have multiple engines in use and don’t
have the need to reference connections explicitly. It should also be noted that
an application which is focused on using the SQLAlchemy ORM will not be dealing
explicitly with Engine or Connection objects very much in any case, so it’s
probably less confusing and more “future proof” to not use the bind attribute.
--
You received this message because you are subscribed to the Google Groups
sqlalchemy group.
To post to this group, send email to sqlalch...@googlegroups.com.
To unsubscribe from this group, send email to
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at
http://groups.google.com/group/sqlalchemy?hl=en.