forked from mtusi2026/mtusi2026lab3
45 lines
1.2 KiB
Python
45 lines
1.2 KiB
Python
import asyncio
|
|
import asyncpg
|
|
from pathlib import Path
|
|
|
|
from .db import DATABASE_URL
|
|
|
|
|
|
async def migrate():
|
|
conn = await asyncpg.connect(DATABASE_URL)
|
|
|
|
try:
|
|
path = Path(__file__).parent / "migrations"
|
|
|
|
async with conn.transaction():
|
|
await conn.execute("SELECT pg_advisory_xact_lock(12345)")
|
|
|
|
await conn.execute("""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
name TEXT PRIMARY KEY
|
|
)
|
|
""")
|
|
|
|
for file in sorted(path.glob("*.sql")):
|
|
applied = await conn.fetchval(
|
|
"SELECT name FROM schema_migrations WHERE name = $1",
|
|
file.name
|
|
)
|
|
|
|
if not applied:
|
|
await conn.execute(
|
|
file.read_text(encoding="utf-8")
|
|
)
|
|
|
|
await conn.execute(
|
|
"INSERT INTO schema_migrations VALUES ($1)",
|
|
file.name
|
|
)
|
|
|
|
print(f"Applied: {file.name}")
|
|
finally:
|
|
await conn.close()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(migrate()) |