fix(plantes): script migration — try/except rollback + DB_PATH absolu + commentaires IDs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -8,84 +8,92 @@ import sqlite3
|
|||||||
from datetime import datetime, timezone
|
from datetime import datetime, timezone
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
DB_PATH = Path("data/jardin.db")
|
DB_PATH = Path(__file__).resolve().parent.parent.parent / "data" / "jardin.db"
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
|
if not DB_PATH.exists():
|
||||||
|
print(f"ERREUR : base de données introuvable : {DB_PATH}")
|
||||||
|
return
|
||||||
conn = sqlite3.connect(DB_PATH)
|
conn = sqlite3.connect(DB_PATH)
|
||||||
conn.row_factory = sqlite3.Row
|
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
|
# 2. Ajouter colonnes manquantes à plant
|
||||||
conn.execute("""
|
existing = [r[1] for r in conn.execute("PRAGMA table_info(plant)").fetchall()]
|
||||||
CREATE TABLE IF NOT EXISTS plant_variety (
|
for col, typ in [("temp_germination", "TEXT"), ("temps_levee_j", "TEXT")]:
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
if col not in existing:
|
||||||
plant_id INTEGER NOT NULL REFERENCES plant(id) ON DELETE CASCADE,
|
conn.execute(f"ALTER TABLE plant ADD COLUMN {col} {typ}")
|
||||||
variete TEXT,
|
print(f"✓ Colonne {col} ajoutée à plant")
|
||||||
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
|
# 3. Vérifier si déjà migré
|
||||||
existing = [r[1] for r in conn.execute("PRAGMA table_info(plant)").fetchall()]
|
count = conn.execute("SELECT COUNT(*) FROM plant_variety").fetchone()[0]
|
||||||
for col, typ in [("temp_germination", "TEXT"), ("temps_levee_j", "TEXT")]:
|
if count > 0:
|
||||||
if col not in existing:
|
print(f"⚠️ Migration déjà effectuée ({count} variétés). Abandon.")
|
||||||
conn.execute(f"ALTER TABLE plant ADD COLUMN {col} {typ}")
|
return
|
||||||
print(f"✓ Colonne {col} ajoutée à plant")
|
|
||||||
|
|
||||||
# 3. Vérifier si déjà migré
|
# 4. Migrer chaque plante → plant_variety
|
||||||
count = conn.execute("SELECT COUNT(*) FROM plant_variety").fetchone()[0]
|
plants = conn.execute(
|
||||||
if count > 0:
|
"SELECT id, nom_commun, variete, tags, boutique_nom, boutique_url, "
|
||||||
print(f"⚠️ Migration déjà effectuée ({count} variétés). Abandon.")
|
"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()
|
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__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Reference in New Issue
Block a user