forked from mtusi2026/mtusi2026lab4
116 lines
3.1 KiB
Python
116 lines
3.1 KiB
Python
from __future__ import annotations
|
|
|
|
import os
|
|
from contextlib import contextmanager
|
|
from pathlib import Path
|
|
from typing import Iterator, Optional
|
|
|
|
from sqlalchemy import create_engine, text
|
|
from sqlalchemy.engine import Engine
|
|
from sqlalchemy.orm import Session, sessionmaker
|
|
|
|
_engine: Optional[Engine] = None
|
|
_SessionLocal: Optional[sessionmaker[Session]] = None
|
|
|
|
|
|
def _read_database_url() -> str:
|
|
url_file = os.environ.get("DATABASE_URL_FILE")
|
|
if url_file:
|
|
url = Path(url_file).read_text(encoding="utf-8").strip()
|
|
else:
|
|
url = os.environ.get("DATABASE_URL")
|
|
if not url:
|
|
raise RuntimeError("DATABASE_URL or DATABASE_URL_FILE is required")
|
|
url = url.strip()
|
|
if url.startswith("postgresql://"):
|
|
url = "postgresql+psycopg://" + url[len("postgresql://") :]
|
|
elif url.startswith("postgres://"):
|
|
url = "postgresql+psycopg://" + url[len("postgres://") :]
|
|
return url
|
|
|
|
|
|
def init_engine() -> Engine:
|
|
global _engine, _SessionLocal
|
|
if _engine is not None:
|
|
return _engine
|
|
_engine = create_engine(
|
|
_read_database_url(),
|
|
pool_size=5,
|
|
max_overflow=5,
|
|
pool_pre_ping=True,
|
|
pool_timeout=10,
|
|
)
|
|
_SessionLocal = sessionmaker(bind=_engine, expire_on_commit=False)
|
|
return _engine
|
|
|
|
|
|
def get_engine() -> Engine:
|
|
if _engine is None:
|
|
raise RuntimeError("database engine is not initialized")
|
|
return _engine
|
|
|
|
|
|
@contextmanager
|
|
def session_scope() -> Iterator[Session]:
|
|
if _SessionLocal is None:
|
|
raise RuntimeError("database engine is not initialized")
|
|
session = _SessionLocal()
|
|
try:
|
|
yield session
|
|
session.commit()
|
|
except Exception:
|
|
session.rollback()
|
|
raise
|
|
finally:
|
|
session.close()
|
|
|
|
|
|
def close_engine() -> None:
|
|
global _engine, _SessionLocal
|
|
if _engine is not None:
|
|
_engine.dispose()
|
|
_engine = None
|
|
_SessionLocal = None
|
|
|
|
|
|
def migrations_dir() -> Path:
|
|
return Path(__file__).resolve().parents[2] / "migrations"
|
|
|
|
|
|
def apply_migrations() -> None:
|
|
engine = get_engine()
|
|
with engine.begin() as conn:
|
|
conn.execute(
|
|
text(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
version TEXT PRIMARY KEY,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)
|
|
"""
|
|
)
|
|
)
|
|
applied = {
|
|
row[0]
|
|
for row in conn.execute(text("SELECT version FROM schema_migrations")).fetchall()
|
|
}
|
|
for path in sorted(migrations_dir().glob("*.sql")):
|
|
version = path.name
|
|
if version in applied:
|
|
continue
|
|
conn.exec_driver_sql(path.read_text(encoding="utf-8"))
|
|
conn.execute(
|
|
text("INSERT INTO schema_migrations (version) VALUES (:version)"),
|
|
{"version": version},
|
|
)
|
|
|
|
|
|
def ping() -> bool:
|
|
try:
|
|
engine = get_engine()
|
|
with engine.connect() as conn:
|
|
conn.execute(text("SELECT 1"))
|
|
return True
|
|
except Exception:
|
|
return False
|