58 lines
1.9 KiB
Python
58 lines
1.9 KiB
Python
import os
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
import psycopg
|
|
|
|
def get_dsn():
|
|
file_path = os.environ.get("DATABASE_URL_FILE")
|
|
if file_path and os.path.exists(file_path):
|
|
return Path(file_path).read_text().strip()
|
|
return os.environ.get("DATABASE_URL")
|
|
|
|
def main():
|
|
dsn = get_dsn()
|
|
if not dsn:
|
|
print("ERROR: DATABASE_URL or DATABASE_URL_FILE not set", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
for i in range(10):
|
|
try:
|
|
with psycopg.connect(dsn, autocommit=True) as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("SELECT 1")
|
|
break
|
|
except psycopg.OperationalError:
|
|
print("Waiting for database...")
|
|
time.sleep(2)
|
|
else:
|
|
print("ERROR: Database is not ready", file=sys.stderr)
|
|
sys.exit(1)
|
|
|
|
# ВАЖНО: путь к миграциям. Раз они лежат в src/migrations:
|
|
migrations_dir = Path(__file__).parent.parent / "src" / "migrations"
|
|
sql_files = sorted(migrations_dir.glob("*.sql"))
|
|
|
|
with psycopg.connect(dsn, autocommit=True) as conn:
|
|
with conn.cursor() as cur:
|
|
cur.execute("""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version text PRIMARY KEY,
|
|
applied_at timestamptz DEFAULT now()
|
|
)
|
|
""")
|
|
|
|
for sql_file in sql_files:
|
|
version = sql_file.name
|
|
cur.execute("SELECT 1 FROM schema_migrations WHERE version = %s", (version,))
|
|
if cur.fetchone():
|
|
continue
|
|
|
|
print(f"Applying {version}...")
|
|
sql = sql_file.read_text(encoding="utf-8")
|
|
cur.execute(sql)
|
|
cur.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,))
|
|
print(f"Applied {version}.")
|
|
|
|
if __name__ == "__main__":
|
|
main() |