views:

62

answers:

0

Hi,

I am using sqlalchemy(version-0.4.5) with turbogears(version - 1.0) as its orm layer, with sharded multiple databases instances at the backend.

While sqlalchemy seems to support passing session/engine bound to a database as a parameter to :
Quering Tables : session.query(...) function
Executing native sql queries : engine.execute(...)

While adding a new table record object( http://www.sqlalchemy.org/docs/ormtutorial.html#adding-new-objects ), I am getting exception.

Lets take the example given below:


sess = get_session(...) #gets appropriate session.
sess.begin()
user1 = User(name='user1')
user2 = User(name='user2')
session.save(user1)
sess.save(user2)
sess.commit()     # write changes to the database

I can't understand, why it needs metadata object bound to a engine/session object to execute first two statements.

And I get following exception while executing first two statements.

Even if I need to pass the session object, there should be a way for me to pass session object as a parameter (as I can pass in the other two functions given above), which after hours of googling I couldn't find any. All I can see is that there is implicit assumption on database engine/session to be used.

There is one ugly way to do this, which is attaching req session object at the module level itself, like:


model.metadata.bind = sess

But then this approach is not thread safe and is bound to fail.

Ideally I want to be able to create a object without need for metdadata to be bound to a engine/session, and could save that instantiated obj later to whichever session I want to.

Please let me know if my understanding/assumption is wrong here and a possible solution.

thanks.