forked from mtusi2026/mtusi2026lab3
65 lines
2.1 KiB
Python
65 lines
2.1 KiB
Python
"""Apply numbered SQL files once. Run as a separate one-shot step: python -m app.migrate."""
|
|
import asyncio
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
import asyncpg
|
|
|
|
from .config import load_settings
|
|
from .db import open_pool
|
|
|
|
logger = logging.getLogger('messenger')
|
|
|
|
_MIGRATIONS = Path(__file__).resolve().parents[1] / 'migrations'
|
|
# Any constant shared by all runners; serializes concurrent migrators across processes.
|
|
_LOCK_ID = 3_2026_0003
|
|
|
|
_BOOTSTRAP = """
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
|
)
|
|
"""
|
|
|
|
|
|
def expected_versions() -> list[str]:
|
|
return sorted(path.name for path in _MIGRATIONS.glob('*.sql'))
|
|
|
|
|
|
async def apply_migrations(pool: asyncpg.Pool) -> None:
|
|
async with pool.acquire() as conn:
|
|
await conn.execute('SET statement_timeout = 0')
|
|
await conn.execute('SELECT pg_advisory_lock($1)', _LOCK_ID)
|
|
try:
|
|
await conn.execute(_BOOTSTRAP)
|
|
rows = await conn.fetch('SELECT version FROM schema_migrations')
|
|
applied = {row['version'] for row in rows}
|
|
for version in expected_versions():
|
|
if version in applied:
|
|
logger.info('migration %s already applied', version)
|
|
continue
|
|
sql = (_MIGRATIONS / version).read_text(encoding='utf-8')
|
|
async with conn.transaction():
|
|
await conn.execute(sql)
|
|
await conn.execute(
|
|
'INSERT INTO schema_migrations (version) VALUES ($1)',
|
|
version,
|
|
)
|
|
logger.info('applied migration %s', version)
|
|
finally:
|
|
await conn.execute('SELECT pg_advisory_unlock($1)', _LOCK_ID)
|
|
|
|
|
|
async def _main() -> None:
|
|
settings = load_settings()
|
|
pool = await open_pool(settings.database_url)
|
|
try:
|
|
await apply_migrations(pool)
|
|
finally:
|
|
await pool.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
logging.basicConfig(level=logging.INFO, format='%(levelname)s %(message)s')
|
|
asyncio.run(_main())
|