Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check for open transactions on a psycopg2 connection?

How can I check for open transactions on a psycopg2 connection? I intend to add it to my unit/functional tests since Python's DB API uses implicit transactions.

like image 915
Eugene Yarmash Avatar asked Sep 25 '15 13:09

Eugene Yarmash


1 Answers

You can check the connection's status attribute:

from psycopg2.extensions import STATUS_BEGIN, STATUS_READY

if conn.status == STATUS_READY:
    print("No transaction in progress.")
elif conn.status == STATUS_BEGIN:
    print("A transaction is in progress.")

Alternatively, the transaction status can be obtained with connection.get_transaction_status().

To manually check for in-progress transaction you could use PostgreSQL's statistics collector:

SELECT * FROM pg_stat_activity WHERE state = 'idle in transaction';
like image 134
Eugene Yarmash Avatar answered Sep 28 '22 08:09

Eugene Yarmash