-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmigrate.py
More file actions
66 lines (50 loc) · 1.57 KB
/
migrate.py
File metadata and controls
66 lines (50 loc) · 1.57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from pathlib import Path
import sys
from sqlalchemy import create_engine, text
from config import DATABASE_URL
def _get_engine():
if not DATABASE_URL:
raise SystemExit("DATABASE_URL is not set")
return create_engine(DATABASE_URL, future=True)
def reset_db():
"""
Drop and recreate the public schema.
DESTRUCTIVE. Intended for dev/test only.
"""
engine = _get_engine()
with engine.begin() as conn:
conn.execute(text("DROP SCHEMA public CASCADE"))
conn.execute(text("CREATE SCHEMA public"))
print("database reset complete")
def run_migrations():
engine = _get_engine()
# migrate.py now lives directly in /app
root = Path(__file__).resolve().parent
mig = root / "ops" / "compose" / "migrations"
sql_files = sorted(mig.glob("*.sql"))
if not sql_files:
print("no migrations found")
return
with engine.begin() as conn:
for p in sql_files:
sql = p.read_text(encoding="utf-8").strip()
if not sql:
continue
try:
conn.execute(text(sql))
print("applied", p.name)
except Exception as e:
# migrations are intentionally idempotent-ish
print("warn", p.name, "->", e)
def main():
"""
Usage:
python -m migrate # run migrations
python -m migrate reset # DROP + recreate schema, then exit
"""
if len(sys.argv) > 1 and sys.argv[1] == "reset":
reset_db()
return
run_migrations()
if __name__ == "__main__":
main()