Michael Bayer wrote:
> On Nov 12, 2007, at 5:37 AM, Huy Do wrote:
>
>   
>> Hi,
>>
>> I've just had  a heck of a time getting transactions to behave  
>> correctly
>> after upgrading to 0.4dev from 0.3.6, and I just wanted to make sure
>> that I am doing things correctly.
>>
>> I've found that to totally control transactions myself, and get ORM
>> sessions (i.e Session.flush()) to interact with SQL transactions i.e
>> table.insert().execute(), I had to do the following.
>>
>> engine = create_engine(appconfig.dburi, strategy='threadlocal',  
>> echo=False)
>> Session = scoped_session(sessionmaker(bind=engine, autoflush=False,
>> transactional=False))
>> metadata = MetaData(engine)
>>
>> then.
>>
>> engine.begin()
>> try:
>>   // Session.flush()
>>   // mytable.insert().execute() stuff
>>   engine.commit
>> except:
>>   engine.rollback()
>>
>> Does this seem correct ?
>>
>> Previously i used autoflush=True, transactional=True together with
>> Session.begin(), Session.commit(), Session.rollback() and I ran into  
>> all
>> sorts of issues e.g transaction was started but never committed etc.
>>
>>     
>
> The reason you have to use "threadlocal" in that case is because you  
> are relying upon "implicit" execution of things like mytable.insert(),  
> and you also want the transaction to propigate from engine to session  
> without explicitly passing the connection to it.  so what youre doing  
> above is OK.   it might actually be the easiest way to do it and is  
> the only way the "implicit" execution style can participate in the  
> transaction.
>   
Great. Thanks for the confirmation.
> 2. use the engine to manage the transaction but dont use threadlocal:
>
> conn = engine.connect()
> trans = conn.begin()
> Session(bind=conn)
> try:
>       # ....
>       conn.execute(mytable.insert(), stuff)
>       trans.commit()
> except:
>       trans.rollback()
> finally:
>       Session.close()
>   
There's no way i'm giving up threadlocal :-) I love it (at least in my 
web programs).

I have this transaction decorator which I wrap all my data access code 
in, and with SA's cool transaction support, I don't have to worry about 
transaction commit/rollback handling again.

def transaction(func):
    '''
    This is a decorator for wrapping methods in a db transaction
    '''
    def trans_func(*args, **kws):
        engine.begin()
        try:
            f = func(*args, **kws)
            engine.commit()
            return f
        except:
            engine.rollback()
            raise
    return trans_func

--~--~---------~--~----~------------~-------~--~----~
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