from contextlib import asynccontextmanager from fastapi import FastAPI from sqlalchemy import text from .logging import setup_logging from .database import engine from models.database_models import Base import logging logger = logging.getLogger(__name__) @asynccontextmanager async def lifespan(app: FastAPI): """Application lifespan events""" # Startup logger = setup_logging() # Configure logging first logger.info("Starting up ecommerce API") # Create tables Base.metadata.create_all(bind=engine) # Create indexes create_indexes() yield # Shutdown logger.info("Shutting down ecommerce API") def create_indexes(): """Create database indexes""" with engine.connect() as conn: try: # User indexes conn.execute(text("CREATE INDEX IF NOT EXISTS idx_user_email ON users(email)")) conn.execute(text("CREATE INDEX IF NOT EXISTS idx_user_username ON users(username)")) # Product indexes conn.execute(text("CREATE INDEX IF NOT EXISTS idx_product_gtin ON products(gtin)")) conn.execute(text("CREATE INDEX IF NOT EXISTS idx_product_marketplace ON products(marketplace)")) # Stock indexes conn.execute(text("CREATE INDEX IF NOT EXISTS idx_stock_gtin_location ON stock(gtin, location)")) conn.commit() logger.info("Database indexes created successfully") except Exception as e: logger.warning(f"Index creation warning: {e}")