Predict the output
What do the two lines print?
import psycopg
with psycopg.connect() as conn:
conn.execute("CREATE TEMP TABLE t (id int) ON COMMIT PRESERVE ROWS")
conn.commit()
try:
with conn.transaction():
conn.execute("INSERT INTO t VALUES (1), (2)")
n = conn.execute("SELECT count(*) FROM t").fetchone()
print("inside test:", n)
raise RuntimeError("roll back after the test")
except RuntimeError:
pass
print("after:", conn.execute("SELECT count(*) FROM t").fetchone())Hint 1 of 1
What does conn.transaction() do on an exception?
Choose an answer, then open Show answer below to check it.
Show answer
Answer: A inside test: (2,) then after: (0,)
Correct. The rows exist inside the transaction and vanish on rollback.
Wrapping each test in a transaction that rolls back gives every test a clean database. Inside, the rows are visible; once the exception rolls back, they are gone.
Why not the others?
- B
inside test: (2,)thenafter: (2,). The exception rolls the transaction back. - C
inside test: (0,)thenafter: (0,). Inside the transaction, the inserts are visible. - D An unhandled RuntimeError. It's caught after the block rolls back.