45 lines
1.4 KiB
Rust
45 lines
1.4 KiB
Rust
// error
|
|
#[derive(thiserror::Error)]
|
|
// the rest
|
|
#[derive(Debug)]
|
|
pub enum Error {
|
|
#[error("Unique constraint on primary key")]
|
|
UniqueConstraintPrimaryKey,
|
|
|
|
#[error("Unique constraint on key {0}")]
|
|
UniqueConstraint(String),
|
|
|
|
#[error("{0}")]
|
|
Database(#[from] sqlx::Error),
|
|
}
|
|
|
|
fn parse_unique_constraint(msg: &str) -> Option<String> {
|
|
// Format will be "table.column"
|
|
let mut constraint = msg.strip_prefix("UNIQUE constraint failed: ")?.split('.');
|
|
|
|
// Extract "column" (which is the second value)
|
|
let _table = constraint.next()?;
|
|
let column = constraint.next()?;
|
|
|
|
Some(column.to_string())
|
|
}
|
|
|
|
pub fn handle_error(e: sqlx::Error) -> Error {
|
|
match e.as_database_error() {
|
|
Some(database_error) => match database_error.code() {
|
|
// List of all codes: https://www.sqlite.org/rescode.html
|
|
Some(code) => match code.as_ref() {
|
|
"1555" => Error::UniqueConstraintPrimaryKey,
|
|
|
|
// Attempt to extract unique constraint column
|
|
"2067" => match parse_unique_constraint(database_error.message()) {
|
|
Some(column) => Error::UniqueConstraint(column),
|
|
None => Error::Database(e),
|
|
},
|
|
_ => Error::Database(e),
|
|
},
|
|
None => Error::Database(e),
|
|
},
|
|
None => Error::Database(e),
|
|
}
|
|
}
|