from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from pathlib import Path from app.config import database_path, ensure_data_layout, migrate_legacy_data # Persistent user database lives under data/ (see app.config). Resolve paths # and migrate any legacy app/database/work_tracker.db before opening SQLite. ensure_data_layout() migrate_legacy_data() # Keep SQLite anchored to the configured data root, independent of CWD. DATABASE_PATH: Path = database_path() DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True) # SQLAlchemy accepts an absolute SQLite URL in this form on Windows and Unix. DATABASE_URL = f"sqlite:///{DATABASE_PATH.as_posix()}" # Create engine engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False}) # Create session SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) # Base class for models Base = declarative_base() # Dependency to get database session def get_db(): db = SessionLocal() try: yield db finally: db.close()