Files
mtusi2026lab3/app/migrate.py
T

24 lines
1017 B
Python

"""Single-purpose Compose migration job. APIs never apply DDL on startup."""
from pathlib import Path
from .main import db, log
def main():
directory = Path(__file__).resolve().parent.parent / 'migrations'
with db() as conn:
conn.execute('SELECT pg_advisory_xact_lock(2026, 2)')
conn.execute('''CREATE TABLE IF NOT EXISTS schema_migrations (
version integer PRIMARY KEY,
applied_at timestamptz NOT NULL DEFAULT CURRENT_TIMESTAMP)''')
for path in sorted(directory.glob('*.sql')):
version = int(path.name.split('_', 1)[0])
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s', (version,)).fetchone():
conn.execute(path.read_text(encoding='utf-8'))
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (version,))
log.info('Applied migration %03d', version)
log.info('Migrations complete')
if __name__ == '__main__':
main()