Download backend/app/storage/database.py from deeep-sec/campus-placement-engine: direct link, hf CLI and curl.
- Browser
- Download file 1.53 kB
-
https://huggingface.co/deeep-sec/campus-placement-engine/resolve/main/backend/app/storage/database.py
- Command line
-
hf download hf://deeep-sec/campus-placement-engine/backend/app/storage/database.py
-
curl -L -o database.py https://huggingface.co/deeep-sec/campus-placement-engine/resolve/main/backend/app/storage/database.py
1.53 kB
| """ | |
| Database connection and session management. | |
| Ensures SQLite WAL mode and foreign key constraint enforcement. | |
| """ | |
| import os | |
| from collections.abc import Generator | |
| from sqlalchemy import create_engine, event | |
| from sqlalchemy.engine import Engine | |
| from sqlalchemy.orm import DeclarativeBase, Session, sessionmaker | |
| DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./placement_engine.db") | |
| # For SQLite, ensure connection arguments for multithreading | |
| connect_args = {} | |
| if DATABASE_URL.startswith("sqlite"): | |
| connect_args = {"check_same_thread": False} | |
| engine = create_engine( | |
| DATABASE_URL, | |
| connect_args=connect_args, | |
| echo=os.getenv("DEBUG", "false").lower() == "true", | |
| ) | |
| # SQLite PRAGMA configuration: WAL mode, foreign keys, synchronous normal | |
| def set_sqlite_pragma(dbapi_connection: object, connection_record: object) -> None: | |
| # Check if SQLite connection | |
| if hasattr(dbapi_connection, "cursor"): | |
| cursor = dbapi_connection.cursor() | |
| cursor.execute("PRAGMA foreign_keys=ON") | |
| cursor.execute("PRAGMA journal_mode=WAL") | |
| cursor.execute("PRAGMA synchronous=NORMAL") | |
| cursor.close() | |
| SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | |
| class Base(DeclarativeBase): | |
| pass | |
| def get_db() -> Generator[Session, None, None]: | |
| """Dependency for API route handlers.""" | |
| db = SessionLocal() | |
| try: | |
| yield db | |
| finally: | |
| db.close() | |