MalwareGuard / backend /app /database.py
Codex
Fix Clerk account recovery and tier safety
34bbf1b
Raw History Blame Contribute Delete
2.18 kB
"""Database session and schema initialization."""
from pathlib import Path
from sqlalchemy import create_engine, inspect, text
from sqlalchemy.orm import declarative_base, sessionmaker
from .config import settings
def _database_url() -> str:
url = settings.database_url.strip()
if not url:
# Hugging Face mounts persistent Space storage at /data. Falling back
# to the container working directory is safe for local development,
# but intentionally visible in production logs because it is ephemeral.
if settings.is_production and Path("/data").is_dir():
url = "sqlite:////data/malwareguard.db"
else:
url = "sqlite:///./malwareguard.db"
if url.startswith("postgres://"):
return url.replace("postgres://", "postgresql://", 1)
return url
def database_is_ephemeral() -> bool:
"""Return whether the configured SQLite path will disappear on Space rebuilds."""
url = _database_url()
if not url.startswith("sqlite"):
return False
return "/data/" not in url.replace("\\", "/")
connect_args = {"check_same_thread": False} if _database_url().startswith("sqlite") else {}
engine = create_engine(_database_url(), connect_args=connect_args, pool_pre_ping=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base()
def init_db() -> None:
from . import db_models # noqa: F401
Base.metadata.create_all(bind=engine)
_apply_lightweight_migrations()
def _apply_lightweight_migrations() -> None:
inspector = inspect(engine)
if "users" not in inspector.get_table_names():
return
user_columns = {column["name"] for column in inspector.get_columns("users")}
with engine.begin() as connection:
if "clerk_user_id" not in user_columns:
connection.execute(text("ALTER TABLE users ADD COLUMN clerk_user_id VARCHAR(128)"))
connection.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS ix_users_clerk_user_id ON users (clerk_user_id)"))
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()