diff --git a/backend/scripts/migrate_plant_varieties.py b/backend/scripts/migrate_plant_varieties.py index 22ee0ac..1e51560 100644 --- a/backend/scripts/migrate_plant_varieties.py +++ b/backend/scripts/migrate_plant_varieties.py @@ -8,84 +8,92 @@ import sqlite3 from datetime import datetime, timezone from pathlib import Path -DB_PATH = Path("data/jardin.db") +DB_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "jardin.db" def run(): + if not DB_PATH.exists(): + print(f"ERREUR : base de données introuvable : {DB_PATH}") + return conn = sqlite3.connect(DB_PATH) conn.row_factory = sqlite3.Row + try: + # 1. Créer plant_variety + conn.execute(""" + CREATE TABLE IF NOT EXISTS plant_variety ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + plant_id INTEGER NOT NULL REFERENCES plant(id) ON DELETE CASCADE, + variete TEXT, + tags TEXT, + notes_variete TEXT, + boutique_nom TEXT, + boutique_url TEXT, + prix_achat REAL, + date_achat TEXT, + poids TEXT, + dluo TEXT, + created_at TEXT DEFAULT (datetime('now')) + ) + """) + print("✓ Table plant_variety créée") - # 1. Créer plant_variety - conn.execute(""" - CREATE TABLE IF NOT EXISTS plant_variety ( - id INTEGER PRIMARY KEY AUTOINCREMENT, - plant_id INTEGER NOT NULL REFERENCES plant(id) ON DELETE CASCADE, - variete TEXT, - tags TEXT, - notes_variete TEXT, - boutique_nom TEXT, - boutique_url TEXT, - prix_achat REAL, - date_achat TEXT, - poids TEXT, - dluo TEXT, - created_at TEXT DEFAULT (datetime('now')) - ) - """) - print("✓ Table plant_variety créée") + # 2. Ajouter colonnes manquantes à plant + existing = [r[1] for r in conn.execute("PRAGMA table_info(plant)").fetchall()] + for col, typ in [("temp_germination", "TEXT"), ("temps_levee_j", "TEXT")]: + if col not in existing: + conn.execute(f"ALTER TABLE plant ADD COLUMN {col} {typ}") + print(f"✓ Colonne {col} ajoutée à plant") - # 2. Ajouter colonnes manquantes à plant - existing = [r[1] for r in conn.execute("PRAGMA table_info(plant)").fetchall()] - for col, typ in [("temp_germination", "TEXT"), ("temps_levee_j", "TEXT")]: - if col not in existing: - conn.execute(f"ALTER TABLE plant ADD COLUMN {col} {typ}") - print(f"✓ Colonne {col} ajoutée à plant") + # 3. Vérifier si déjà migré + count = conn.execute("SELECT COUNT(*) FROM plant_variety").fetchone()[0] + if count > 0: + print(f"⚠️ Migration déjà effectuée ({count} variétés). Abandon.") + return - # 3. Vérifier si déjà migré - count = conn.execute("SELECT COUNT(*) FROM plant_variety").fetchone()[0] - if count > 0: - print(f"⚠️ Migration déjà effectuée ({count} variétés). Abandon.") + # 4. Migrer chaque plante → plant_variety + plants = conn.execute( + "SELECT id, nom_commun, variete, tags, boutique_nom, boutique_url, " + "prix_achat, date_achat, poids, dluo FROM plant" + ).fetchall() + + for p in plants: + conn.execute(""" + INSERT INTO plant_variety + (plant_id, variete, tags, boutique_nom, boutique_url, + prix_achat, date_achat, poids, dluo, created_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, ( + p["id"], p["variete"], p["tags"], p["boutique_nom"], p["boutique_url"], + p["prix_achat"], p["date_achat"], p["poids"], p["dluo"], + datetime.now(timezone.utc).isoformat(), + )) + print(f" → plant id={p['id']} {p['nom_commun']} : variété '{p['variete']}'") + + # 5. Fusionner haricot grimpant (id=21) sous Haricot (id=7) + # IDs stables dans le seed de production : Haricot=7, haricot grimpant=21 + hg = conn.execute("SELECT * FROM plant WHERE id = 21").fetchone() + if hg: + # Supprimer la plant_variety créée pour id=21 (on va la recréer sous id=7) + conn.execute("DELETE FROM plant_variety WHERE plant_id = 21") + # Créer variété sous Haricot (id=7) + conn.execute(""" + INSERT INTO plant_variety (plant_id, variete, notes_variete, created_at) + VALUES (7, 'Grimpant Neckarkönigin', 'Fusionné depuis haricot grimpant', ?) + """, (datetime.now(timezone.utc).isoformat(),)) + new_vid = conn.execute("SELECT last_insert_rowid()").fetchone()[0] + print(f" → haricot grimpant fusionné sous Haricot (plant_variety id={new_vid})") + # Supprimer le plant haricot grimpant + conn.execute("DELETE FROM plant WHERE id = 21") + print(" → plant id=21 (haricot grimpant) supprimé") + + conn.commit() + print("\nMigration terminée avec succès.") + except Exception as e: + conn.rollback() + print(f"ERREUR — rollback effectué : {e}") + raise + finally: conn.close() - return - - # 4. Migrer chaque plante → plant_variety - plants = conn.execute( - "SELECT id, nom_commun, variete, tags, boutique_nom, boutique_url, " - "prix_achat, date_achat, poids, dluo FROM plant" - ).fetchall() - - for p in plants: - conn.execute(""" - INSERT INTO plant_variety - (plant_id, variete, tags, boutique_nom, boutique_url, - prix_achat, date_achat, poids, dluo, created_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - """, ( - p["id"], p["variete"], p["tags"], p["boutique_nom"], p["boutique_url"], - p["prix_achat"], p["date_achat"], p["poids"], p["dluo"], - datetime.now(timezone.utc).isoformat(), - )) - print(f" → plant id={p['id']} {p['nom_commun']} : variété '{p['variete']}'") - - # 5. Fusionner haricot grimpant (id=21) sous Haricot (id=7) - hg = conn.execute("SELECT * FROM plant WHERE id = 21").fetchone() - if hg: - # Supprimer la plant_variety créée pour id=21 (on va la recréer sous id=7) - conn.execute("DELETE FROM plant_variety WHERE plant_id = 21") - # Créer variété sous Haricot (id=7) - conn.execute(""" - INSERT INTO plant_variety (plant_id, variete, notes_variete, created_at) - VALUES (7, 'Grimpant Neckarkönigin', 'Fusionné depuis haricot grimpant', ?) - """, (datetime.now(timezone.utc).isoformat(),)) - new_vid = conn.execute("SELECT last_insert_rowid()").fetchone()[0] - print(f" → haricot grimpant fusionné sous Haricot (plant_variety id={new_vid})") - # Supprimer le plant haricot grimpant - conn.execute("DELETE FROM plant WHERE id = 21") - print(" → plant id=21 (haricot grimpant) supprimé") - - conn.commit() - conn.close() - print("\nMigration terminée avec succès.") if __name__ == "__main__":