AI-Assisted Coding Lab · Run Schema Migrations in Order

40:00left of 40:00

Run Schema Migrations in Order

The deploy tool needs a migration runner that applies each SQL file once, in order, against the production database. The README has the rules, including the cases that come from several branches merging at once. Build migrate.py with the assistant and decide what to keep.

migrate.py1 of 3

Files

migrate.py

Python · Editable
import re
NAME_RE = re.compile(r"(\d+)_[a-z0-9_]+\.sql")
class MigrationError(Exception):
pass
def version_of(name):
match = NAME_RE.fullmatch(name)
if not match:
raise MigrationError(f"bad migration name: {name}")
return int(match.group(1))
def ordered(names):
"""Migration names in the order they run. Two files can't share a version."""
versions = {}
for name in names:
version = version_of(name)
versions[version] = name
raise NotImplementedError
def applied_versions(conn):
conn.execute("CREATE TABLE IF NOT EXISTS schema_migrations (version INTEGER PRIMARY KEY, name TEXT NOT NULL, note TEXT NOT NULL)")
return {row[0] for row in conn.execute("SELECT version FROM schema_migrations")}
def record(conn, name, note):
"""Records that a migration ran, with the deploy's release note."""
raise NotImplementedError
def migrate(conn, migrations, note=""):
"""migrations maps file name to SQL. Runs the pending ones in order and returns their names."""
done = applied_versions(conn)
todo = ordered(migrations)
ran = []
for name in todo:
conn.executescript(migrations[name])
record(conn, name, note)
conn.commit()
ran.append(name)
return ran

Test Output

No runs yet.

Assistant

Scripted
  1. Send the first prompt to start.

Next Prompt

Finish ordered so it returns the names in the order they run.