expression
SQLite: handle a deferred foreign-key failure at commit
Deferred constraints can allow temporary inconsistency inside a transaction. The database checks the relationship when the outer transaction commits. Always enable foreign-key checks before beginning the transaction and inspect commit errors, not only statement errors. Run in the accompanying Cargo project. Expected stdout (not executed): inserted: 1; commit failed: true Common mistake: Reporting success before commit returns successfully.
Formal Syntax & Structure
rust syntaxrust
REFERENCES parent(id) DEFERRABLE INITIALLY DEFERREDWorking Example
Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut db = rusqlite::Connection::open_in_memory()?; db.execute_batch("PRAGMA foreign_keys = ON; CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE child (pid INTEGER REFERENCES parent(id) DEFERRABLE INITIALLY DEFERRED);")?; let tx = db.transaction()?; let inserted = tx.execute("INSERT INTO child VALUES (7)", [])?; let failed = tx.commit().is_err(); println!("inserted: {inserted}; commit failed: {failed}"); Ok(())}