"""Versioned, transactional migrations; safe to run again.""" from pathlib import Path import secrets from .config import Settings from .database import Database def migrate(database): directory = Path(__file__).resolve().parents[1] / 'migrations' with database.transaction() as conn: conn.execute('SELECT pg_advisory_xact_lock(20260201)') conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)') versions = {r['version'] for r in conn.execute('SELECT version FROM schema_migrations')} for path in sorted(directory.glob('*.sql')): if path.name not in versions: conn.execute(path.read_text(encoding='utf-8')) conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)', (path.name,)) conn.execute("INSERT INTO app_settings(name,value) VALUES ('cursor_key',%s) ON CONFLICT DO NOTHING", (secrets.token_hex(32),)) if __name__ == '__main__': migrate(Database(Settings.from_env().database_url)) print('Migrations applied successfully (already applied versions skipped).')