Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add constraint method to DatabaseError trait #998

Merged
merged 1 commit into from
Jan 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions sqlx-core/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,15 @@ pub trait DatabaseError: 'static + Send + Sync + StdError {

#[doc(hidden)]
fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;

/// Returns the name of the constraint that triggered the error, if applicable.
/// If the error was caused by a conflict of a unique index, this will be the index name.
///
/// ### Note
/// Currently only populated by the Postgres driver.
fn constraint(&self) -> Option<&str> {
None
}
}

impl dyn DatabaseError {
Expand Down
4 changes: 4 additions & 0 deletions sqlx-core/src/postgres/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,4 +184,8 @@ impl DatabaseError for PgDatabaseError {
fn into_error(self: Box<Self>) -> Box<dyn Error + Send + Sync + 'static> {
self
}

fn constraint(&self) -> Option<&str> {
self.constraint()
}
}
36 changes: 36 additions & 0 deletions tests/postgres/postgres.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,42 @@ async fn it_can_inspect_errors() -> anyhow::Result<()> {
assert_eq!(err.code(), "42703");
assert_eq!(err.position(), Some(PgErrorPosition::Original(8)));
assert_eq!(err.routine(), Some("errorMissingColumn"));
assert_eq!(err.constraint(), None);

Ok(())
}

#[sqlx_macros::test]
async fn it_can_inspect_constraint_errors() -> anyhow::Result<()> {
let mut conn = new::<Postgres>().await?;

let res: Result<_, sqlx::Error> =
sqlx::query("INSERT INTO products VALUES (1, 'Product 1', 0);")
.execute(&mut conn)
.await;
let err = res.unwrap_err();

// can also do [as_database_error] or use `match ..`
let err = err.into_database_error().unwrap();

assert_eq!(
err.message(),
"new row for relation \"products\" violates check constraint \"products_price_check\""
);
assert_eq!(err.code().as_deref(), Some("23514"));

// can also do [downcast_ref]
let err: Box<PgDatabaseError> = err.downcast();

assert_eq!(err.severity(), PgSeverity::Error);
assert_eq!(
err.message(),
"new row for relation \"products\" violates check constraint \"products_price_check\""
);
assert_eq!(err.code(), "23514");
assert_eq!(err.position(), None);
assert_eq!(err.routine(), Some("ExecConstraints"));
assert_eq!(err.constraint(), Some("products_price_check"));

Ok(())
}
Expand Down
6 changes: 6 additions & 0 deletions tests/postgres/setup.sql
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,9 @@ CREATE TYPE float_range AS RANGE
subtype = float8,
subtype_diff = float8mi
);

CREATE TABLE products (
product_no INTEGER,
name TEXT,
price NUMERIC CHECK (price > 0)
);