| 1 | use sqlx::{error::ErrorKind, postgres::Postgres, Connection}; |
| 2 | use sqlx_test::new; |
| 3 | |
| 4 | #[sqlx_macros::test] |
| 5 | async fn it_fails_with_unique_violation() -> anyhow::Result<()> { |
| 6 | let mut conn = new::<Postgres>().await?; |
| 7 | let mut tx = conn.begin().await?; |
| 8 | |
| 9 | sqlx::query("INSERT INTO tweet(id, text, owner_id) VALUES (1, 'Foo', 1);") |
| 10 | .execute(&mut *tx) |
| 11 | .await?; |
| 12 | |
| 13 | let res: Result<_, sqlx::Error> = sqlx::query("INSERT INTO tweet VALUES (1, NOW(), 'Foo', 1);") |
| 14 | .execute(&mut *tx) |
| 15 | .await; |
| 16 | let err = res.unwrap_err(); |
| 17 | |
| 18 | let err = err.into_database_error().unwrap(); |
| 19 | |
| 20 | assert_eq!(err.kind(), ErrorKind::UniqueViolation); |
| 21 | |
| 22 | Ok(()) |
| 23 | } |
| 24 | |
| 25 | #[sqlx_macros::test] |
| 26 | async fn it_fails_with_foreign_key_violation() -> anyhow::Result<()> { |
| 27 | let mut conn = new::<Postgres>().await?; |
| 28 | let mut tx = conn.begin().await?; |
| 29 | |
| 30 | let res: Result<_, sqlx::Error> = |
| 31 | sqlx::query("INSERT INTO tweet_reply (tweet_id, text) VALUES (1, 'Reply!');") |
| 32 | .execute(&mut *tx) |
| 33 | .await; |
| 34 | let err = res.unwrap_err(); |
| 35 | |
| 36 | let err = err.into_database_error().unwrap(); |
| 37 | |
| 38 | assert_eq!(err.kind(), ErrorKind::ForeignKeyViolation); |
| 39 | |
| 40 | Ok(()) |
| 41 | } |
| 42 | |
| 43 | #[sqlx_macros::test] |
| 44 | async fn it_fails_with_not_null_violation() -> anyhow::Result<()> { |
| 45 | let mut conn = new::<Postgres>().await?; |
| 46 | let mut tx = conn.begin().await?; |
| 47 | |
| 48 | let res: Result<_, sqlx::Error> = sqlx::query("INSERT INTO tweet (text) VALUES (null);") |
| 49 | .execute(&mut *tx) |
| 50 | .await; |
| 51 | let err = res.unwrap_err(); |
| 52 | |
| 53 | let err = err.into_database_error().unwrap(); |
| 54 | |
| 55 | assert_eq!(err.kind(), ErrorKind::NotNullViolation); |
| 56 | |
| 57 | Ok(()) |
| 58 | } |
| 59 | |
| 60 | #[sqlx_macros::test] |
| 61 | async fn it_fails_with_check_violation() -> anyhow::Result<()> { |
| 62 | let mut conn = new::<Postgres>().await?; |
| 63 | let mut tx = conn.begin().await?; |
| 64 | |
| 65 | let res: Result<_, sqlx::Error> = |
| 66 | sqlx::query("INSERT INTO products VALUES (1, 'Product 1', 0);") |
| 67 | .execute(&mut *tx) |
| 68 | .await; |
| 69 | let err = res.unwrap_err(); |
| 70 | |
| 71 | let err = err.into_database_error().unwrap(); |
| 72 | |
| 73 | assert_eq!(err.kind(), ErrorKind::CheckViolation); |
| 74 | |
| 75 | Ok(()) |
| 76 | } |