1use sqlx::error::DatabaseError;
2
3use crate::DbErr;
4
5pub trait DatabaseErrorExt {
8 fn is_error_code(&self, error_code: &str) -> bool;
9
10 fn is_database_does_not_exist(&self) -> bool;
11
12 fn is_database_exists(&self) -> bool;
13
14 fn is_table_does_not_exist(&self) -> bool;
15
16 fn is_duplicate_record(&self) -> bool;
17
18 fn is_restrict(&self) -> bool;
19}
20
21impl DatabaseErrorExt for &dyn DatabaseError {
22 fn is_error_code(&self, error_code: &str) -> bool {
23 self.code()
24 .is_some_and(|code| code.to_string().eq(error_code))
25 }
26
27 fn is_database_does_not_exist(&self) -> bool {
28 self.is_error_code("3D000" )
29 }
30
31 fn is_database_exists(&self) -> bool {
32 self.is_error_code("42P04" )
33 }
34
35 fn is_table_does_not_exist(&self) -> bool {
36 self.is_error_code("42P01" )
37 }
38
39 fn is_duplicate_record(&self) -> bool {
40 self.is_unique_violation()
41 }
42
43 fn is_restrict(&self) -> bool {
44 self.is_error_code("23001" )
45 }
46}
47
48impl DatabaseErrorExt for DbErr {
49 fn is_error_code(&self, error_code: &str) -> bool {
50 self.as_database_error()
51 .is_some_and(|error| error.is_error_code(error_code))
52 }
53
54 fn is_database_does_not_exist(&self) -> bool {
55 self.as_database_error()
56 .is_some_and(|error| error.is_database_does_not_exist())
57 }
58
59 fn is_database_exists(&self) -> bool {
60 self.as_database_error()
61 .is_some_and(|error| error.is_database_exists())
62 }
63
64 fn is_table_does_not_exist(&self) -> bool {
65 self.as_database_error()
66 .is_some_and(|error| error.is_table_does_not_exist())
67 }
68
69 fn is_duplicate_record(&self) -> bool {
70 self.as_database_error()
71 .is_some_and(|error| error.is_duplicate_record())
72 }
73
74 fn is_restrict(&self) -> bool {
75 self.as_database_error()
76 .is_some_and(|error| error.is_restrict())
77 }
78}
79
80macro_rules! update_if_some {
81 ($self:expr, $($field:ident),+ $(,)?) => {
82 $(
83 if let Some(value) = $field {
84 $self.$field = value;
85 }
86 )+
87 };
88}
89
90pub(crate) use update_if_some;