from __future__ import annotations from pathlib import Path from sqlalchemy import text from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine from .config import settings def _sqlite_url() -> str: db_path = Path(settings.sqlite_path) db_path.parent.mkdir(parents=True, exist_ok=True) return f"sqlite+aiosqlite:///{db_path}" engine = create_async_engine(_sqlite_url(), future=True) SessionLocal = async_sessionmaker(engine, expire_on_commit=False, class_=AsyncSession) async def get_session() -> AsyncSession: async with SessionLocal() as session: yield session async def run_migrations() -> None: statements = [ "ALTER TABLE products ADD COLUMN categoria TEXT DEFAULT ''", "ALTER TABLE products ADD COLUMN caducidad_estimada INTEGER DEFAULT 0", ] async with engine.begin() as conn: for statement in statements: try: await conn.execute(text(statement)) except Exception: pass