expression

SQLite: enable foreign-key checks for a connection

Enable and verify foreign-key enforcement as part of connection initialization, before a transaction starts. A foreign key prevents an orphaned child record when enforcement is active. This example checks the setting; it does not rely on a build-specific default. Run in the accompanying Cargo project. Expected stdout (not executed): orphan rejected: true Common mistake: Assuming one connection enables enforcement for all connections.

Formal Syntax & Structure

rust syntaxrust
conn.execute_batch("PRAGMA foreign_keys = ON;")?

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    let db = rusqlite::Connection::open_in_memory()?;    db.execute_batch("PRAGMA foreign_keys = ON; CREATE TABLE parent (id INTEGER PRIMARY KEY); CREATE TABLE child (parent_id INTEGER REFERENCES parent(id));")?;    let enabled: i64 = db.query_row("PRAGMA foreign_keys", [], |r| r.get(0))?;    assert_eq!(enabled, 1);    let result = db.execute("INSERT INTO child VALUES (?1)", [99_i64]);    println!("orphan rejected: {}", result.is_err());    Ok(())}
Rust Reference