forked from launchbadge/sqlx
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patherror.rs
More file actions
479 lines (415 loc) · 15.6 KB
/
error.rs
File metadata and controls
479 lines (415 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Types for working with errors produced by SQLx.
use std::any::type_name;
use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt::Display;
use std::io;
use crate::database::Database;
use crate::type_info::TypeInfo;
use crate::types::Type;
/// A specialized `Result` type for SQLx.
pub type Result<T, E = Error> = ::std::result::Result<T, E>;
// Convenience type alias for usage within SQLx.
// Do not make this type public.
pub type BoxDynError = Box<dyn StdError + 'static + Send + Sync>;
/// An unexpected `NULL` was encountered during decoding.
///
/// Returned from [`Row::get`](crate::row::Row::get) if the value from the database is `NULL`,
/// and you are not decoding into an `Option`.
#[derive(thiserror::Error, Debug)]
#[error("unexpected null; try decoding as an `Option`")]
pub struct UnexpectedNullError;
/// Represents all the ways a method can fail within SQLx.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
/// Error occurred while parsing a connection string.
#[error("error with configuration: {0}")]
Configuration(#[source] BoxDynError),
/// One or more of the arguments to the called function was invalid.
///
/// The string contains more information.
#[error("{0}")]
InvalidArgument(String),
/// Error returned from the database.
#[error("error returned from database: {0}")]
Database(#[source] Box<dyn DatabaseError>),
/// Error communicating with the database backend.
#[error("error communicating with database: {0}")]
Io(#[from] io::Error),
/// Error occurred while attempting to establish a TLS connection.
#[error("error occurred while attempting to establish a TLS connection: {0}")]
Tls(#[source] BoxDynError),
/// Unexpected or invalid data encountered while communicating with the database.
///
/// This should indicate there is a programming error in a SQLx driver or there
/// is something corrupted with the connection to the database itself.
#[error("encountered unexpected or invalid data: {0}")]
Protocol(String),
/// No rows returned by a query that expected to return at least one row.
#[error("no rows returned by a query that expected to return at least one row")]
RowNotFound,
/// Type in query doesn't exist. Likely due to typo or missing user type.
#[error("type named {type_name} not found")]
TypeNotFound { type_name: String },
/// Column index was out of bounds.
#[error("column index out of bounds: the len is {len}, but the index is {index}")]
ColumnIndexOutOfBounds { index: usize, len: usize },
/// No column found for the given name.
#[error("no column found for name: {0}")]
ColumnNotFound(String),
/// Error occurred while decoding a value from a specific column.
#[error("error occurred while decoding column {index}: {source}")]
ColumnDecode {
index: String,
#[source]
source: BoxDynError,
},
/// Error occurred while encoding a value.
#[error("error occurred while encoding a value: {0}")]
Encode(#[source] BoxDynError),
/// Error occurred while decoding a value.
#[error("error occurred while decoding: {0}")]
Decode(#[source] BoxDynError),
/// Error occurred within the `Any` driver mapping to/from the native driver.
#[error("error in Any driver mapping: {0}")]
AnyDriverError(#[source] BoxDynError),
/// A [`Pool::acquire`] timed out due to connections not becoming available or
/// because another task encountered too many errors while trying to open a new connection.
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
#[error("pool timed out while waiting for an open connection")]
PoolTimedOut,
/// [`Pool::close`] was called while we were waiting in [`Pool::acquire`].
///
/// [`Pool::acquire`]: crate::pool::Pool::acquire
/// [`Pool::close`]: crate::pool::Pool::close
#[error("attempted to acquire a connection on a closed pool")]
PoolClosed,
/// A background worker has crashed.
#[error("attempted to communicate with a crashed background worker")]
WorkerCrashed,
#[cfg(feature = "migrate")]
#[error("{0}")]
Migrate(#[source] Box<crate::migrate::MigrateError>),
#[error("attempted to call begin_with at non-zero transaction depth")]
InvalidSavePointStatement,
#[error("got unexpected connection status after attempting to begin transaction")]
BeginFailed,
// Not returned in normal operation.
/// Error occurred while reading configuration file
#[doc(hidden)]
#[error("error reading configuration file: {0}")]
ConfigFile(#[from] crate::config::ConfigError),
}
impl StdError for Box<dyn DatabaseError> {}
impl Error {
pub fn into_database_error(self) -> Option<Box<dyn DatabaseError + 'static>> {
match self {
Error::Database(err) => Some(err),
_ => None,
}
}
pub fn as_database_error(&self) -> Option<&(dyn DatabaseError + 'static)> {
match self {
Error::Database(err) => Some(&**err),
_ => None,
}
}
#[doc(hidden)]
#[inline]
pub fn protocol(err: impl Display) -> Self {
Error::Protocol(err.to_string())
}
#[doc(hidden)]
#[inline]
pub fn database(err: impl DatabaseError) -> Self {
Error::Database(Box::new(err))
}
#[doc(hidden)]
#[inline]
pub fn config(err: impl StdError + Send + Sync + 'static) -> Self {
Error::Configuration(err.into())
}
pub(crate) fn tls(err: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
Error::Tls(err.into())
}
#[doc(hidden)]
#[inline]
pub fn decode(err: impl Into<Box<dyn StdError + Send + Sync + 'static>>) -> Self {
Error::Decode(err.into())
}
}
pub fn mismatched_types<DB: Database, T: Type<DB>>(ty: &DB::TypeInfo) -> BoxDynError {
// TODO: `#name` only produces `TINYINT` but perhaps we want to show `TINYINT(1)`
format!(
"mismatched types; Rust type `{}` (as SQL type `{}`) is not compatible with SQL type `{}`",
type_name::<T>(),
T::type_info().name(),
ty.name()
)
.into()
}
/// The error kind.
///
/// This enum is to be used to identify frequent errors that can be handled by the program.
/// Although it currently only supports constraint violations, the type may grow in the future.
#[derive(Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ErrorKind {
/// Unique/primary key constraint violation.
UniqueViolation,
/// Foreign key constraint violation.
ForeignKeyViolation,
/// Not-null constraint violation.
NotNullViolation,
/// Check constraint violation.
CheckViolation,
/// Exclusion constraint violation.
ExclusionViolation,
/// An unmapped error.
Other,
}
/// An error that was returned from the database.
pub trait DatabaseError: 'static + Send + Sync + StdError {
/// The primary, human-readable error message.
fn message(&self) -> &str;
/// The (SQLSTATE) code for the error.
fn code(&self) -> Option<Cow<'_, str>> {
None
}
#[doc(hidden)]
fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static);
#[doc(hidden)]
fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static);
#[doc(hidden)]
fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static>;
#[doc(hidden)]
fn is_transient_in_connect_phase(&self) -> bool {
false
}
/// Returns the name of the constraint that triggered the error, if applicable.
/// If the error was caused by a conflict of a unique index, this will be the index name.
///
/// ### Note
/// Currently only populated by the Postgres driver.
fn constraint(&self) -> Option<&str> {
None
}
/// Returns the name of the table that was affected by the error, if applicable.
///
/// ### Note
/// Currently only populated by the Postgres driver.
fn table(&self) -> Option<&str> {
None
}
/// Returns the kind of the error, if supported.
///
/// ### Note
/// Not all back-ends behave the same when reporting the error code.
fn kind(&self) -> ErrorKind;
/// Returns whether the error kind is a violation of a unique/primary key constraint.
fn is_unique_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::UniqueViolation)
}
/// Returns whether the error kind is a violation of a foreign key.
fn is_foreign_key_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::ForeignKeyViolation)
}
/// Returns whether the error kind is a violation of a check.
fn is_check_violation(&self) -> bool {
matches!(self.kind(), ErrorKind::CheckViolation)
}
}
impl dyn DatabaseError {
/// Downcast a reference to this generic database error to a specific
/// database error type.
///
/// # Panics
///
/// Panics if the database error type is not `E`. This is a deliberate contrast from
/// `Error::downcast_ref` which returns `Option<&E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast_ref`.
pub fn downcast_ref<E: DatabaseError>(&self) -> &E {
self.try_downcast_ref().unwrap_or_else(|| {
panic!("downcast to wrong DatabaseError type; original error: {self}")
})
}
/// Downcast this generic database error to a specific database error type.
///
/// # Panics
///
/// Panics if the database error type is not `E`. This is a deliberate contrast from
/// `Error::downcast` which returns `Option<E>`. In normal usage, you should know the
/// specific error type. In other cases, use `try_downcast`.
pub fn downcast<E: DatabaseError>(self: Box<Self>) -> Box<E> {
self.try_downcast()
.unwrap_or_else(|e| panic!("downcast to wrong DatabaseError type; original error: {e}"))
}
/// Downcast a reference to this generic database error to a specific
/// database error type.
#[inline]
pub fn try_downcast_ref<E: DatabaseError>(&self) -> Option<&E> {
self.as_error().downcast_ref()
}
/// Downcast this generic database error to a specific database error type.
#[inline]
pub fn try_downcast<E: DatabaseError>(self: Box<Self>) -> Result<Box<E>, Box<Self>> {
if self.as_error().is::<E>() {
Ok(self.into_error().downcast().unwrap())
} else {
Err(self)
}
}
}
impl<E> From<E> for Error
where
E: DatabaseError,
{
#[inline]
fn from(error: E) -> Self {
Error::Database(Box::new(error))
}
}
#[cfg(feature = "migrate")]
impl From<crate::migrate::MigrateError> for Error {
#[inline]
fn from(error: crate::migrate::MigrateError) -> Self {
Error::Migrate(Box::new(error))
}
}
/// Format an error message as a `Protocol` error
#[macro_export]
macro_rules! err_protocol {
($($fmt_args:tt)*) => {
$crate::error::Error::Protocol(
format!(
"{} ({}:{})",
// Note: the format string needs to be unmodified (e.g. by `concat!()`)
// for implicit formatting arguments to work
format_args!($($fmt_args)*),
module_path!(),
line!(),
)
)
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_display_wrapper_variants() {
let io = || std::io::Error::new(std::io::ErrorKind::Other, "oops");
assert_eq!(
Error::Configuration(Box::new(io())).to_string(),
"error with configuration: oops"
);
assert_eq!(
Error::Io(io()).to_string(),
"error communicating with database: oops"
);
assert_eq!(
Error::Tls(Box::new(io())).to_string(),
"error occurred while attempting to establish a TLS connection: oops"
);
assert_eq!(
Error::Protocol("bad".into()).to_string(),
"encountered unexpected or invalid data: bad"
);
assert_eq!(
Error::ColumnDecode {
index: "1".into(),
source: Box::new(io()),
}
.to_string(),
"error occurred while decoding column 1: oops"
);
assert_eq!(
Error::Encode(Box::new(io())).to_string(),
"error occurred while encoding a value: oops"
);
assert_eq!(
Error::Decode(Box::new(io())).to_string(),
"error occurred while decoding: oops"
);
assert_eq!(
Error::AnyDriverError(Box::new(io())).to_string(),
"error in Any driver mapping: oops"
);
}
#[test]
fn test_display_message_variants() {
assert_eq!(
Error::InvalidArgument("missing host".into()).to_string(),
"missing host"
);
assert_eq!(
Error::TypeNotFound {
type_name: "custom".into(),
}
.to_string(),
"type named custom not found"
);
assert_eq!(
Error::ColumnIndexOutOfBounds { index: 5, len: 3 }.to_string(),
"column index out of bounds: the len is 3, but the index is 5"
);
assert_eq!(
Error::ColumnNotFound("foo".into()).to_string(),
"no column found for name: foo"
);
}
#[test]
fn test_display_unit_variants() {
assert_eq!(
Error::RowNotFound.to_string(),
"no rows returned by a query that expected to return at least one row"
);
assert_eq!(
Error::PoolTimedOut.to_string(),
"pool timed out while waiting for an open connection"
);
assert_eq!(
Error::PoolClosed.to_string(),
"attempted to acquire a connection on a closed pool"
);
assert_eq!(
Error::WorkerCrashed.to_string(),
"attempted to communicate with a crashed background worker"
);
assert_eq!(
Error::InvalidSavePointStatement.to_string(),
"attempted to call begin_with at non-zero transaction depth"
);
assert_eq!(
Error::BeginFailed.to_string(),
"got unexpected connection status after attempting to begin transaction"
);
}
#[test]
fn test_debug_contains_variant_name() {
let io = || std::io::Error::new(std::io::ErrorKind::Other, "oops");
assert!(format!("{:?}", Error::Configuration(Box::new(io()))).contains("Configuration"));
assert!(format!("{:?}", Error::InvalidArgument("x".into())).contains("InvalidArgument"));
assert!(format!("{:?}", Error::Io(io())).contains("Io"));
assert!(format!("{:?}", Error::Protocol("x".into())).contains("Protocol"));
assert!(format!("{:?}", Error::RowNotFound).contains("RowNotFound"));
assert!(
format!("{:?}", Error::TypeNotFound { type_name: "x".into() }).contains("TypeNotFound")
);
assert!(
format!("{:?}", Error::ColumnIndexOutOfBounds { index: 0, len: 0 })
.contains("ColumnIndexOutOfBounds")
);
assert!(
format!("{:?}", Error::ColumnNotFound("x".into())).contains("ColumnNotFound")
);
assert!(format!("{:?}", Error::PoolTimedOut).contains("PoolTimedOut"));
assert!(format!("{:?}", Error::PoolClosed).contains("PoolClosed"));
assert!(format!("{:?}", Error::WorkerCrashed).contains("WorkerCrashed"));
assert!(
format!("{:?}", Error::InvalidSavePointStatement).contains("InvalidSavePointStatement")
);
assert!(format!("{:?}", Error::BeginFailed).contains("BeginFailed"));
}
}