Managing Transactions
A newly constructed Session
may be said to be in the “begin” state. In this state, the Session
has not established any connection or transactional state with any of the Engine
objects that may be associated with it.
(新創(chuàng)建的 Session 可以說被歸類到開始階段戒劫,在此階段 Session 沒有與任何的 Engine對(duì)象建立連接或者transactional state)
The Session
then receives requests to operate upon a database connection.(Session會(huì)接收請(qǐng)求根據(jù)數(shù)據(jù)庫連接進(jìn)行操作) Typically, this means it is called upon to execute SQL statements using a particular Engine
, which may be via Session.query()
, Session.execute()
, or within a flush operation of pending data, which occurs when such state exists and Session.commit()
or Session.flush()
is called.
(通過sql語句或者flush操作完成)
As these requests are received, each new Engine
encountered is associated with an ongoing transactional state maintained by the Session
. (當(dāng)請(qǐng)求被接收到后闻察,每一個(gè)遇到的新engine會(huì)與正在進(jìn)行的transactional state相聯(lián)合)When the first Engine
is operated upon, the Session
can be said to have left the “begin” state and entered “transactional” state.(當(dāng)?shù)谝粋€(gè)engine被操作連接后愈魏,session就處于 ‘begin state’ 并且進(jìn)入了“transactional state”) For each Engine
encountered, a Connection
is associated with it, which is acquired via the Engine.contextual_connect()
method. If a Connection
was directly associated with the Session
(see Joining a Session into an External Transaction (such as for test suites) for an example of this), it is added to the transactional state directly.(如果一個(gè)Connection與Session直接連接良狈,那么它同樣跟transactional state直接連接)
For each Connection
, the Session
also maintains a Transaction
object, (對(duì)于每一個(gè) Connection, Session都會(huì)維持一個(gè) Transactional對(duì)象摘投,可以用以下方式獲壤沂酢)which is acquired by calling Connection.begin()
on each Connection
, or if the Session
object has been established using the flag twophase=True
, a TwoPhaseTransaction
object acquired via Connection.begin_twophase()
. These transactions are all committed or rolled back corresponding to the invocation of theSession.commit()
and Session.rollback()
methods. A commit operation will also call the TwoPhaseTransaction.prepare()
method on all transactions if applicable.
When the transactional state is completed after a rollback or commit, the Session
releases all Transaction
and Connection
resources, and goes back to the “begin” state, which will again invoke new Connection
and Transaction
objects as new requests to emit SQL statements are received.
(當(dāng) transactional state被完成后陆盘,Session 會(huì)釋放所有的 Transaction 和 connection資源株汉,并且返回到 ‘begin’ state。之后會(huì)重新調(diào)用新的 connection 和 transaction 對(duì)象液茎,因?yàn)榻邮艿叫掳l(fā)出的SQL語句的請(qǐng)求)
The example below illustrates this lifecycle:
engine = create_engine("...")
Session = sessionmaker(bind=engine)
# new session. no connections are in use.
session = Session()
try:
# first query. a Connection is acquired
# from the Engine, and a Transaction
# started.
item1 = session.query(Item).get(1)
# second query. the same Connection/Transaction
# are used.
item2 = session.query(Item).get(2)
# pending changes are created.
item1.foo = 'bar'
item2.bar = 'foo'
# commit. The pending changes above
# are flushed via flush(), the Transaction
# is committed, the Connection object closed
# and discarded, the underlying DBAPI connection
# returned to the connection pool.
session.commit()
except:
# on rollback, the same closure of state
# as that of commit proceeds.
session.rollback()
raise
finally:
# close the Session. This will expunge(消除) any remaining
# objects as well as reset any existing SessionTransaction
# state. Neither of these steps are usually essential.
# However, if the commit() or rollback() itself experienced
# an unanticipated internal failure (such as due to a mis-behaved
# user-defined event handler), .close() will ensure that
# invalid state is removed.
session.close()
Autocommit Mode
The example of Session
transaction lifecycle illustrated at the start of Managing Transactions applies to a Session
configured in the default mode of autocommit=False
. Constructing a Session
with autocommit=True
produces a Session
placed into “autocommit” mode, where each SQL statement invoked by a Session.query()
or Session.execute()
occurs using a new connection from the connection pool(每個(gè)sql語句都會(huì)從connection pool中抽取一個(gè)新的connection使用), discarding it after results have been iterated(在結(jié)果重復(fù)后丟棄這個(gè)connection). The Session.flush()
operation still occurs within the scope of a single transaction, though this transaction is closed out after the Session.flush()
operation completes.
(Session.flush() 操作仍然發(fā)生在單個(gè)事務(wù)的范圍內(nèi)逞姿,盡管此事務(wù)在Session.flush() 操作完成后被關(guān)閉。)
Warning
“autocommit” mode should not be considered for general use. If used, it should always be combined with the usage ofSession.begin()
and Session.commit()
, to ensure a transaction demarcation.( session.begin()是必要的 )
Executing queries outside of a demarcated transaction is a legacy mode of usage, and can in some cases lead to concurrent connection checkouts.(執(zhí)行query操作在transaction之外很可能導(dǎo)致并發(fā)連接檢查)
In the absence of a demarcated transaction, the Session
cannot make appropriate decisions as to when autoflush should occur nor when auto-expiration should occur, so these features should be disabled with autoflush=False,expire_on_commit=False (在沒有劃分的事務(wù)的情況下捆等,session不能作出適當(dāng)?shù)臎Q定滞造,關(guān)于何時(shí)應(yīng)該發(fā)生auto_flush,或者合適應(yīng)該發(fā)生auto_expiration栋烤,因此應(yīng)該使用autoflush = False禁用這些功能谒养,expire_on_commit = False)
Modern usage of “autocommit” is for framework integrations that need to control specifically when the “begin” state occurs. A session which is configured with autocommit=True
may be placed into the “begin” state using the Session.begin()
method. After the cycle completes upon Session.commit()
or Session.rollback()
, connection and transaction resources are released and the Session
goes back into “autocommit” mode, until Session.begin()
is called again:
(auto_commit=True時(shí),通過session.begin() 將 session 置于‘begin’ state明郭。在 close() 或 commit() 的循環(huán)完成后蝴光, connection 和 transaction的資源被釋放,此時(shí)session返回 autocommit mode 直到 begin()被重新調(diào)用)
Session = sessionmaker(bind=engine, autocommit=True)
session = Session()
session.begin()
try:
item1 = session.query(Item).get(1)
item2 = session.query(Item).get(2)
item1.foo = 'bar'
item2.bar = 'foo'
session.commit()
except:
session.rollback()
raise
Using Subtransactions with Autocommit
A subtransaction indicates usage of the Session.begin()
method in conjunction with the subtransactions=True
flag. This produces a non-transactional, delimiting construct that allows nesting of calls to begin()
and commit()
. Its purpose is to allow the construction of code that can function within a transaction both independently of any external code that starts a transaction, as well as within a block that has already demarcated a transaction.
subtransactions=True
is generally only useful in conjunction with autocommit, and is equivalent to the pattern described at Nesting of Transaction Blocks, where any number of functions can call Connection.begin()
and Transaction.commit()
as though they are the initiator of the transaction, but in fact may be participating in an already ongoing transaction:
# method_a starts a transaction and calls method_b
def method_a(session):
session.begin(subtransactions=True)
try:
method_b(session)
session.commit() # transaction is committed here
except:
session.rollback() # rolls back the transaction
raise
# method_b also starts a transaction, but when
# called from method_a participates in the ongoing
# transaction.
def method_b(session):
session.begin(subtransactions=True)
try:
session.add(SomeObject('bat', 'lala'))
session.commit() # transaction is not committed yet
except:
session.rollback() # rolls back the transaction, in this case
# the one that was initiated in method_a().
raise
# create a Session and call method_a
session = Session(autocommit=True)
method_a(session)
session.close()
Subtransactions are used by the Session.flush()
process to ensure that the flush operation takes place within a transaction, regardless of autocommit. When autocommit is disabled, it is still useful in that it forces the Session
into a “pending rollback” state, as a failed flush cannot be resumed in mid-operation, where the end user still maintains the “scope” of the transaction overall.