""" Lance le seed uniquement si la table shopping.stores est vide. Usage : python -m app.data.seed """ import asyncio import json from pathlib import Path from sqlalchemy import select, text from sqlalchemy.exc import ProgrammingError from app.core.database import AsyncSessionLocal from app.models.shopping import Product, Store DATA_DIR = Path(__file__).parent async def run_seed() -> None: try: async with AsyncSessionLocal() as session: # Vérifier que la table existe avant de faire le seed try: result = await session.execute( text( "SELECT COUNT(*) FROM information_schema.tables " "WHERE table_schema = 'shopping' AND table_name = 'stores'" ) ) table_exists = result.scalar() > 0 except Exception: table_exists = False if not table_exists: print("Seed ignoré — les migrations Alembic n'ont pas encore été appliquées.") return count = await session.scalar(select(Store).limit(1)) if count is not None: print("Seed déjà chargé — rien à faire.") return stores_raw = json.loads((DATA_DIR / "seed_stores.json").read_text()) for s in stores_raw: session.add(Store(name=s["name"], location=s.get("location"))) products_raw = json.loads((DATA_DIR / "seed_products.json").read_text()) for p in products_raw: session.add(Product( name=p["name"], category=p.get("category"), default_unit=p.get("default_unit"), frequency_score=p.get("frequency_score", 0), )) await session.commit() print(f"Seed : {len(stores_raw)} magasins, {len(products_raw)} produits chargés.") except ProgrammingError as e: print(f"Seed ignoré — tables non disponibles (migrations requises) : {e}") if __name__ == "__main__": asyncio.run(run_seed())