On Feb 1, 2014, at 9:01 AM, lars van gemerden <l...@rational-it.com> wrote:

> Oh, on more question:
> 
> might there be anything inherently wrong with the scoped_session approach 
> that i showed in the code snippets above?

the code which illustrates the @contextmanager and the “def Session()” looks 
error-prone and entirely awkward, and the rationale for such a context manager 
isn’t apparent.   

It appears to be mixing the intent of wishing to share random rows between 
multiple sessions (a bad idea) while at the same time trying to conceal the 
details of how a delicate operation like that is performed (it guesses whether 
add() or merge() should be used, etc).  It also seems to mix the concerns of 
dealing with object mechanics and session creation at the same time which are 
typically two different concerns, not to mention that it has a complex system 
of committing or not committing using flags which makes it unsurprising that 
you’re seeing non-existent rows show up in other transactions.

So yeah, if it were me, I’d definitely try to approach whatever the problem is 
it’s trying to solve in a different way, one which preferably sticks to the 
patterns outlined in the ORM tutorial as much as possible (e.g. one session at 
a time, load/manipulate objects, commit(), throw everything away).   Those 
points at which an application actually uses two sessions at once, or transfers 
objects between them, should be very isolated cases with very explicit 
mechanics and clear rationale why this operation is needed in this specific 
case (where typical cases are: sending objects into worker threads or 
processes, moving objects in and out of caching layers, or running two 
transactions simultaneously so that one can commit and the other roll back, 
such as a transaction writing to an application history table).    The app 
wouldn’t have a generic “here’s one of those places we need to use two sessions 
with a specific target object to pull out of one of them” use case such that a 
context manager is needed, there should be extremely few places where that kind 
of thing goes on.

The kind of issue you’re hitting is exactly the one I talk about in detail in 
my talk, “The SQLAlchemy Session in Depth”: 
http://techspot.zzzeek.org/2012/11/14/pycon-canada-the-sqlalchemy-session-in-depth/
  Page 18 of the PDF illustrates a slide “Lack of Behavioral Constraints 
Creates Confusion” illustrating an anti-pattern similar to the one I think 
we’re seeing here.

Attachment: signature.asc
Description: Message signed with OpenPGP using GPGMail

Reply via email to