Transactions and Connection Management

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.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末达址,一起剝皮案震驚了整個(gè)濱河市蔑祟,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌沉唠,老刑警劉巖疆虚,帶你破解...
    沈念sama閱讀 207,113評(píng)論 6 481
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異满葛,居然都是意外死亡径簿,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 88,644評(píng)論 2 381
  • 文/潘曉璐 我一進(jìn)店門嘀韧,熙熙樓的掌柜王于貴愁眉苦臉地迎上來篇亭,“玉大人,你說我怎么就攤上這事锄贷∫氲伲” “怎么了?”我有些...
    開封第一講書人閱讀 153,340評(píng)論 0 344
  • 文/不壞的土叔 我叫張陵谊却,是天一觀的道長(zhǎng)柔昼。 經(jīng)常有香客問我,道長(zhǎng)炎辨,這世上最難降的妖魔是什么捕透? 我笑而不...
    開封第一講書人閱讀 55,449評(píng)論 1 279
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上乙嘀,老公的妹妹穿的比我還像新娘末购。我一直安慰自己,他們只是感情好虎谢,可當(dāng)我...
    茶點(diǎn)故事閱讀 64,445評(píng)論 5 374
  • 文/花漫 我一把揭開白布招盲。 她就那樣靜靜地躺著,像睡著了一般嘉冒。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上咆繁,一...
    開封第一講書人閱讀 49,166評(píng)論 1 284
  • 那天讳推,我揣著相機(jī)與錄音,去河邊找鬼玩般。 笑死银觅,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的坏为。 我是一名探鬼主播究驴,決...
    沈念sama閱讀 38,442評(píng)論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼匀伏!你這毒婦竟也來了洒忧?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 37,105評(píng)論 0 261
  • 序言:老撾萬榮一對(duì)情侶失蹤够颠,失蹤者是張志新(化名)和其女友劉穎熙侍,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體履磨,經(jīng)...
    沈念sama閱讀 43,601評(píng)論 1 300
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡蛉抓,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,066評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了剃诅。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片巷送。...
    茶點(diǎn)故事閱讀 38,161評(píng)論 1 334
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖矛辕,靈堂內(nèi)的尸體忽然破棺而出笑跛,到底是詐尸還是另有隱情,我是刑警寧澤聊品,帶...
    沈念sama閱讀 33,792評(píng)論 4 323
  • 正文 年R本政府宣布堡牡,位于F島的核電站,受9級(jí)特大地震影響杨刨,放射性物質(zhì)發(fā)生泄漏晤柄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,351評(píng)論 3 307
  • 文/蒙蒙 一妖胀、第九天 我趴在偏房一處隱蔽的房頂上張望芥颈。 院中可真熱鬧惠勒,春花似錦、人聲如沸爬坑。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,352評(píng)論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽盾计。三九已至售担,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間署辉,已是汗流浹背族铆。 一陣腳步聲響...
    開封第一講書人閱讀 31,584評(píng)論 1 261
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留哭尝,地道東北人哥攘。 一個(gè)月前我還...
    沈念sama閱讀 45,618評(píng)論 2 355
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像材鹦,于是被迫代替她去往敵國(guó)和親逝淹。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 42,916評(píng)論 2 344

推薦閱讀更多精彩內(nèi)容