forked from mtusi2026/mtusi2026lab5
рестеу бвт2302 лаба5
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from src.db import connection_kwargs
|
||||
|
||||
|
||||
def main():
|
||||
files = sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql"))
|
||||
if not files:
|
||||
raise RuntimeError("Миграции не найдены")
|
||||
with psycopg.connect(**connection_kwargs()) as conn:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)
|
||||
""")
|
||||
for file in files:
|
||||
applied = False
|
||||
with conn.transaction():
|
||||
conn.execute("SELECT pg_advisory_xact_lock(202602)")
|
||||
exists = conn.execute(
|
||||
"SELECT 1 FROM schema_migrations WHERE version = %s", (file.name,)
|
||||
).fetchone()
|
||||
if exists is None:
|
||||
conn.execute(file.read_text(encoding="utf-8"))
|
||||
conn.execute(
|
||||
"INSERT INTO schema_migrations (version) VALUES (%s)", (file.name,)
|
||||
)
|
||||
applied = True
|
||||
print(("APPLIED " if applied else "SKIP ") + file.name)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user