memleketmeselesi/mm_data/migrate.py
Mukan Erkin 2498e75594 init: memleketmeselesi platform — API + migrations
FastAPI + PostgreSQL 16. KYC, issue sistemi, permission/group yönetimi,
session yönetimi, API client auth (kışla kapısı), officials/persons CRUD.
Migration 0001–0013 dahil.
2026-04-27 23:06:59 +03:00

49 lines
1.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
"""
Migration runner — migrations/ dizinindeki SQL dosyalarını sırayla çalıştırır.
Hangi migration'ların çalıştığını schema_migrations tablosunda tutar.
"""
import os
import sys
import psycopg
from pathlib import Path
from dotenv import load_dotenv
load_dotenv(Path(__file__).parent.parent / ".env") # normal konum: new/.env
load_dotenv(Path(__file__).parent / ".env", override=False) # sunucu geçici konum
DSN = os.environ["DATABASE_URL"]
_base = Path(__file__).parent
MIGRATIONS_DIR = (_base.parent / "migrations") if (_base.parent / "migrations").exists() else (_base / "migrations")
def run():
with psycopg.connect(DSN) as conn:
conn.execute("""
CREATE TABLE IF NOT EXISTS schema_migrations (
filename TEXT PRIMARY KEY,
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
""")
conn.commit()
applied = {row[0] for row in conn.execute("SELECT filename FROM schema_migrations")}
files = sorted(f for f in MIGRATIONS_DIR.glob("*.sql") if f.name not in applied)
if not files:
print("Uygulanacak migration yok.")
return
for f in files:
print(f"{f.name} ...", end=" ", flush=True)
sql = f.read_text(encoding="utf-8")
conn.execute(sql)
conn.execute("INSERT INTO schema_migrations (filename) VALUES (%s)", (f.name,))
conn.commit()
print("OK")
if __name__ == "__main__":
run()