PythiloLesson 6 of 12 · progress kept in this browser

Apply a schema migration once and atomically

Schema evolution needs a durable record of which migration has committed. Recording a version before the schema change succeeds can leave an unrecoverable mismatch. Recording it in the same transaction makes a retry safe after a crash or validation failure.

This SQLite migration adds a nullable column and records version one. SQL executes one statement at a time: executescript can alter transaction boundaries, so it is deliberately excluded. Real rolling deployments should also use expand-and-contract compatibility, because an atomic migration does not guarantee that an old application version understands the new schema.

import sqlite3
with sqlite3.connect(":memory:") as db:
    db.execute("create table data(id int)")
    db.execute("alter table data add column note text")
    print([r[1] for r in db.execute("pragma table_info(data)")])
Your task

Implement migrate_note(db,fail=False). Existing tables data(id) and migrations(version primary key). If version 1 exists return False. Otherwise begin a transaction, add note TEXT, optionally raise RuntimeError, insert migration 1 and return True. Expect an idle connection.