Skip to content

Instantly share code, notes, and snippets.

@hanksudo
Last active June 24, 2025 15:50
Show Gist options
  • Save hanksudo/35b2a7b6752bba887b73 to your computer and use it in GitHub Desktop.
Save hanksudo/35b2a7b6752bba887b73 to your computer and use it in GitHub Desktop.
(Python) reproduce psycopg2 TransactionRollbackError on ISOLATION_LEVEL_SERIALIZABLE mode
# -*- coding: utf-8 -*-
import psycopg2
from datetime import datetime
# ISOLATION_LEVEL_AUTOCOMMIT
# ISOLATION_LEVEL_READ_COMMITTED
# ISOLATION_LEVEL_REPEATABLE_READ
# ISOLATION_LEVEL_SERIALIZABLE
def reproduce_psycopg2():
"""
psycopg2.extensions.TransactionRollbackError: could not serialize access due to read/write dependencies among transactions
DETAIL: Reason code: Canceled on identification as a pivot, during commit attempt.
HINT: The transaction might succeed if retried.
"""
conn1 = psycopg2.connect("dbname=h2 user=h2 password=h2 host=localhost")
conn1.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE)
cur1 = conn1.cursor()
conn2 = psycopg2.connect("dbname=h2 user=h2 password=h2 host=localhost")
conn2.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_SERIALIZABLE)
cur2 = conn2.cursor()
cur1.execute("SELECT * FROM antz WHERE id IN (1);")
cur2.execute("SELECT * FROM antz WHERE id IN (2);")
cur1.execute("UPDATE antz SET fired_at = '%s' WHERE id = 1;" % datetime.now())
cur2.execute("UPDATE antz SET fired_at = '%s' WHERE id = 2;" % datetime.now())
conn1.commit()
conn2.commit()
# begin;
# set transaction isolation level serializable; -- T1
# select * from antz where id in (1,2); -- T1
# update antz set task = 'welcome' where id = 1; -- T1
# commit; -- T1
# begin;
# set transaction isolation level serializable; -- T2
# select * from antz where id in (1,2); -- T2
# update antz set task = 'welcome' where id = 2; -- T2
# commit; -- T2. Prints out error
if __name__ == '__main__':
reproduce_psycopg2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment