Sobes.tech
Junior — Middle

Is it possible to implement nested transactions within a single database?

sobes.tech AI

Answer from AI

Most database management systems (DBMS) do not support nested transactions directly. However, there is a concept of savepoints, which allow partial rollback of changes within a single transaction, simulating nesting.

For example, in PostgreSQL, you can create a savepoint, perform some operations, and if needed, rollback only to that point without canceling the entire transaction:

BEGIN;
-- operations
SAVEPOINT sp1;
-- operations that can be rolled back separately
ROLLBACK TO SAVEPOINT sp1;
-- continue transaction
COMMIT;

In Python, using the psycopg2 library, it looks like this:

conn = psycopg2.connect(...)
cur = conn.cursor()
conn.autocommit = False
try:
    cur.execute("BEGIN")
    cur.execute("SAVEPOINT sp1")
    # operations
    cur.execute("ROLLBACK TO SAVEPOINT sp1")
    conn.commit()
except Exception:
    conn.rollback()

Thus, nested transactions are implemented through savepoints, not as separate full transactions.