How to check for pending operations in a PostgreSQL transaction

前端 未结 3 1605
野性不改
野性不改 2021-01-01 13:28

I have a session (SQLAlchemy) on PostgreSQL, with an active uncommitted transaction. I have just passed the session to some call tree that may or may not have issued SQL

3条回答
  •  滥情空心
    2021-01-01 14:30

    Consider the following sequence of statements:

    select txid_current();
    
    begin;
    
    select txid_current();
    

    If the transaction id returned by the two selects is equal, then there is an open transaction. If not then there wasn't, (but now is).

    If the numbers are different, then as a side effect you will just have opened a transaction, which you will probably want to close.

    UPDATE: In fact, as @r2evans points out (thanks for the insight!), you don't need the "begin" -- txid_current() will return the same number just if you are in a transaction.

提交回复
热议问题