From c72a22a965c477bbe026a55fc71c863a4be66f8b Mon Sep 17 00:00:00 2001 From: 4aiman Date: Mon, 1 Jun 2026 22:43:02 +0300 Subject: [PATCH] Fix dedup FK: delete product_units refs before products, remove PRAGMA hack MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit FOREIGN KEY constraint failed because product_units table has FK to products(id) and wasn't cleaned before DELETE. Now: delete orphaned product_units rows first, then delete dupe products. No PRAGMA needed. Verified on desktop: 16675 → 8330 with FK enforcement ON. --- src-tauri/src/lib.rs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs index 6f4ae0f..f8e2a66 100644 --- a/src-tauri/src/lib.rs +++ b/src-tauri/src/lib.rs @@ -140,8 +140,6 @@ fn import_seed_products(app: tauri::AppHandle) -> Result { } // Dedup ALWAYS runs (even if seed version matches) — fixes legacy duplicates. - // Disable FK checks during dedup (refs reassigned before delete, but rusqlite enforces FK by default) - let _ = main_db.execute("PRAGMA foreign_keys = OFF", []); let _ = main_db.execute( "CREATE INDEX IF NOT EXISTS idx_products_name_lower ON products(name_lower)", []); @@ -168,6 +166,13 @@ fn import_seed_products(app: tauri::AppHandle) -> Result { GROUP BY name_lower, source, COALESCE(store_id,'') )", []).map_err(|e| format!("dedup recipe_ingredients: {}", e))?; + // Reassign product_units (also has FK to products) + main_db.execute( + "DELETE FROM product_units WHERE product_id NOT IN ( + SELECT MIN(id) FROM products WHERE name_lower IS NOT NULL + GROUP BY name_lower, source, COALESCE(store_id,'') + )", []).map_err(|e| format!("dedup product_units: {}", e))?; + main_db.execute( "DELETE FROM products WHERE name_lower IS NOT NULL AND id NOT IN ( @@ -180,8 +185,6 @@ fn import_seed_products(app: tauri::AppHandle) -> Result { ON products(name_lower, source, COALESCE(store_id, '')) WHERE name_lower IS NOT NULL", []); - let _ = main_db.execute("PRAGMA foreign_keys = ON", []); - // Check seed version — skip import if already up to date let current_version: i64 = main_db.query_row( "SELECT COALESCE((SELECT value FROM profile WHERE key='seed_version'), '0')",