From f539c604d6ec97d6693aed39e68227224ae5d06e Mon Sep 17 00:00:00 2001 From: Admin MPCZ Date: Thu, 7 May 2026 19:37:44 +0200 Subject: [PATCH] fix(planning_import): RETURNING id au lieu de lastval() (FK violation patch_planning_import_rows_import_id_fkey) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lastval() retourne la derniere valeur de sequence de la session — si un trigger sur patch_planning_imports bumpe une autre sequence (ex: audit log), lastval() retourne la mauvaise valeur. Resultat: import_id pointe vers un ID inexistant et les INSERT sur patch_planning_import_rows echouent en FK violation. Fix: INSERT ... RETURNING id qui est sans ambiguite, et early-return si NULL. --- app/routers/planning_import.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/app/routers/planning_import.py b/app/routers/planning_import.py index 7c438a2..9057827 100644 --- a/app/routers/planning_import.py +++ b/app/routers/planning_import.py @@ -490,13 +490,15 @@ async def import_upload(request: Request, db=Depends(get_db), year_match = re.search(r"(20\d{2})", fname) year = int(year_match.group(1)) if year_match else None - # Insert header - db.execute(text(""" + # Insert header (RETURNING id : evite le bug lastval() pollué par triggers) + import_id = db.execute(text(""" INSERT INTO patch_planning_imports (filename, year, sheet_count, row_count, uploaded_by, note) VALUES (:fn, :y, 0, 0, :uid, :nt) - """), {"fn": fname, "y": year, "uid": user.get("uid"), "nt": note or None}) + RETURNING id + """), {"fn": fname, "y": year, "uid": user.get("uid"), "nt": note or None}).scalar() db.commit() - import_id = db.execute(text("SELECT lastval()")).scalar() + if not import_id: + return RedirectResponse(url="/patching/import?err=insert_header", status_code=303) sheet_count = 0 row_count = 0