|
6 | 6 |
|
7 | 7 | pub use diesel::{Connection, QueryResult}; |
8 | 8 | use diesel::RunQueryDsl; |
| 9 | +use std::fmt; |
| 10 | + |
| 11 | +/// 数据库连接错误类型 |
| 12 | +#[derive(Debug)] |
| 13 | +pub struct ConnectionError { |
| 14 | + pub message: String, |
| 15 | + pub source: Option<Box<dyn std::error::Error + Send + Sync>>, |
| 16 | +} |
| 17 | + |
| 18 | +impl fmt::Display for ConnectionError { |
| 19 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 20 | + write!(f, "{}", self.message) |
| 21 | + } |
| 22 | +} |
| 23 | + |
| 24 | +impl std::error::Error for ConnectionError { |
| 25 | + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { |
| 26 | + self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static)) |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +impl ConnectionError { |
| 31 | + pub fn new(message: &str) -> Self { |
| 32 | + ConnectionError { |
| 33 | + message: message.to_string(), |
| 34 | + source: None, |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + pub fn with_source(message: &str, source: Box<dyn std::error::Error + Send + Sync>) -> Self { |
| 39 | + ConnectionError { |
| 40 | + message: message.to_string(), |
| 41 | + source: Some(source), |
| 42 | + } |
| 43 | + } |
| 44 | +} |
9 | 45 |
|
10 | 46 | /// 通用数据库连接枚举 |
11 | 47 | /// |
@@ -34,57 +70,75 @@ pub enum AnyConnection { |
34 | 70 | /// - `database_type`: 数据库类型 |
35 | 71 | /// |
36 | 72 | /// 返回值: |
37 | | -/// 成功时返回封装好的数据库连接对象,失败时会 panic 并输出错误信息 |
38 | | -pub fn establish_connection(database_url: &str, database_type: &str) -> AnyConnection { |
| 73 | +/// 成功时返回封装好的数据库连接对象,失败时返回 ConnectionError 错误 |
| 74 | +pub fn establish_connection(database_url: &str, database_type: &str) -> Result<AnyConnection, ConnectionError> { |
39 | 75 | // 根据数据库类型建立相应的连接 |
40 | 76 | match database_type { |
41 | 77 | #[cfg(feature = "sqlite")] |
42 | 78 | "sqlite" => { |
43 | | - let mut conn = AnyConnection::Sqlite( |
44 | | - diesel::SqliteConnection::establish(database_url) |
45 | | - .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)), |
46 | | - ); |
| 79 | + let conn = diesel::SqliteConnection::establish(database_url) |
| 80 | + .map_err(|e| ConnectionError::with_source( |
| 81 | + &format!("Error connecting to SQLite database at {}", database_url), |
| 82 | + Box::new(e) |
| 83 | + ))?; |
| 84 | + |
| 85 | + let mut any_conn = AnyConnection::Sqlite(conn); |
47 | 86 |
|
48 | 87 | // 关闭外键约束检查 |
49 | 88 | diesel::sql_query("PRAGMA foreign_keys = OFF") |
50 | | - .execute(&mut conn) |
51 | | - .expect("Error executing PRAGMA foreign_keys = OFF"); |
| 89 | + .execute(&mut any_conn) |
| 90 | + .map_err(|e| ConnectionError::with_source( |
| 91 | + "Error executing PRAGMA foreign_keys = OFF", |
| 92 | + Box::new(e) |
| 93 | + ))?; |
52 | 94 |
|
53 | | - conn |
| 95 | + Ok(any_conn) |
54 | 96 | }, |
55 | 97 |
|
56 | 98 | #[cfg(feature = "mysql")] |
57 | 99 | "mysql" => { |
58 | | - let mut conn = AnyConnection::Mysql( |
59 | | - diesel::MysqlConnection::establish(database_url) |
60 | | - .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)), |
61 | | - ); |
| 100 | + let conn = diesel::MysqlConnection::establish(database_url) |
| 101 | + .map_err(|e| ConnectionError::with_source( |
| 102 | + &format!("Error connecting to MySQL database at {}", database_url), |
| 103 | + Box::new(e) |
| 104 | + ))?; |
| 105 | + |
| 106 | + let mut any_conn = AnyConnection::Mysql(conn); |
62 | 107 |
|
63 | 108 | // 关闭外键约束检查 |
64 | 109 | diesel::sql_query("SET FOREIGN_KEY_CHECKS = 0") |
65 | | - .execute(&mut conn) |
66 | | - .expect("Error executing SET FOREIGN_KEY_CHECKS = 0"); |
| 110 | + .execute(&mut any_conn) |
| 111 | + .map_err(|e| ConnectionError::with_source( |
| 112 | + "Error executing SET FOREIGN_KEY_CHECKS = 0", |
| 113 | + Box::new(e) |
| 114 | + ))?; |
67 | 115 |
|
68 | | - conn |
| 116 | + Ok(any_conn) |
69 | 117 | }, |
70 | 118 |
|
71 | 119 | #[cfg(feature = "postgres")] |
72 | 120 | "postgres" => { |
73 | | - let mut conn = AnyConnection::Postgresql( |
74 | | - diesel::PgConnection::establish(database_url) |
75 | | - .unwrap_or_else(|_| panic!("Error connecting to {}", database_url)), |
76 | | - ); |
| 121 | + let conn = diesel::PgConnection::establish(database_url) |
| 122 | + .map_err(|e| ConnectionError::with_source( |
| 123 | + &format!("Error connecting to PostgreSQL database at {}", database_url), |
| 124 | + Box::new(e) |
| 125 | + ))?; |
| 126 | + |
| 127 | + let mut any_conn = AnyConnection::Postgresql(conn); |
77 | 128 |
|
78 | 129 | // 关闭外键约束检查 |
79 | 130 | diesel::sql_query("SET session_replication_role = 'replica'") |
80 | | - .execute(&mut conn) |
81 | | - .expect("Error executing SET session_replication_role = 'replica'"); |
| 131 | + .execute(&mut any_conn) |
| 132 | + .map_err(|e| ConnectionError::with_source( |
| 133 | + "Error executing SET session_replication_role = 'replica'", |
| 134 | + Box::new(e) |
| 135 | + ))?; |
82 | 136 |
|
83 | | - conn |
| 137 | + Ok(any_conn) |
84 | 138 | }, |
85 | 139 |
|
86 | | - // 不支持的数据库类型直接 panic |
87 | | - _ => panic!("Unsupported database type: {} or feature not enabled", database_type), |
| 140 | + // 不支持的数据库类型 |
| 141 | + _ => Err(ConnectionError::new(&format!("Unsupported database type: {} or feature not enabled", database_type))), |
88 | 142 | } |
89 | 143 | } |
90 | 144 |
|
|
0 commit comments