Code

Rules Inside the Table

The vault keeper can check every amount in Python. But one day another program writes to the same database and forgets. The safest place for a rule is inside the table, where every program must obey it.

Constraints

CREATE TABLE lanterns (
    id INTEGER PRIMARY KEY,
    code TEXT NOT NULL UNIQUE,
    fuel INTEGER NOT NULL CHECK (fuel BETWEEN 0 AND 100)
)
  • PRIMARY KEY: each row's unique id. With INTEGER, SQLite numbers new rows for you.
  • NOT NULL: the value can't be missing.
  • UNIQUE: no two rows may share this value.
  • CHECK (...): the condition must be true for every row.

Break a rule and execute raises sqlite3.IntegrityError. The bad row is not saved.

try:
    cur = conn.execute(
        "INSERT INTO lanterns (code, fuel) VALUES (?, ?)",
        ("AMB-1", 140),
    )
    print("new id:", cur.lastrowid)
except sqlite3.IntegrityError as err:
    print("Refused:", err)  # CHECK constraint failed

Naming the columns ((code, fuel)) lets you skip id. cur.lastrowid is the id SQLite just picked.

Assignment

  1. create_vaults(conn) creates a table vaults with:
    • id: an INTEGER PRIMARY KEY
    • owner: TEXT, required and unique
    • coins: INTEGER, required, and never below 0
  2. open_vault(conn, owner, coins) inserts a vault with ? placeholders and returns its new id. If the database refuses (sqlite3.IntegrityError), return None instead.

Let the table enforce the rules. Don't check them with if. The program should print 1, None, None, 2.