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.
(新创建的 Session 可以说被归类到开始阶段,在此阶段 Session 没有与任何的 Engine对象建立连接或者transactional state)

The Session
then receives requests to operate upon a database connection.(Session会接收请求根据数据库连接进行操作) 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
. (当请求被接收到后,每一个遇到的新engine会与正在进行的transactional state相联合)When the first Engine
is operated upon, the Session
can be said to have left the “begin” state and entered “transactional” state.(当第一个engine被操作连接后,session就处于 ‘begin state’ 并且进入了“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.(如果一个Connection与Session直接连接,那么它同样跟transactional state直接连接)

For each Connection
, the Session
also maintains a Transaction
object, (对于每一个 Connection, Session都会维持一个 Transactional对象,可以用以下方式获取)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.
(当 transactional state被完成后,Session 会释放所有的 Transaction 和 connection资源,并且返回到 ‘begin’ state。之后会重新调用新的 connection 和 transaction 对象,因为接受到新发出的SQL语句的请求)

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(每个sql语句都会从connection pool中抽取一个新的connection使用), discarding it after results have been iterated(在结果重复后丢弃这个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() 操作仍然发生在单个事务的范围内,尽管此事务在Session.flush() 操作完成后被关闭。)

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.(执行query操作在transaction之外很可能导致并发连接检查)
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 (在没有划分的事务的情况下,session不能作出适当的决定,关于何时应该发生auto_flush,或者合适应该发生auto_expiration,因此应该使用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时,通过session.begin() 将 session 置于‘begin’ state。在 close() 或 commit() 的循环完成后, connection 和 transaction的资源被释放,此时session返回 autocommit mode 直到 begin()被重新调用)

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.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 199,902评论 5 468
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,037评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 146,978评论 0 332
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 53,867评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 62,763评论 5 360
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,104评论 1 277
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,565评论 3 390
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,236评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,379评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,313评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,363评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,034评论 3 315
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,637评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,719评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,952评论 1 255
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,371评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 41,948评论 2 341

推荐阅读更多精彩内容