sea-orm/tests/sql_err_tests.rs
darkmmon b37e7655f8
Added enum for SQLx Error and basic functions for it (#1707)
* Added enum for SQL Error and basic functions for it

* fmt

* Restructured code to allow multiple database system simultaneously

* updated code error and moved Eq to derive by compiler

* added ForeignKeyViolation implementation

* fmt

* added type param

* changed type param and used unwrap_or_default instead of unwrap

* fmt

* refactor code and update documentation

* updated some error code and fixed formatting

* create SQL Err test for UniqueConstraintViolation

* fmt

* updated error codes for mysql errors

* added test for ForeignKeyConstraintViolation and removed unused imports/codes

* fmt

* updated doc and error message

* added static str in SqlErr

* changed to add error message into SqlErr as String

* updated test file to check database type through connection

* fmt

* updated test for SqlErr to match the error type only

* Removed comment and fixed grammar mistake

* fmt

* Update src/error.rs

* Refactoring

---------

Co-authored-by: Chris Tsang <chris.2y3@outlook.com>
Co-authored-by: Billy Chan <ccw.billy.123@gmail.com>
2023-06-19 17:19:08 +08:00

68 lines
1.8 KiB
Rust

pub mod common;
pub use common::{bakery_chain::*, setup::*, TestContext};
use rust_decimal_macros::dec;
pub use sea_orm::{
entity::*, error::DbErr, error::SqlErr, tests_cfg, DatabaseConnection, DbBackend, EntityName,
ExecResult,
};
use uuid::Uuid;
#[sea_orm_macros::test]
#[cfg(any(
feature = "sqlx-mysql",
feature = "sqlx-sqlite",
feature = "sqlx-postgres"
))]
async fn main() {
let ctx = TestContext::new("bakery_chain_sql_err_tests").await;
create_tables(&ctx.db).await.unwrap();
test_error(&ctx.db).await;
ctx.delete().await;
}
pub async fn test_error(db: &DatabaseConnection) {
let mud_cake = cake::ActiveModel {
name: Set("Moldy Cake".to_owned()),
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(None),
..Default::default()
};
let cake = mud_cake.save(db).await.expect("could not insert cake");
// if compiling without sqlx, this assignment will complain,
// but the whole test is useless in that case anyway.
#[allow(unused_variables)]
let error: DbErr = cake
.into_active_model()
.insert(db)
.await
.expect_err("inserting should fail due to duplicate primary key");
assert!(matches!(
error.sql_err(),
Some(SqlErr::UniqueConstraintViolation(_))
));
let fk_cake = cake::ActiveModel {
name: Set("fk error Cake".to_owned()),
price: Set(dec!(10.25)),
gluten_free: Set(false),
serial: Set(Uuid::new_v4()),
bakery_id: Set(Some(1000)),
..Default::default()
};
let fk_error = fk_cake
.insert(db)
.await
.expect_err("create foreign key should fail with non-primary key");
assert!(matches!(
fk_error.sql_err(),
Some(SqlErr::ForeignKeyConstraintViolation(_))
));
}