33 lines
1.1 KiB
Python
33 lines
1.1 KiB
Python
import hashlib
|
|
from pathlib import Path
|
|
|
|
import psycopg
|
|
|
|
from .config import secret
|
|
|
|
|
|
def migrate():
|
|
with psycopg.connect(secret("DATABASE_URL")) as conn:
|
|
# Serialize independent migration processes without changing application data.
|
|
conn.execute("SELECT pg_advisory_xact_lock(2301002)")
|
|
conn.execute(
|
|
"CREATE TABLE IF NOT EXISTS schema_migrations "
|
|
"(name text PRIMARY KEY, checksum text NOT NULL)"
|
|
)
|
|
for path in sorted(Path("migrations").glob("*.sql")):
|
|
checksum = hashlib.sha256(path.read_bytes()).hexdigest()
|
|
old = conn.execute(
|
|
"SELECT checksum FROM schema_migrations WHERE name=%s", (path.name,)
|
|
).fetchone()
|
|
if old:
|
|
if old[0] != checksum:
|
|
raise RuntimeError("Изменена применённая миграция: " + path.name)
|
|
continue
|
|
conn.execute(path.read_text())
|
|
conn.execute("INSERT INTO schema_migrations VALUES (%s,%s)", (path.name, checksum))
|
|
print("Applied", path.name)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
migrate()
|