Sobes.tech
Junior — Middle

Have you used nested transactions in PostgreSQL in practice?

sobes.tech AI

Answer from AI

PostgreSQL does not have full support for nested transactions, but there is a mechanism called savepoints that allows rolling back part of a transaction without canceling the entire one.

Example of using savepoints in Python with psycopg2:

import psycopg2

conn = psycopg2.connect(...)
cur = conn.cursor()

try:
    cur.execute("BEGIN")
    # Main operations
    cur.execute("INSERT INTO table1 (col) VALUES ('value1')")

    cur.execute("SAVEPOINT sp1")  # Create a savepoint
    try:
        cur.execute("INSERT INTO table2 (col) VALUES ('value2')")
        # If something goes wrong
        # raise Exception("Error")
    except Exception:
        cur.execute("ROLLBACK TO SAVEPOINT sp1")  # Rollback to savepoint

    cur.execute("COMMIT")
except Exception:
    conn.rollback()
finally:
    cur.close()
    conn.close()

Thus, it is possible to partially rollback operations within a transaction, which mimics nested transactions.