expression

rusqlite: classify a database constraint error

Use structured driver errors rather than matching localized error strings. A uniqueness failure belongs to the constraint category; other failures need their own policy. A broad constraint code does not by itself identify the exact rule that failed. Run in the accompanying Cargo project. Expected stdout (not executed): constraint: true Common mistake: Retrying a duplicate insert without changing its input.

Formal Syntax & Structure

rust syntaxrust
matches!(err, Error::SqliteFailure(code, _) if code.code == ErrorCode::ConstraintViolation)

Working Example

Example Snippetrust
fn main() -> Result<(), Box<dyn std::error::Error>> {    use rusqlite::{Connection, Error, ErrorCode};    let db = Connection::open_in_memory()?;    db.execute_batch("CREATE TABLE item (name TEXT UNIQUE); INSERT INTO item VALUES ('Pen');")?;    let result = db.execute("INSERT INTO item VALUES ('Pen')", []);    let constraint = matches!(result, Err(Error::SqliteFailure(code, _)) if code.code == ErrorCode::ConstraintViolation);    println!("constraint: {constraint}");    Ok(())}
Rust Reference