美文网首页
Transactions and Connection Mana

Transactions and Connection Mana

作者: rick_z | 来源:发表于2017-06-20 14:23 被阅读0次

    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.

    相关文章

      网友评论

          本文标题:Transactions and Connection Mana

          本文链接:https://www.haomeiwen.com/subject/cwioqxtx.html