pub fn interpret(err: &Error) -> Option<String>
Expand description
Interpret an rusqlite::Error
into a String
.
use rusqlite::Connection;
use sqlite_err_parser::{register_interpreter, InterpretedError, interpret};
fn stringify(ie: &InterpretedError) -> Option<String> {
match ie {
InterpretedError::NotUnique(ids) => match ids.as_slice() {
[("testtbl1", "id")] => Some("id already exists".into()),
[("testtbl1", "name")] => Some("name already exists".into()),
[("testtbl2", "name1"), ("testtbl2", "name2")] => {
Some("name pair already exists".into())
}
_ => None
},
InterpretedError::Check(rule) => None,
_ => None
}
}
// Register translator function.
register_interpreter(stringify);
// Open and initialize database
let conn = Connection::open_in_memory().unwrap();
conn
.execute("CREATE TABLE IF NOT EXISTS testtbl1 (
id INTEGER PRIMARY KEY,
name TEXT UNIQUE NOT NULL
);", []).unwrap();
conn
.execute("CREATE TABLE IF NOT EXISTS testtbl2 (
id INTEGER PRIMARY KEY,
name1 TEXT NOT NULL,
name2 TEXT NOT NULL,
UNIQUE(name1, name2)
);", []).unwrap();
// Populate with some test data
conn.execute(
"INSERT INTO testtbl1 (id, name) VALUES (1, 'frank');", []
).unwrap();
conn.execute(
"INSERT INTO testtbl2 (id, name1, name2) VALUES (1, 'bill', 'frank');",
[]
).unwrap();
// testtbl1.id uniqueness violation
let err = conn.execute(
"INSERT INTO testtbl1 (id, name) VALUES (1, 'bill');", []
).unwrap_err();
assert_eq!(interpret(&err), Some("id already exists".into()));
// testtbl1.name uniqueness violation
let err = conn.execute(
"INSERT INTO testtbl1 (name) VALUES ('frank');", []
).unwrap_err();
assert_eq!(interpret(&err), Some("name already exists".into()));
// (testtbl2.name1, testtbl2.name2) uniqueness violation
let err = conn.execute(
"INSERT INTO testtbl2 (name1, name2) VALUES ('bill', 'frank');", []
).unwrap_err();
assert_eq!(interpret(&err), Some("name pair already exists".into()));