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

Added enum for SQLx Error and basic functions for it #1707

Merged
merged 26 commits into from Jun 19, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
01d6050
Added enum for SQL Error and basic functions for it
darkmmon Jun 13, 2023
e973517
fmt
darkmmon Jun 13, 2023
6de76f9
Restructured code to allow multiple database system simultaneously
darkmmon Jun 14, 2023
fd337e1
updated code error and moved Eq to derive by compiler
darkmmon Jun 14, 2023
268c6f2
added ForeignKeyViolation implementation
darkmmon Jun 14, 2023
2230575
fmt
darkmmon Jun 14, 2023
015172c
added type param
darkmmon Jun 14, 2023
96201b8
changed type param and used unwrap_or_default instead of unwrap
darkmmon Jun 14, 2023
1d84145
fmt
darkmmon Jun 14, 2023
f19f28b
refactor code and update documentation
darkmmon Jun 14, 2023
90c109f
updated some error code and fixed formatting
darkmmon Jun 14, 2023
64b5176
create SQL Err test for UniqueConstraintViolation
darkmmon Jun 14, 2023
610a470
fmt
darkmmon Jun 14, 2023
bdd432f
updated error codes for mysql errors
darkmmon Jun 15, 2023
b693813
added test for ForeignKeyConstraintViolation and removed unused impor…
darkmmon Jun 15, 2023
acc9ed4
fmt
darkmmon Jun 15, 2023
96e566e
updated doc and error message
darkmmon Jun 15, 2023
df52415
added static str in SqlErr
darkmmon Jun 16, 2023
02dceff
changed to add error message into SqlErr as String
darkmmon Jun 16, 2023
5fb5128
updated test file to check database type through connection
darkmmon Jun 16, 2023
90279ae
fmt
darkmmon Jun 16, 2023
6fe8c5b
updated test for SqlErr to match the error type only
darkmmon Jun 19, 2023
ae8067f
Removed comment and fixed grammar mistake
darkmmon Jun 19, 2023
144976d
fmt
darkmmon Jun 19, 2023
da0660b
Update src/error.rs
tyt2y3 Jun 19, 2023
156e577
Refactoring
billy1624 Jun 19, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
41 changes: 31 additions & 10 deletions src/error.rs
Expand Up @@ -144,12 +144,13 @@ where
#[derive(Error, Debug, PartialEq, Eq)]
tyt2y3 marked this conversation as resolved.
Show resolved Hide resolved
#[non_exhaustive]
pub enum SqlErr {
// string stored in error is a placebo,
/// error for duplicate record in unique field or primary key field
#[error("Unique Constraint Violated")]
UniqueConstraintViolation,
#[error("Unique Constraint Violated: {0}")]
UniqueConstraintViolation(String),
/// error for Foreign key constraint
#[error("Foreign Key Constraint Violated")]
ForeignKeyConstraintViolation,
#[error("Foreign Key Constraint Violated: {0}")]
ForeignKeyConstraintViolation(String),
}

#[allow(dead_code)]
Expand Down Expand Up @@ -181,7 +182,9 @@ impl DbErr {
// 1169 Can't write, because of unique constraint, to table '%s'
// 1586 Duplicate entry '%s' for key '%s'
1022 | 1062 | 1169 | 1586 => {
return Some(SqlErr::UniqueConstraintViolation)
return Some(SqlErr::UniqueConstraintViolation(String::from(
e.message(),
)))
}
// 1216 Cannot add or update a child row: a foreign key constraint fails
// 1217 Cannot delete or update a parent row: a foreign key constraint fails
Expand All @@ -191,7 +194,9 @@ impl DbErr {
// 1761 Foreign key constraint for table '%s', record '%s' would lead to a duplicate entry in table '%s', key '%s'
// 1762 Foreign key constraint for table '%s', record '%s' would lead to a duplicate entry in a child table
1216 | 1217 | 1451 | 1452 | 1557 | 1761 | 1762 => {
return Some(SqlErr::ForeignKeyConstraintViolation)
return Some(SqlErr::ForeignKeyConstraintViolation(String::from(
e.message(),
)))
}
_ => return None,
}
Expand All @@ -201,8 +206,16 @@ impl DbErr {
.is_some()
{
match _error_code_expanded {
"23505" => return Some(SqlErr::UniqueConstraintViolation),
"23503" => return Some(SqlErr::ForeignKeyConstraintViolation),
"23505" => {
return Some(SqlErr::UniqueConstraintViolation(String::from(
e.message(),
)))
}
"23503" => {
return Some(SqlErr::ForeignKeyConstraintViolation(String::from(
e.message(),
)))
}
_ => return None,
}
}
Expand All @@ -211,8 +224,16 @@ impl DbErr {
match _error_code_expanded {
// error code 1555 refers to the primary key's unique constraint violation
// error code 2067 refers to the UNIQUE unique constraint violation
"1555" | "2067" => return Some(SqlErr::UniqueConstraintViolation),
"787" => return Some(SqlErr::ForeignKeyConstraintViolation),
"1555" | "2067" => {
return Some(SqlErr::UniqueConstraintViolation(String::from(
e.message(),
)))
}
"787" => {
return Some(SqlErr::ForeignKeyConstraintViolation(String::from(
e.message(),
)))
}
_ => return None,
}
}
Expand Down
33 changes: 30 additions & 3 deletions tests/sql_err_tests.rs
Expand Up @@ -2,7 +2,10 @@ pub mod common;
pub use common::{bakery_chain::*, setup::*, TestContext};
use pretty_assertions::assert_eq;
use rust_decimal_macros::dec;
pub use sea_orm::{entity::*, error::*, tests_cfg, DatabaseConnection, EntityName, ExecResult};
use sea_orm::ConnectionTrait;
pub use sea_orm::{
entity::*, error::*, tests_cfg, DatabaseConnection, DbBackend, EntityName, ExecResult,
};
use uuid::Uuid;

#[sea_orm_macros::test]
Expand Down Expand Up @@ -39,7 +42,21 @@ pub async fn test_error(db: &DatabaseConnection) {
.await
.expect_err("inserting should fail due to duplicate primary key");

assert_eq!(error.sql_err(), Some(SqlErr::UniqueConstraintViolation));
let mut error_message: &str = "";
if db.get_database_backend() == DbBackend::MySql {
error_message = "Duplicate entry '1' for key 'cake.PRIMARY'"
} else if db.get_database_backend() == DbBackend::Postgres {
error_message = "duplicate key value violates unique constraint \"cake_pkey\""
} else if db.get_database_backend() == DbBackend::Sqlite {
error_message = "UNIQUE constraint failed: cake.id"
}

assert_eq!(
error.sql_err(),
Some(SqlErr::UniqueConstraintViolation(String::from(
error_message
)))
);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The content is out of our control, so may be

assert!(matches!(error.sql_err(), Some(SqlErr::UniqueConstraintViolation(_)));

would suffice.


let fk_cake = cake::ActiveModel {
name: Set("fk error Cake".to_owned()),
Expand All @@ -55,8 +72,18 @@ pub async fn test_error(db: &DatabaseConnection) {
.await
.expect_err("create foreign key should fail with non-primary key");

if db.get_database_backend() == DbBackend::MySql {
error_message = "Cannot add or update a child row: a foreign key constraint fails (`bakery_chain_sql_err_tests`.`cake`, CONSTRAINT `fk-cake-bakery_id` FOREIGN KEY (`bakery_id`) REFERENCES `bakery` (`id`) ON DELETE CASCADE ON UPDATE CASCADE)"
} else if db.get_database_backend() == DbBackend::Postgres {
error_message = "insert or update on table \"cake\" violates foreign key constraint \"fk-cake-bakery_id\""
} else if db.get_database_backend() == DbBackend::Sqlite {
error_message = "FOREIGN KEY constraint failed"
}

assert_eq!(
fk_error.sql_err(),
Some(SqlErr::ForeignKeyConstraintViolation)
Some(SqlErr::ForeignKeyConstraintViolation(String::from(
error_message
)))
);
}