59 lines
1.4 KiB
Python
59 lines
1.4 KiB
Python
import os
|
|
from pathlib import Path
|
|
from dotenv import load_dotenv
|
|
from sqlalchemy import create_engine, event
|
|
from sqlalchemy.orm import DeclarativeBase, sessionmaker
|
|
|
|
load_dotenv()
|
|
|
|
# Ensure data directory exists relative to project root
|
|
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
|
DATA_DIR = BASE_DIR / "data"
|
|
DATA_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
# Build absolute SQLite URI so it works regardless of process working directory
|
|
DEFAULT_DB_PATH = DATA_DIR / "onboarding.db"
|
|
env_db_url = os.getenv("DATABASE_URL")
|
|
|
|
if env_db_url and not env_db_url.startswith("sqlite:///./"):
|
|
DATABASE_URL = env_db_url
|
|
else:
|
|
# Use robust absolute path for SQLite
|
|
DATABASE_URL = f"sqlite:///{DEFAULT_DB_PATH.as_posix()}"
|
|
|
|
engine = create_engine(
|
|
DATABASE_URL,
|
|
connect_args={
|
|
"check_same_thread": False,
|
|
"timeout": 15,
|
|
},
|
|
)
|
|
|
|
@event.listens_for(engine, "connect")
|
|
def set_sqlite_pragmas(dbapi_connection, connection_record):
|
|
if "sqlite" in DATABASE_URL:
|
|
cursor = dbapi_connection.cursor()
|
|
cursor.execute("PRAGMA journal_mode=WAL;")
|
|
cursor.execute("PRAGMA busy_timeout=10000;")
|
|
cursor.execute("PRAGMA synchronous=NORMAL;")
|
|
cursor.close()
|
|
|
|
|
|
SessionLocal = sessionmaker(
|
|
bind=engine,
|
|
autoflush=False,
|
|
autocommit=False,
|
|
)
|
|
|
|
|
|
class Base(DeclarativeBase):
|
|
pass
|
|
|
|
|
|
def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
db.close()
|