4 messages in com.googlegroups.sqlalchemy[sqlalchemy] migrating to 0.4: sessio...
FromSent OnAttachments
Max Ischenko28 Dec 2007 01:19 
Max Ischenko28 Dec 2007 01:46 
Michael Bayer29 Dec 2007 10:18 
Max Ischenko02 Jan 2008 02:28 
Subject:[sqlalchemy] migrating to 0.4: session handling
From:Max Ischenko (isch@gmail.com)
Date:12/28/2007 01:19:51 AM
List:com.googlegroups.sqlalchemy

Hello,

I am porting my code to SA 0.4 and cannot figure out whether or not I should work correctly.

I have most of my db-related code united under a single DatabaseFacade class which is then bound to SA session via property:

class DatabaseFacade(object): ... session = property(fget=lambda self: Session())

Session is setup as: Session = scoped_session(sessionmaker(autoflush=True, transactional=True))

and configured later on.

Here is how I use it:

def create_draft(self, **kw): p = WordpressPost(**kw) self.session.save(p) self.session.commit() return p

Since self.session is a property it calls Session() repeatedly. It seems to work but is it OK, from transactional/performance point of view? Do I need to change it to something like: s = self.session # obtain new session s.save(p) s.commit()

I also have a transactional_method() decorator which does session().begin() and then commit() or rollback() depending on whether exception occured or not.

I also noticed that session.save() fails if I try to save a "persistent" object so I am forced to change every such save() call to save_or_update(). I don't mind but why it's not mentioned in whatsnew40/migration guide?

Another error I am now getting is: InvalidRequestError: Instance 'Invoice@0x9b6b36c' is with key (<class ' doupy.model.objects.Invoice'>, (73L,), None) already persisted with a different identity

Any ideas how to fix this?

Method impl. looks lke this (edited for brevity): @transactional_method() def create_invoice(self, wpuser, **kw): invoice = Invoice(wpuser, public_id=str(next_id), **kw) self.session.save(invoice) return invoice

Btw, is it possible to retrieve metadata if you have an engine or configured session object? I haven't found a way so ended up storing it in a module global when session is configured.