37 lines
1.2 KiB
Python
37 lines
1.2 KiB
Python
from pathlib import Path
|
|
|
|
from sqlalchemy import text
|
|
|
|
from .db import engine
|
|
|
|
|
|
MIGRATIONS = Path(__file__).resolve().parents[2] / "migrations"
|
|
|
|
|
|
def migrate() -> None:
|
|
with engine.begin() as connection:
|
|
connection.exec_driver_sql("SELECT pg_advisory_xact_lock(2026102202)")
|
|
connection.exec_driver_sql(
|
|
"CREATE TABLE IF NOT EXISTS schema_migrations "
|
|
"(version VARCHAR(128) PRIMARY KEY, applied_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP)"
|
|
)
|
|
applied = set(connection.execute(text("SELECT version FROM schema_migrations")).scalars())
|
|
for path in sorted(MIGRATIONS.glob("*.sql")):
|
|
version = path.stem
|
|
if version in applied:
|
|
continue
|
|
sql = path.read_text(encoding="utf-8")
|
|
for statement in sql.split(";"):
|
|
if statement.strip():
|
|
connection.exec_driver_sql(statement)
|
|
connection.execute(
|
|
text("INSERT INTO schema_migrations(version) VALUES (:version)"),
|
|
{"version": version},
|
|
)
|
|
print(f"Applied migration {version}")
|
|
engine.dispose()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
migrate()
|