1. Foreign key constraints are disabled by default on every new SQLite connection.
2. Loose column types let invalid numbers (like negative order amounts) slip in unless you enforce CHECK rules.
Here is a self-contained pattern using Python's built-in sqlite3 module to enforce data integrity at the database layer.
1. Enable Foreign Keys and Define Constraints
Always execute PRAGMA foreign_keys = ON; right after opening a connection. Combine REFERENCES with CHECK constraints so the database rejects bad rows before they corrupt downstream queries:
import sqlite3
from datetime import datetime, timezone
def init_schema(conn: sqlite3.Connection) -> None:
conn.execute("PRAGMA foreign_keys = ON;")
conn.executescript(
"""
CREATE TABLE IF NOT EXISTS customers (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE IF NOT EXISTS orders (
id INTEGER PRIMARY KEY AUTOINCREMENT,
customer_id INTEGER NOT NULL REFERENCES customers(id) ON DELETE RESTRICT,
amount_cents INTEGER NOT NULL CHECK (amount_cents > 0),
created_utc TEXT NOT NULL
);
"""
)
2. Verify Constraints With Runnable Assertions
Instead of assuming constraints work, verify both valid writes and expected sqlite3.IntegrityError rejections in an in-memory database:
def run_checks() -> None:
conn = sqlite3.connect(":memory:")
init_schema(conn)
now_iso = datetime(2026, 12, 2, 2, 16, tzinfo=timezone.utc).isoformat()
# 1. Insert a valid customer and order using parameterized placeholders (?)
with conn:
cur = conn.execute(
"INSERT INTO customers (email) VALUES (?)",
("dev@example.com",),
)
customer_id = cur.lastrowid
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(customer_id, 4900, now_iso),
)
# 2. Orphaned customer_id must fail
fk_rejected = False
try:
with conn:
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(9999, 1500, now_iso),
)
except sqlite3.IntegrityError:
fk_rejected = True
assert fk_rejected, "Foreign key constraint did not trigger"
# 3. Non-positive amount_cents must fail
check_rejected = False
try:
with conn:
conn.execute(
"INSERT INTO orders (customer_id, amount_cents, created_utc) VALUES (?, ?, ?)",
(customer_id, -100, now_iso),
)
except sqlite3.IntegrityError:
check_rejected = True
assert check_rejected, "CHECK constraint did not trigger"
# 4. Confirm clean join output
row = conn.execute(
"""
SELECT c.email, o.amount_cents
FROM orders o
JOIN customers c ON https://www.google.com/url?q=http://c.id&source=gmail&ust=1796264203377000&sa=E = o.customer_id
"""
).fetchone()
assert row == ("dev@example.com", 4900)
print("All SQLite integrity checks passed.")
if __name__ == "__main__":
run_checks()
Key Takeaways
- Set PRAGMA foreign_keys = ON; per connection: SQLite resets this flag on every new session.
- Store money as integer cents (amount_cents): Avoids floating-point rounding bugs.
- Use parameterized ? queries: Prevents SQL injection and handles escaping cleanly.
---
Disclosure: I maintain HowCodex (https://www.google.com/url?q=https://www.howcodex.com/&source=gmail&ust=1796264203377000&sa=E), a free, no-paywall programming and computer science tutorial library covering Python, SQL/DBMS, Web Development, and Data Structures. If you are looking for structured beginner-to-intermediate walkthroughs on relational databases and Python, feel free to explore the guides there.