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.

the two other variants are:

1. use the Session to manage the transaction (below, we have  
transactional=False, which basically means we call "begin" ourselves):

Session.begin()

# execute with Session
Session.execute(mytable.insert(), stuff)

# get the current connection from Session, use that
conn = Session.connection()
conn.execute(mytable.insert(), stuff)

# commit
Session.commit()

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()






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