"""Timestamped schema migrations, applied once by the database initializer. schema.sql is the frozen baseline and runs on every start; a change after it is a file in app/migrations/, named YYYYMMDDHHMM_slug.sql. The name is the migration's identity and is recorded in dtf_local.migrations, so a deploy never applies one twice and an older image skips names it does not know. """ import re from pathlib import Path MIGRATIONS = Path(__file__).resolve().with_name('migrations') LOCK = 804209 NAME = re.compile(r'\d{12}_[a-z0-9-]+\.sql') def apply(c, directory=MIGRATIONS) -> list[str]: """Run, in name order, every migration file not yet recorded in dtf_local.migrations, each recorded in the same transaction. A name in the table that has no file (written by a newer image) is ignored, so an older image still starts.""" c.execute('SELECT pg_advisory_xact_lock(%s)', (LOCK,)) files = {} for path in Path(directory).iterdir(): if not path.is_file() or not NAME.fullmatch(path.name): raise ValueError(f'Unexpected file in {directory}: {path.name}') files[path.name] = path applied = [] for name in sorted(files): if c.execute('SELECT 1 FROM dtf_local.migrations WHERE name=%s', (name,)).fetchone(): continue c.execute(files[name].read_text()) c.execute('INSERT INTO dtf_local.migrations(name) VALUES(%s)', (name,)) applied.append(name) return applied