""" Database & Persistence Management for FastAPI (Capa 4 - SQLAlchemy 2.0 Nativo) Provides engine, SessionLocal, scoped_session, and declarative Base without any Flask dependency. """ import os import contextlib from typing import Generator, Any from sqlalchemy import ( create_engine, Column, Integer, String, Text, Boolean, DateTime, Date, Time, Float, ForeignKey, Table, and_, or_, not_, desc, asc, func, Index, UniqueConstraint ) from sqlalchemy.orm import declarative_base, scoped_session, sessionmaker, relationship, backref import sqlalchemy as sa from config.config import Config # 1. Configurar Engine y conexión db_url = Config.SQLALCHEMY_DATABASE_URI connect_args = {} if "sqlite" in db_url: connect_args["check_same_thread"] = False engine = create_engine( db_url, connect_args=connect_args, pool_pre_ping=True ) # 2. Sessionmaker y scoped_session nativo SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) session = scoped_session(SessionLocal) # 3. Base declarativa con query_property habilitado Base = declarative_base() Base.query = session.query_property() # 4. Wrapper compatible que emula la API de SQLAlchemy de Flask sin requerir Flask class SQLAlchemyWrapper: def __init__(self, target_engine, session_factory, base_class): self.engine = target_engine self.session = session_factory self.Model = base_class # Schema constructs & Types self.Column = Column self.Integer = Integer self.String = String self.Text = Text self.Boolean = Boolean self.DateTime = DateTime self.Date = Date self.Time = Time self.Float = Float self.ForeignKey = ForeignKey self.Index = Index self.UniqueConstraint = UniqueConstraint # Relationships self.relationship = relationship self.backref = backref # Operators & functions self.and_ = and_ self.or_ = or_ self.not_ = not_ self.desc = desc self.asc = asc self.func = func @property def metadata(self): return self.Model.metadata def Table(self, name, *args, **kwargs): from sqlalchemy import MetaData, Table as SaTable if len(args) == 0 or not isinstance(args[0], MetaData): return SaTable(name, self.metadata, *args, **kwargs) return SaTable(name, *args, **kwargs) def create_all(self, bind=None): target = bind or self.engine try: import app.models # noqa except Exception: pass self.Model.metadata.create_all(bind=target) def drop_all(self, bind=None): target = bind or self.engine try: import app.models # noqa except Exception: pass self.Model.metadata.drop_all(bind=target) def init_app(self, app=None): """No-op for legacy compatibility""" pass def __getattr__(self, name: str) -> Any: return getattr(sa, name) db = SQLAlchemyWrapper(engine, session, Base) def get_db() -> Generator[Any, None, None]: """ FastAPI dependency yielding a clean database session per request. """ db_session = SessionLocal() try: yield db_session finally: db_session.close() # Context manager dummy para compatibilidad transitoria class DummyAppContext: def __enter__(self): return self def __exit__(self, exc_type, exc_val, exc_tb): pass def push(self): pass def pop(self): pass class DummyApp: def __init__(self): self.config = { 'TESTING': False, 'SQLALCHEMY_DATABASE_URI': Config.SQLALCHEMY_DATABASE_URI, 'SECRET_KEY': Config.SECRET_KEY, 'LANGUAGES': Config.LANGUAGES } def app_context(self): return DummyAppContext() _dummy_app_instance = DummyApp() def get_flask_app(): """ Legacy helper: returns a harmless dummy context object to prevent breakages during incremental removal of with flask_app.app_context(). """ return _dummy_app_instance