On Sep 2, 2011, at 3:02 AM, Wichert Akkerman wrote:

> On 09/02/2011 03:31 AM, Michael Bayer wrote:
>> With SQLAlchemy you should have an ongoing transaction/session defined 
>> externally to individual operations on your mapped objects - SQLA uses the 
>> "unit of work" pattern which specifically is about grouping related 
>> persistence/query operations together. The usage you have above is still 
>> thinking in the "active record" style of things - "session per individual 
>> persistence operation" - and won't take full advantage of SQLA's way of 
>> doing things.
> 
> I can see this  being useful if you need a id generated by a serial though. 
> In places where I need something like that I use object_session(self), which 
> seems to work well.


OK let me clarify -   it is *entirely OK*, even encouraged, to make usage of 
the Session inside of object methods.   object_session(self) to do queries, 
add() more things, as well as using a contextual Session to add() new objects 
from within a @classmethod.   This is commonplace and necessary.   Use Sessions 
freely anywhere and everywhere.

What is *usually not needed*, is to create a brand new Session inside of an 
object method, and then to commit() the transaction it uses.   Usually, there 
should be an external context that all objects are interfacing with, i.e., a 
Session.   If you don't have an ongoing context at all, and are adding "x = 
Session(); x.add(self); x.commit()" inside of all your methods as the normal 
way of doing things, that is definitely the wrong way to do it.

The case where you *may* want to build a brand new Session and commit it inside 
of a method is when you specifically want some operation to occur in a 
transaction that is distinct from everything else that's going on ;  I use such 
a notion to write operations to a "logging" table in my app, so that a web GUI 
can read that one table for status while some long operation is going on, and 
also so that the log of activity remains if the long running operation fails, 
and the transaction is rolled back.  But even in that case, I have a single 
function in my app called log() that's at the module level which does this 
(with lots of behavioral options).

The main thing I want to get across is, all apps should ideally have some 
standard, defined-in-only-one-or-two-places system of initiating Sessions and 
establishing where the scope of that Session ends for the majority of 
operations, and you should catch yourself if you're trying to avoid building 
that pattern that for some reason.

-- 
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 
sqlalchemy+unsubscr...@googlegroups.com.
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.

Reply via email to