2026-03-08 13:27:11 -04:00
|
|
|
import logging
|
|
|
|
|
from pathlib import Path
|
|
|
|
|
|
2026-03-02 11:46:40 -05:00
|
|
|
from sqlalchemy import create_engine
|
2026-03-08 13:27:11 -04:00
|
|
|
from sqlalchemy.exc import OperationalError
|
2026-03-02 11:46:40 -05:00
|
|
|
from sqlalchemy.ext.declarative import declarative_base
|
2026-03-08 12:50:44 -04:00
|
|
|
from sqlalchemy.orm import Session, sessionmaker
|
2026-03-02 11:46:40 -05:00
|
|
|
|
2026-03-08 13:27:11 -04:00
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2026-03-02 11:46:40 -05:00
|
|
|
SQLALCHEMY_DATABASE_URL = "sqlite:///./data/timmy_calm.db"
|
|
|
|
|
|
2026-03-08 13:27:11 -04:00
|
|
|
# Ensure the data directory exists before creating the engine
|
|
|
|
|
Path("./data").mkdir(parents=True, exist_ok=True)
|
|
|
|
|
|
2026-03-08 12:50:44 -04:00
|
|
|
engine = create_engine(SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False})
|
2026-03-02 11:46:40 -05:00
|
|
|
|
|
|
|
|
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
|
|
|
|
|
|
|
|
Base = declarative_base()
|
|
|
|
|
|
2026-03-08 12:50:44 -04:00
|
|
|
|
2026-03-07 23:21:30 -05:00
|
|
|
def create_tables():
|
2026-03-08 13:27:11 -04:00
|
|
|
"""Create all tables idempotently (safe under pytest-xdist concurrency)."""
|
|
|
|
|
try:
|
|
|
|
|
Base.metadata.create_all(bind=engine)
|
|
|
|
|
except OperationalError as exc:
|
|
|
|
|
logger.debug("Table creation skipped (already exists): %s", exc)
|
2026-03-07 23:21:30 -05:00
|
|
|
|
|
|
|
|
|
2026-03-02 11:46:40 -05:00
|
|
|
def get_db():
|
|
|
|
|
db = SessionLocal()
|
|
|
|
|
try:
|
|
|
|
|
yield db
|
|
|
|
|
finally:
|
|
|
|
|
db.close()
|