mirror of
https://github.com/launchbadge/sqlx.git
synced 2026-03-19 08:39:44 +00:00
Add constraint method to DatabaseError trait
Override `constraint` method for `PgDatabaseError`.
This commit is contained in:
committed by
Ryan Leckey
parent
d5e0f1b92b
commit
68cf2f9cdb
@@ -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(())
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user