A transaction groups several operations so that all or none are applied. It is what prevents a transfer from taking money out of one account without paying it into the other.
commit and rollback
Commands that modify data (INSERT, UPDATE, DELETE) open a transaction. Their changes are not definitive until you do con.commit(); with con.rollback() all the pending ones are discarded.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE grades (student TEXT, grade INTEGER)")
con.execute("INSERT INTO grades VALUES (?, ?)", ("ana", 8))
con.commit() # definitive
con.execute("INSERT INTO grades VALUES (?, ?)", ("luis", 3))
con.rollback() # discarded
print(con.execute("SELECT student FROM grades").fetchall()) # [('ana',)]
In a file database, without commit() the changes are lost when closing. In memory it makes no difference, but it is better to do it anyway.
The connection as a context manager
Remember context managers? The sqlite3 connection is one: with con: does a commit if the block ends well and a rollback if there is an exception (which keeps propagating). Careful: it does not close the connection.
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("CREATE TABLE accounts (name TEXT PRIMARY KEY, balance INTEGER)")
con.executemany("INSERT INTO accounts VALUES (?, ?)", [("ana", 100), ("luis", 50)])
con.commit()
def transfer(source, target, amount):
try:
with con:
con.execute("UPDATE accounts SET balance = balance - ? WHERE name = ?", (amount, source))
con.execute("UPDATE accounts SET balance = balance + ? WHERE name = ?", (amount, target))
if con.execute("SELECT balance FROM accounts WHERE name = ?", (source,)).fetchone()[0] < 0:
raise ValueError("insufficient balance")
print("done")
except ValueError as e:
print("rejected:", e)
transfer("ana", "luis", 30) # done
transfer("luis", "ana", 500) # rejected: insufficient balance
print(con.execute("SELECT * FROM accounts ORDER BY name").fetchall()) # [('ana', 70), ('luis', 80)]
In the second transfer both UPDATEs had already run when the error was detected; the automatic rollback undid them. It is the same pattern you saw in context managers and you practise it in Transfers with rollback.
Constraints: rules inside the table
You can declare rules in CREATE TABLE and the database will enforce them always, wherever the data comes from.
| Constraint | What it requires |
|---|---|
PRIMARY KEY | unique value that identifies each row |
UNIQUE | the value cannot repeat |
NOT NULL | the value cannot be missing |
DEFAULT x | default value if none is given |
CHECK (condition) | the condition must hold |
import sqlite3
con = sqlite3.connect(":memory:")
con.execute("""
CREATE TABLE users (
email TEXT PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER CHECK (age >= 18)
)
""")
con.execute("INSERT INTO users VALUES (?, ?, ?)", ("ana@x.com", "Ana", 30))
attempts = [
("ana@x.com", "Other", 40), # repeated email
("b@x.com", None, 25), # missing name
("c@x.com", "Chris", 17), # under age
]
for data in attempts:
try:
con.execute("INSERT INTO users VALUES (?, ?, ?)", data)
print("inserted")
except sqlite3.IntegrityError:
print("rejected")
# rejected
# rejected
# rejected
print(con.execute("SELECT COUNT(*) FROM users").fetchone()[0]) # 1
When a piece of data breaks a constraint, sqlite3.IntegrityError is raised. Catching it lets you warn the user without the program stopping. You practise it in Integrity constraints.
What is the advantage
Validating in the Python program is not enough: there may be another program, a bug or a manual query that inserts wrong data. Constraints are the last line of defence and keep the database consistent.