Hi there,

MikeCo wrote:
> I have an application that will need to bind to several different
> databases with the same structure. The databases to be accessed are
> not known at import time, that will be determined later while the
> application is running. I want to use declarative and autoload the
> columns.  Autoload needs a database connection available when a class
> is first compiled to do the database introspection, that is the part I
> can't figure out. Maybe a custom metaclass?
> 
> If this is already solved, can someone point me at the answer? I
> haven't found it yet.

I've solved it, but the solution is rather particular to Zope technology 
right now. It's spread around z3c.saconfig and megrok.rdb:

http://svn.zope.org/z3c.saconfig/trunk

http://svn.zope.org/megrok.rdb/trunk/

Let me sketch out what's going on:

* z3c.saconfig sets up a special scoped session, with a custom session 
factory and scopefunc. The session factory looks up in the Zope 3 
component architecture for a way to create an engine, but you could use 
some other strategy.

* the engine factory is also looked up dynamically by the session 
factory and in turn creates a SQLAlchemy engine (or returns an existing 
one if the engine is already created).

* when an engine is first created, an event is fired. In effect this 
event is fired when a session is needed for the first time in the 
application.

Now megrok.rdb hooks into this event. If will reflect any tables that 
need to be reflected and create any tables that need to be created (if 
their structure is defined in python).

reflection in the simplest case can be done like this:

metadata.reflect(bind=engine)

and creation can be done like this:

metadata.create_all(engine)

Now at the point the event is handled, previously the various 
declarative classes have been associated with the metadata object.

megrok.rdb actually doesn't use the declarative extension's metaclass 
approach, but instead drives the declarative extension's 
instrument_declarative from a grokker (see the martian library). In my 
approach I use an explicit metadata object. I believe the declarative 
extension creates one on the fly (but you can get to it with Base.metadata).

Anyway, all of this sounds very complicated, as the Zope and Grok stuff 
take particular approaches towards configurability. I think the core of 
this approach is:

* hook up your classes to a metadata (declarative does this for you)

* at the appropriate time, do metadata.reflect(bind=engine)

Regards,

Martijn



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to [EMAIL PROTECTED]
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to