diesel/result.rs
1//! Errors, type aliases, and functions related to working with `Result`.
2
3use alloc::boxed::Box;
4use alloc::ffi::NulError;
5use alloc::string::String;
6use alloc::string::ToString;
7use core::error::Error as StdError;
8use core::fmt::{self, Display};
9
10#[doc(inline)]
11pub use sqlstate::{InvalidSqlState, SqlState, SqlStateClass};
12
13#[derive(Debug)]
14#[allow(clippy::enum_variant_names)]
15/// Represents all the ways that a query can fail.
16///
17/// This type is not intended to be exhaustively matched, and new variants may
18/// be added in the future without a major version bump.
19#[non_exhaustive]
20pub enum Error {
21 /// The query contained a nul byte.
22 ///
23 /// This should never occur in normal usage.
24 InvalidCString(NulError),
25
26 /// The database returned an error.
27 ///
28 /// While Diesel prevents almost all sources of runtime errors at compile
29 /// time, it does not attempt to prevent 100% of them. Typically this error
30 /// will occur from insert or update statements due to a constraint
31 /// violation.
32 DatabaseError(
33 DatabaseErrorKind,
34 Box<dyn DatabaseErrorInformation + Send + Sync>,
35 ),
36
37 /// No rows were returned by a query expected to return at least one row.
38 ///
39 /// This variant is only returned by [`get_result`] and [`first`]. [`load`]
40 /// does not treat 0 rows as an error. If you would like to allow either 0
41 /// or 1 rows, call [`optional`] on the result.
42 ///
43 /// [`get_result`]: crate::query_dsl::RunQueryDsl::get_result()
44 /// [`first`]: crate::query_dsl::RunQueryDsl::first()
45 /// [`load`]: crate::query_dsl::RunQueryDsl::load()
46 /// [`optional`]: OptionalExtension::optional
47 NotFound,
48
49 /// The query could not be constructed
50 ///
51 /// An example of when this error could occur is if you are attempting to
52 /// construct an update statement with no changes (e.g. all fields on the
53 /// struct are `None`).
54 QueryBuilderError(Box<dyn StdError + Send + Sync>),
55
56 /// An error occurred deserializing the data being sent to the database.
57 ///
58 /// Typically this error means that the stated type of the query is
59 /// incorrect. An example of when this error might occur in normal usage is
60 /// attempting to deserialize an infinite date into chrono.
61 DeserializationError(Box<dyn StdError + Send + Sync>),
62
63 /// An error occurred serializing the data being sent to the database.
64 ///
65 /// An example of when this error would be returned is if you attempted to
66 /// serialize a `chrono::NaiveDate` earlier than the earliest date supported
67 /// by PostgreSQL.
68 SerializationError(Box<dyn StdError + Send + Sync>),
69
70 /// An error occurred when attempting rollback of a transaction subsequently to a failed
71 /// commit attempt.
72 ///
73 /// When a commit attempt fails and Diesel believes that it can attempt a rollback to return
74 /// the connection back in a usable state (out of that transaction), it attempts it then
75 /// returns the original error.
76 ///
77 /// If that fails, you get this.
78 RollbackErrorOnCommit {
79 /// The error that was encountered when attempting the rollback
80 rollback_error: Box<Error>,
81 /// The error that was encountered during the failed commit attempt
82 commit_error: Box<Error>,
83 },
84
85 /// Roll back the current transaction.
86 ///
87 /// You can return this variant inside of a transaction when you want to
88 /// roll it back, but have no actual error to return. Diesel will never
89 /// return this variant unless you gave it to us, and it can be safely
90 /// ignored in error handling.
91 RollbackTransaction,
92
93 /// Attempted to perform an operation that cannot be done inside a transaction
94 /// when a transaction was already open.
95 AlreadyInTransaction,
96
97 /// Attempted to perform an operation that can only be done inside a transaction
98 /// when no transaction was open
99 NotInTransaction,
100
101 /// Transaction manager broken, likely due to a broken connection. No other operations are possible.
102 BrokenTransactionManager,
103
104 /// Internal integer conversion failed
105 IntegerConversion(core::num::TryFromIntError),
106
107 /// Closing a handle failed
108 ClosingHandle(&'static str),
109}
110
111#[derive(Debug, PartialEq, Clone, Copy)]
112/// The kind of database error that occurred.
113///
114/// This is not meant to exhaustively cover all possible errors, but is used to
115/// identify errors which are commonly recovered from programmatically. This enum
116/// is not intended to be exhaustively matched, and new variants may be added in
117/// the future without a major version bump.
118#[non_exhaustive]
119pub enum DatabaseErrorKind {
120 /// A unique constraint was violated.
121 UniqueViolation = 0,
122
123 /// A foreign key constraint was violated.
124 ForeignKeyViolation = 1,
125
126 /// The query could not be sent to the database due to a protocol violation.
127 ///
128 /// An example of a case where this would occur is if you attempted to send
129 /// a query with more than 65000 bind parameters using PostgreSQL.
130 UnableToSendCommand = 2,
131
132 /// A serializable transaction failed to commit due to a read/write
133 /// dependency on a concurrent transaction.
134 ///
135 /// Corresponds to SQLSTATE code 40001
136 ///
137 /// This error is only detected for PostgreSQL, as we do not yet support
138 /// transaction isolation levels for other backends.
139 SerializationFailure = 3,
140
141 /// The command could not be completed because the transaction was read
142 /// only.
143 ///
144 /// This error will also be returned for `SELECT` statements which attempted
145 /// to lock the rows.
146 ReadOnlyTransaction = 4,
147
148 /// A restrict constraint was violated.
149 RestrictViolation = 9,
150
151 /// A not null constraint was violated.
152 NotNullViolation = 5,
153
154 /// A check constraint was violated.
155 CheckViolation = 6,
156
157 /// An exclusion constraint was violated.
158 ExclusionViolation = 10,
159
160 /// The connection to the server was unexpectedly closed.
161 ///
162 /// This error is only detected for PostgreSQL and is emitted on a best-effort basis
163 /// and may be missed.
164 ClosedConnection = 7,
165
166 #[doc(hidden)]
167 Unknown = 8, // Match against _ instead, more variants may be added in the future
168}
169
170/// Information about an error that was returned by the database.
171pub trait DatabaseErrorInformation {
172 /// The primary human-readable error message. Typically one line.
173 fn message(&self) -> &str;
174
175 /// An optional secondary error message providing more details about the
176 /// problem, if it was provided by the database. Might span multiple lines.
177 fn details(&self) -> Option<&str>;
178
179 /// An optional suggestion of what to do about the problem, if one was
180 /// provided by the database.
181 fn hint(&self) -> Option<&str>;
182
183 /// The name of the table the error was associated with, if the error was
184 /// associated with a specific table and the backend supports retrieving
185 /// that information.
186 ///
187 /// Currently this method will return `None` for all backends other than
188 /// PostgreSQL.
189 fn table_name(&self) -> Option<&str>;
190
191 /// The name of the column the error was associated with, if the error was
192 /// associated with a specific column and the backend supports retrieving
193 /// that information.
194 ///
195 /// Currently this method will return `None` for all backends other than
196 /// PostgreSQL.
197 fn column_name(&self) -> Option<&str>;
198
199 /// The constraint that was violated if this error is a constraint violation
200 /// and the backend supports retrieving that information.
201 ///
202 /// Currently this method will return `None` for all backends other than
203 /// PostgreSQL.
204 fn constraint_name(&self) -> Option<&str>;
205
206 /// An optional integer indicating an error cursor position as an index into
207 /// the original statement string.
208 fn statement_position(&self) -> Option<i32>;
209
210 /// The [`SqlState`] of the error, if the connection reports one.
211 ///
212 /// Which errors carry a code is documented by each connection.
213 fn sqlstate(&self) -> Option<SqlState> {
214 None
215 }
216}
217
218impl fmt::Debug for dyn DatabaseErrorInformation + Send + Sync {
219 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
220 fmt::Debug::fmt(&self.message(), f)
221 }
222}
223
224impl DatabaseErrorInformation for String {
225 fn message(&self) -> &str {
226 self
227 }
228 fn details(&self) -> Option<&str> {
229 None
230 }
231 fn hint(&self) -> Option<&str> {
232 None
233 }
234 fn table_name(&self) -> Option<&str> {
235 None
236 }
237 fn column_name(&self) -> Option<&str> {
238 None
239 }
240 fn constraint_name(&self) -> Option<&str> {
241 None
242 }
243 fn statement_position(&self) -> Option<i32> {
244 None
245 }
246}
247
248impl DatabaseErrorInformation for core::convert::Infallible {
249 fn message(&self) -> &str {
250 match *self {}
251 }
252
253 fn details(&self) -> Option<&str> {
254 match *self {}
255 }
256
257 fn hint(&self) -> Option<&str> {
258 match *self {}
259 }
260
261 fn table_name(&self) -> Option<&str> {
262 match *self {}
263 }
264
265 fn column_name(&self) -> Option<&str> {
266 match *self {}
267 }
268
269 fn constraint_name(&self) -> Option<&str> {
270 match *self {}
271 }
272
273 fn statement_position(&self) -> Option<i32> {
274 match *self {}
275 }
276}
277
278/// Errors which can occur during [`Connection::establish`]
279///
280/// [`Connection::establish`]: crate::connection::Connection::establish
281#[derive(Debug, PartialEq)]
282#[non_exhaustive]
283pub enum ConnectionError {
284 /// The connection URL contained a `NUL` byte.
285 InvalidCString(NulError),
286 /// The database returned an error.
287 BadConnection(String),
288 /// The connection URL could not be parsed.
289 InvalidConnectionUrl(String),
290 /// Diesel could not configure the database connection.
291 ///
292 /// Diesel may try to automatically set session specific configuration
293 /// values, such as UTF8 encoding, or enabling the `||` operator on MySQL.
294 /// This variant is returned if an error occurred executing the query to set
295 /// those options. Diesel will never affect global configuration.
296 CouldntSetupConfiguration(Error),
297}
298
299/// A specialized result type for queries.
300///
301/// This type is exported by `diesel::prelude`, and is generally used by any
302/// code which is interacting with Diesel. This type exists to avoid writing out
303/// `diesel::result::Error`, and is otherwise a direct mapping to `Result`.
304pub type QueryResult<T> = Result<T, Error>;
305
306/// A specialized result type for establishing connections.
307///
308/// This type exists to avoid writing out `diesel::result::ConnectionError`, and
309/// is otherwise a direct mapping to `Result`.
310pub type ConnectionResult<T> = Result<T, ConnectionError>;
311
312/// See the [method documentation](OptionalExtension::optional).
313pub trait OptionalExtension<T> {
314 /// Converts a `QueryResult<T>` into a `QueryResult<Option<T>>`.
315 ///
316 /// By default, Diesel treats 0 rows being returned from a query that is expected to return 1
317 /// row as an error (e.g. the return value of [`get_result`] or [`first`]). This method will
318 /// handle that error, and give you back an `Option<T>` instead.
319 ///
320 /// [`get_result`]: crate::query_dsl::RunQueryDsl::get_result()
321 /// [`first`]: crate::query_dsl::RunQueryDsl::first()
322 ///
323 /// # Example
324 ///
325 /// ```rust
326 /// use diesel::{NotFound, OptionalExtension, QueryResult};
327 ///
328 /// let result: QueryResult<i32> = Ok(1);
329 /// assert_eq!(Ok(Some(1)), result.optional());
330 ///
331 /// let result: QueryResult<i32> = Err(NotFound);
332 /// assert_eq!(Ok(None), result.optional());
333 /// ```
334 fn optional(self) -> Result<Option<T>, Error>;
335}
336
337impl<T> OptionalExtension<T> for QueryResult<T> {
338 fn optional(self) -> Result<Option<T>, Error> {
339 match self {
340 Ok(value) => Ok(Some(value)),
341 Err(Error::NotFound) => Ok(None),
342 Err(e) => Err(e),
343 }
344 }
345}
346
347/// See the [method documentation](OptionalEmptyChangesetExtension::optional_empty_changeset).
348pub trait OptionalEmptyChangesetExtension<T> {
349 /// By default, Diesel treats an empty update as a `QueryBuilderError`. This method will
350 /// convert that error into `None`.
351 ///
352 /// # Example
353 ///
354 /// ```rust
355 /// use diesel::{
356 /// result::EmptyChangeset, result::Error::QueryBuilderError, OptionalEmptyChangesetExtension,
357 /// QueryResult,
358 /// };
359 /// let result: QueryResult<i32> = Err(QueryBuilderError(Box::new(EmptyChangeset)));
360 /// assert_eq!(Ok(None), result.optional_empty_changeset());
361 /// ```
362 fn optional_empty_changeset(self) -> Result<Option<T>, Error>;
363}
364
365impl<T> OptionalEmptyChangesetExtension<T> for QueryResult<T> {
366 fn optional_empty_changeset(self) -> Result<Option<T>, Error> {
367 match self {
368 Ok(value) => Ok(Some(value)),
369 Err(Error::QueryBuilderError(e)) if e.is::<EmptyChangeset>() => Ok(None),
370 Err(e) => Err(e),
371 }
372 }
373}
374
375impl From<NulError> for ConnectionError {
376 fn from(e: NulError) -> Self {
377 ConnectionError::InvalidCString(e)
378 }
379}
380
381impl From<NulError> for Error {
382 fn from(e: NulError) -> Self {
383 Error::InvalidCString(e)
384 }
385}
386
387impl Display for Error {
388 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
389 match *self {
390 Error::InvalidCString(ref nul_err) => write!(f, "{nul_err}"),
391 Error::DatabaseError(_, ref e) => write!(f, "{}", e.message()),
392 Error::NotFound => f.write_str("Record not found"),
393 Error::QueryBuilderError(ref e) => e.fmt(f),
394 Error::DeserializationError(ref e) => e.fmt(f),
395 Error::SerializationError(ref e) => e.fmt(f),
396 Error::RollbackErrorOnCommit {
397 ref rollback_error,
398 ref commit_error,
399 } => {
400 write!(
401 f,
402 "Transaction rollback failed: {rollback_error} \
403 (rollback attempted because of failure to commit: {commit_error})",
404 )?;
405 Ok(())
406 }
407 Error::RollbackTransaction => {
408 write!(f, "You have asked diesel to rollback the transaction")
409 }
410 Error::BrokenTransactionManager => write!(f, "The transaction manager is broken"),
411 Error::AlreadyInTransaction => write!(
412 f,
413 "Cannot perform this operation while a transaction is open",
414 ),
415 Error::NotInTransaction => {
416 write!(f, "Cannot perform this operation outside of a transaction",)
417 }
418 Error::IntegerConversion(_) => f.write_str("Internal integer conversion failed"),
419 Error::ClosingHandle(message) => {
420 write!(f, "Error closing SQLite blob: {message}")
421 }
422 }
423 }
424}
425
426impl StdError for Error {
427 fn source(&self) -> Option<&(dyn StdError + 'static)> {
428 match *self {
429 Error::InvalidCString(ref e) => e.source(),
430 Error::QueryBuilderError(ref e) => e.source(),
431 Error::DeserializationError(ref e) => e.source(),
432 Error::SerializationError(ref e) => e.source(),
433 Error::IntegerConversion(ref e) => Some(e),
434 _ => None,
435 }
436 }
437}
438
439impl Display for ConnectionError {
440 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
441 match *self {
442 ConnectionError::InvalidCString(ref nul_err) => nul_err.fmt(f),
443 ConnectionError::BadConnection(ref s) => write!(f, "{s}"),
444 ConnectionError::InvalidConnectionUrl(ref s) => write!(f, "{s}"),
445 ConnectionError::CouldntSetupConfiguration(ref e) => e.fmt(f),
446 }
447 }
448}
449
450impl StdError for ConnectionError {
451 fn source(&self) -> Option<&(dyn StdError + 'static)> {
452 match *self {
453 ConnectionError::InvalidCString(ref e) => e.source(),
454 ConnectionError::CouldntSetupConfiguration(ref e) => e.source(),
455 _ => None,
456 }
457 }
458}
459
460impl PartialEq for Error {
461 fn eq(&self, other: &Error) -> bool {
462 match (self, other) {
463 (Error::InvalidCString(a), Error::InvalidCString(b)) => a == b,
464 (Error::DatabaseError(_, a), Error::DatabaseError(_, b)) => a.message() == b.message(),
465 (&Error::NotFound, &Error::NotFound) => true,
466 (&Error::RollbackTransaction, &Error::RollbackTransaction) => true,
467 (&Error::AlreadyInTransaction, &Error::AlreadyInTransaction) => true,
468 _ => false,
469 }
470 }
471}
472
473#[cfg(test)]
474#[allow(warnings)]
475fn error_impls_send() {
476 let err: Error = unimplemented!();
477 let x: &dyn Send = &err;
478}
479
480#[cfg(test)]
481#[allow(warnings)]
482fn infallible_impls_database_error_information() {
483 let err: core::convert::Infallible = unimplemented!();
484 let x: &dyn DatabaseErrorInformation = &err;
485}
486
487/// An unexpected `NULL` was encountered during deserialization
488#[derive(Debug, Clone, Copy)]
489pub struct UnexpectedNullError;
490
491impl fmt::Display for UnexpectedNullError {
492 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
493 write!(f, "Unexpected null for non-null column")
494 }
495}
496
497impl StdError for UnexpectedNullError {}
498
499/// Expected more fields then present in the current row while deserializing results
500#[derive(Debug, Clone, Copy)]
501pub struct UnexpectedEndOfRow;
502
503impl fmt::Display for UnexpectedEndOfRow {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 write!(f, "Unexpected end of row")
506 }
507}
508
509impl StdError for UnexpectedEndOfRow {}
510
511/// Expected when an update has no changes to save.
512///
513/// When using `optional_empty_changeset`, this error is turned into `None`.
514#[derive(Debug, Clone, Copy)]
515pub struct EmptyChangeset;
516
517impl fmt::Display for EmptyChangeset {
518 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
519 write!(
520 f,
521 "There are no changes to save. This query cannot be built"
522 )
523 }
524}
525
526impl StdError for EmptyChangeset {}
527
528/// Expected when you try to execute an empty query
529#[derive(Debug, Clone, Copy)]
530pub struct EmptyQuery;
531
532impl fmt::Display for EmptyQuery {
533 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
534 write!(
535 f,
536 "Detected an empty query. These are not supported by your database system"
537 )
538 }
539}
540
541impl StdError for EmptyQuery {}
542
543/// An error occurred while deserializing a field
544#[derive(Debug)]
545#[non_exhaustive]
546pub struct DeserializeFieldError {
547 /// The name of the field that failed to deserialize
548 pub field_name: Option<String>,
549 /// The error that occurred while deserializing the field
550 pub error: Box<dyn StdError + Send + Sync>,
551}
552
553impl DeserializeFieldError {
554 #[cold]
555 pub(crate) fn new<'a, F, DB>(field: F, error: Box<dyn core::error::Error + Send + Sync>) -> Self
556 where
557 DB: crate::backend::Backend,
558 F: crate::row::Field<'a, DB>,
559 {
560 DeserializeFieldError {
561 field_name: field.field_name().map(|s| s.to_string()),
562 error,
563 }
564 }
565}
566
567impl StdError for DeserializeFieldError {
568 fn source(&self) -> Option<&(dyn StdError + 'static)> {
569 Some(&*self.error)
570 }
571}
572
573impl fmt::Display for DeserializeFieldError {
574 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
575 if let Some(ref field_name) = self.field_name {
576 write!(f, "Error deserializing field '{field_name}'")
577 } else {
578 f.write_str("Error deserializing field")
579 }
580 }
581}