{"record":{"id":"e814f371d047fab7","repo":"BigPizzaV3/CodexPlusPlus","slug":"restore-conflict-table-row-already-exists","errorCode":null,"errorMessage":"restore conflict: {table} row already exists","messagePattern":"restore conflict: (.+?) row already exists","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"crates/codex-plus-data/src/storage.rs","lineNumber":1115,"sourceCode":"        }\n    }\n    Ok(())\n}\n\nfn detect_restore_conflicts(db: &Connection, tables: &Map<String, Value>) -> anyhow::Result<()> {\n    for (table, rows) in tables {\n        if table.starts_with(\"__\") {\n            continue;\n        }\n        let Some(rows) = rows.as_array() else {\n            continue;\n        };\n        for row in rows {\n            let Some(row) = row.as_object() else {\n                continue;\n            };\n            if restore_row_conflicts(db, table, row)? {\n                anyhow::bail!(\"restore conflict: {table} row already exists\");\n            }\n        }\n    }\n    Ok(())\n}\n\nfn restore_row_conflicts(\n    db: &Connection,\n    table: &str,\n    row: &Map<String, Value>,\n) -> anyhow::Result<bool> {\n    let key_columns = restore_conflict_key_columns(table, row);\n    if key_columns.is_empty() || !has_table(db, table)? {\n        return Ok(false);\n    }\n    let where_clause = key_columns\n        .iter()\n        .enumerate()","sourceCodeStart":1097,"sourceCodeEnd":1133,"githubUrl":"https://github.com/BigPizzaV3/CodexPlusPlus/blob/b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6/crates/codex-plus-data/src/storage.rs#L1097-L1133","documentation":"detect_restore_conflicts pre-flights every row of a restore payload against the live database; if restore_row_conflicts finds an existing row with the same key (and conflicting content), it bails before any restore is applied. Restore is intentionally non-destructive: it refuses to overwrite existing rows instead of silently clobbering live data.","triggerScenarios":"Calling restore_backups when the target DB already contains a row matching a backup row's primary key (e.g. same thread/session id) — the row already exists, so restoring would duplicate or overwrite it.","commonSituations":"Running undo/restore twice (second run sees rows restored by the first); the deleted thread still exists in the DB so undoing its deletion collides; other threads/databases sharing rows across grouped restores (preflight detects the conflict in a later DB).","solutions":["Delete or dedupe the conflicting rows from the target DB first, or verify the row content matches and skip it in the payload.","Don't run the same restore/undo twice; track completed tokens in your undo history.","Filter the backup's tables/rows to exclude ids that already exist in the live DB before calling restore_backups.","If the intent is overwrite, remove the existing rows (or truncate the table) explicitly within a transaction, then restore."],"exampleFix":"// before\nstorage.restore_backups(&backup)?; // thread id \"abc\" already exists in threads table\n// after\nlet existing: Vec<String> = load_existing_thread_ids(&db_path)?;\nlet backup = filter_backup_rows(&backup, |table, row| {\n    let id = row[\"id\"].as_str().unwrap_or_default();\n    !(table == \"threads\" && existing.iter().any(|e| e == id))\n});\nstorage.restore_backups(&backup)?;","handlingStrategy":"validation","validationCode":"for (table, rows) in backup[\"tables\"].as_object().unwrap() {\n    for row in rows.as_array().unwrap_or(&vec![]) {\n        if row_exists(&db_path, table, row)? {\n            anyhow::bail!(\"pre-check: {table} row already exists; dedupe or remove before restore\");\n        }\n    }\n}","typeGuard":"fn restore_is_clean(db: &Connection, backup: &Value) -> bool {\n    detect_restore_conflicts(db, backup[\"tables\"].as_object().unwrap_or(&Map::new())).is_ok()\n}","tryCatchPattern":"match storage.restore_backups(&backup) {\n    Ok(()) => {}\n    Err(e) if e.to_string().contains(\"row already exists\") => {\n        eprintln!(\"{e}; skipping rows already present (restore is non-destructive)\");\n        let filtered = remove_conflicting_rows(&backup, &db_path)?;\n        storage.restore_backups(&filtered)?;\n    }\n    Err(e) => return Err(e),\n}","preventionTips":["Mark undo/restore tokens as consumed so the same backup is never applied twice","Pre-check row ids against the live DB and filter out already-present rows","Remember restore never overwrites: delete existing rows explicitly if overwrite is intended","Verify a delete actually removed DB rows before undoing it, otherwise restore will collide"],"tags":["sqlite","conflict","restore","duplicate"],"backgroundTag":"file-already-exists","analyzedSha":"b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6","analyzedAt":"2026-09-19T23:35:21.129Z","contentChangedAt":"2026-09-19T23:35:21.129Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}