File size: 2,184 Bytes
34bbf1b
 
 
 
 
d6ddebe
 
 
 
 
34bbf1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d6ddebe
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()