Skip to main content

rusqlite/
error.rs

1use crate::types::FromSqlError;
2use crate::types::Type;
3use crate::{Result, errmsg_to_string, ffi};
4use std::error;
5use std::ffi::{NulError, c_char, c_int};
6use std::fmt;
7use std::path::PathBuf;
8use std::str;
9
10// Just to keep MSRV low
11macro_rules! cfg_select {
12    ({ $($tt:tt)* }) => {{
13        $crate::cfg_select! { $($tt)* }
14    }};
15    (_ => { $($output:tt)* }) => {
16        $($output)*
17    };
18    (
19        $cfg:meta => $output:tt
20        $($( $rest:tt )+)?
21    ) => {{
22        #[cfg($cfg)]
23        cfg_select! { _ => $output }
24        $(
25            #[cfg(not($cfg))]
26            cfg_select! { $($rest)+ }
27        )?
28    }}
29}
30
31/// Enum listing possible errors from rusqlite.
32#[derive(Debug)]
33#[non_exhaustive]
34pub enum Error {
35    /// An error from an underlying SQLite call.
36    SqliteFailure(ffi::Error, Option<String>),
37
38    /// Error reported when attempting to open a connection when SQLite was
39    /// configured to allow single-threaded use only.
40    SqliteSingleThreadedMode,
41
42    /// Error when the value of a particular column is requested, but it cannot
43    /// be converted to the requested Rust type.
44    FromSqlConversionFailure(usize, Type, Box<dyn error::Error + Send + Sync + 'static>),
45
46    /// Error when SQLite gives us an integral value outside the range of the
47    /// requested type (e.g., trying to get the value 1000 into a `u8`).
48    /// The associated `usize` is the column index,
49    /// and the associated `i64` is the value returned by SQLite.
50    IntegralValueOutOfRange(usize, i64),
51
52    /// Error converting a string to UTF-8.
53    Utf8Error(usize, str::Utf8Error),
54
55    /// Error converting a string to a C-compatible string because it contained
56    /// an embedded nul.
57    NulError(NulError),
58
59    /// Error when using SQL named parameters and passing a parameter name not
60    /// present in the SQL.
61    InvalidParameterName(String),
62
63    /// Error converting a file path to a string.
64    InvalidPath(PathBuf),
65
66    /// Error returned when an [`execute`](crate::Connection::execute) call
67    /// returns rows.
68    ExecuteReturnedResults,
69
70    /// Error when a query that was expected to return at least one row (e.g.,
71    /// for [`query_row`](crate::Connection::query_row)) did not return any.
72    QueryReturnedNoRows,
73
74    /// Error when a query that was expected to return only one row (e.g.,
75    /// for [`query_one`](crate::Connection::query_one)) did return more than one.
76    QueryReturnedMoreThanOneRow,
77
78    /// Error when the value of a particular column is requested, but the index
79    /// is out of range for the statement.
80    InvalidColumnIndex(usize),
81
82    /// Error when the value of a named column is requested, but no column
83    /// matches the name for the statement.
84    InvalidColumnName(String),
85
86    /// Error when the value of a particular column is requested, but the type
87    /// of the result in that column cannot be converted to the requested
88    /// Rust type.
89    InvalidColumnType(usize, String, Type),
90
91    /// Error when a query that was expected to insert one row did not insert
92    /// any or insert many.
93    StatementChangedRows(usize),
94
95    /// Error returned by:
96    /// - [`functions::Context::get`](crate::functions::Context::get) when the function argument cannot be converted to the requested type.
97    /// - or [`vtab::Values::get`](crate::vtab::Values::get) when the filter argument cannot be converted to the requested type.
98    #[cfg(any(feature = "functions", feature = "vtab"))]
99    InvalidParameterType(usize, Type),
100
101    /// An error case available for implementors of custom user functions (e.g.,
102    /// [`create_scalar_function`](crate::Connection::create_scalar_function)).
103    #[cfg(feature = "functions")]
104    UserFunctionError(Box<dyn error::Error + Send + Sync + 'static>),
105
106    /// Error available for the implementors of the
107    /// [`ToSql`](crate::types::ToSql) trait.
108    ToSqlConversionFailure(Box<dyn error::Error + Send + Sync + 'static>),
109
110    /// Empty or comment only SQL
111    Empty,
112    /// Error when the SQL is not a `SELECT`, is not read-only.
113    InvalidQuery,
114
115    /// An error case available for implementors of custom modules (e.g.,
116    /// [`create_module`](crate::Connection::create_module)).
117    #[cfg(feature = "vtab")]
118    ModuleError(String),
119
120    /// An unwinding panic occurs in a UDF (user-defined function).
121    UnwindingPanic,
122
123    /// An error returned when
124    /// [`Context::get_aux`](crate::functions::Context::get_aux) attempts to
125    /// retrieve data of a different type than what had been stored using
126    /// [`Context::set_aux`](crate::functions::Context::set_aux).
127    #[cfg(feature = "functions")]
128    GetAuxWrongType,
129
130    /// Error when the SQL contains multiple statements.
131    MultipleStatement,
132    /// Error when the number of bound parameters does not match the number of
133    /// parameters in the query. The first `usize` is how many parameters were
134    /// given, the 2nd is how many were expected.
135    InvalidParameterCount(usize, usize),
136
137    /// Returned from various functions in the Blob IO positional API. For
138    /// example,
139    /// [`Blob::raw_read_at_exact`](crate::blob::Blob::raw_read_at_exact) will
140    /// return it if the blob has insufficient data.
141    #[cfg(feature = "blob")]
142    BlobSizeError,
143    /// Error referencing a specific token in the input SQL
144    SqlInputError {
145        /// error code
146        error: ffi::Error,
147        /// error message
148        msg: String,
149        /// SQL input
150        sql: String,
151        /// byte offset of the start of invalid token
152        offset: c_int,
153    },
154    /// Loadable extension initialization error
155    #[cfg(feature = "loadable_extension")]
156    InitError(ffi::InitError),
157    /// Error when the schema of a particular database is requested, but the index
158    /// is out of range.
159    InvalidDatabaseIndex(usize),
160}
161
162impl PartialEq for Error {
163    fn eq(&self, other: &Self) -> bool {
164        match (self, other) {
165            (Self::SqliteFailure(e1, s1), Self::SqliteFailure(e2, s2)) => e1 == e2 && s1 == s2,
166            (Self::SqliteSingleThreadedMode, Self::SqliteSingleThreadedMode) => true,
167            (Self::IntegralValueOutOfRange(i1, n1), Self::IntegralValueOutOfRange(i2, n2)) => {
168                i1 == i2 && n1 == n2
169            }
170            (Self::Utf8Error(i1, e1), Self::Utf8Error(i2, e2)) => i1 == i2 && e1 == e2,
171            (Self::NulError(e1), Self::NulError(e2)) => e1 == e2,
172            (Self::InvalidParameterName(n1), Self::InvalidParameterName(n2)) => n1 == n2,
173            (Self::InvalidPath(p1), Self::InvalidPath(p2)) => p1 == p2,
174            (Self::ExecuteReturnedResults, Self::ExecuteReturnedResults) => true,
175            (Self::QueryReturnedNoRows, Self::QueryReturnedNoRows) => true,
176            (Self::QueryReturnedMoreThanOneRow, Self::QueryReturnedMoreThanOneRow) => true,
177            (Self::InvalidColumnIndex(i1), Self::InvalidColumnIndex(i2)) => i1 == i2,
178            (Self::InvalidColumnName(n1), Self::InvalidColumnName(n2)) => n1 == n2,
179            (Self::InvalidColumnType(i1, n1, t1), Self::InvalidColumnType(i2, n2, t2)) => {
180                i1 == i2 && t1 == t2 && n1 == n2
181            }
182            (Self::StatementChangedRows(n1), Self::StatementChangedRows(n2)) => n1 == n2,
183            #[cfg(any(feature = "functions", feature = "vtab"))]
184            (Self::InvalidParameterType(i1, t1), Self::InvalidParameterType(i2, t2)) => {
185                i1 == i2 && t1 == t2
186            }
187            (Self::Empty, Self::Empty) => true,
188            (Self::InvalidQuery, Self::InvalidQuery) => true,
189            #[cfg(feature = "vtab")]
190            (Self::ModuleError(s1), Self::ModuleError(s2)) => s1 == s2,
191            (Self::UnwindingPanic, Self::UnwindingPanic) => true,
192            #[cfg(feature = "functions")]
193            (Self::GetAuxWrongType, Self::GetAuxWrongType) => true,
194            (Self::InvalidParameterCount(i1, n1), Self::InvalidParameterCount(i2, n2)) => {
195                i1 == i2 && n1 == n2
196            }
197            #[cfg(feature = "blob")]
198            (Self::BlobSizeError, Self::BlobSizeError) => true,
199            (
200                Self::SqlInputError {
201                    error: e1,
202                    msg: m1,
203                    sql: s1,
204                    offset: o1,
205                },
206                Self::SqlInputError {
207                    error: e2,
208                    msg: m2,
209                    sql: s2,
210                    offset: o2,
211                },
212            ) => e1 == e2 && m1 == m2 && s1 == s2 && o1 == o2,
213            #[cfg(feature = "loadable_extension")]
214            (Self::InitError(e1), Self::InitError(e2)) => e1 == e2,
215            (Self::InvalidDatabaseIndex(i1), Self::InvalidDatabaseIndex(i2)) => i1 == i2,
216            (..) => false,
217        }
218    }
219}
220
221impl From<str::Utf8Error> for Error {
222    #[cold]
223    fn from(err: str::Utf8Error) -> Self {
224        Self::Utf8Error(UNKNOWN_COLUMN, err)
225    }
226}
227
228impl From<NulError> for Error {
229    #[cold]
230    fn from(err: NulError) -> Self {
231        Self::NulError(err)
232    }
233}
234
235const UNKNOWN_COLUMN: usize = usize::MAX;
236
237/// The conversion isn't precise, but it's convenient to have it
238/// to allow use of `get_raw(…).as_…()?` in callbacks that take `Error`.
239impl From<FromSqlError> for Error {
240    #[cold]
241    fn from(err: FromSqlError) -> Self {
242        // The error type requires index and type fields, but they aren't known in this
243        // context.
244        match err {
245            FromSqlError::OutOfRange(val) => Self::IntegralValueOutOfRange(UNKNOWN_COLUMN, val),
246            FromSqlError::InvalidBlobSize { .. } => {
247                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Blob, Box::new(err))
248            }
249            FromSqlError::Other(source) => {
250                Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, source)
251            }
252            _ => Self::FromSqlConversionFailure(UNKNOWN_COLUMN, Type::Null, Box::new(err)),
253        }
254    }
255}
256
257#[cfg(feature = "loadable_extension")]
258impl From<ffi::InitError> for Error {
259    #[cold]
260    fn from(err: ffi::InitError) -> Self {
261        Self::InitError(err)
262    }
263}
264
265impl fmt::Display for Error {
266    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267        match *self {
268            Self::SqliteFailure(ref err, None) => err.fmt(f),
269            Self::SqliteFailure(_, Some(ref s)) => write!(f, "{s}"),
270            Self::SqliteSingleThreadedMode => write!(
271                f,
272                "SQLite was compiled or configured for single-threaded use only"
273            ),
274            Self::FromSqlConversionFailure(i, ref t, ref err) => {
275                if i == UNKNOWN_COLUMN {
276                    err.fmt(f)
277                } else {
278                    write!(f, "Conversion error from type {t} at index: {i}, {err}")
279                }
280            }
281            Self::IntegralValueOutOfRange(col, val) => {
282                if col == UNKNOWN_COLUMN {
283                    write!(f, "Integer {val} out of range")
284                } else {
285                    write!(f, "Integer {val} out of range at index {col}")
286                }
287            }
288            Self::Utf8Error(col, ref err) => {
289                if col == UNKNOWN_COLUMN {
290                    err.fmt(f)
291                } else {
292                    write!(f, "{err} at index {col}")
293                }
294            }
295            Self::NulError(ref err) => err.fmt(f),
296            Self::InvalidParameterName(ref name) => write!(f, "Invalid parameter name: {name}"),
297            Self::InvalidPath(ref p) => write!(f, "Invalid path: {}", p.to_string_lossy()),
298            Self::ExecuteReturnedResults => {
299                write!(f, "Execute returned results - did you mean to call query?")
300            }
301            Self::QueryReturnedNoRows => write!(f, "Query returned no rows"),
302            Self::QueryReturnedMoreThanOneRow => write!(f, "Query returned more than one row"),
303            Self::InvalidColumnIndex(i) => write!(f, "Invalid column index: {i}"),
304            Self::InvalidColumnName(ref name) => write!(f, "Invalid column name: {name}"),
305            Self::InvalidColumnType(i, ref name, ref t) => {
306                write!(f, "Invalid column type {t} at index: {i}, name: {name}")
307            }
308            Self::InvalidParameterCount(i1, n1) => write!(
309                f,
310                "Wrong number of parameters passed to query. Got {i1}, needed {n1}"
311            ),
312            Self::StatementChangedRows(i) => write!(f, "Query changed {i} rows"),
313
314            #[cfg(any(feature = "functions", feature = "vtab"))]
315            Self::InvalidParameterType(i, ref t) => {
316                write!(
317                    f,
318                    "Invalid function or filter parameter type {t} at index {i}"
319                )
320            }
321            #[cfg(feature = "functions")]
322            Self::UserFunctionError(ref err) => err.fmt(f),
323            Self::ToSqlConversionFailure(ref err) => err.fmt(f),
324            Self::Empty => write!(f, "SQL is empty or comment only"),
325            Self::InvalidQuery => write!(f, "Query is not read-only"),
326            #[cfg(feature = "vtab")]
327            Self::ModuleError(ref desc) => write!(f, "{desc}"),
328            Self::UnwindingPanic => write!(f, "unwinding panic"),
329            #[cfg(feature = "functions")]
330            Self::GetAuxWrongType => write!(f, "get_aux called with wrong type"),
331            Self::MultipleStatement => write!(f, "Multiple statements provided"),
332            #[cfg(feature = "blob")]
333            Self::BlobSizeError => "Blob size is insufficient".fmt(f),
334            Self::SqlInputError {
335                ref msg,
336                offset,
337                ref sql,
338                ..
339            } => write!(f, "{msg} in {sql} at offset {offset}"),
340            #[cfg(feature = "loadable_extension")]
341            Self::InitError(ref err) => err.fmt(f),
342            Self::InvalidDatabaseIndex(i) => write!(f, "Invalid database index: {i}"),
343        }
344    }
345}
346
347impl error::Error for Error {
348    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
349        match *self {
350            Self::SqliteFailure(ref err, _) => Some(err),
351            Self::Utf8Error(_, ref err) => Some(err),
352            Self::NulError(ref err) => Some(err),
353
354            Self::IntegralValueOutOfRange(..)
355            | Self::SqliteSingleThreadedMode
356            | Self::InvalidParameterName(_)
357            | Self::ExecuteReturnedResults
358            | Self::QueryReturnedNoRows
359            | Self::QueryReturnedMoreThanOneRow
360            | Self::InvalidColumnIndex(_)
361            | Self::InvalidColumnName(_)
362            | Self::InvalidColumnType(..)
363            | Self::InvalidPath(_)
364            | Self::InvalidParameterCount(..)
365            | Self::StatementChangedRows(_)
366            | Self::Empty
367            | Self::InvalidQuery
368            | Self::MultipleStatement => None,
369
370            #[cfg(any(feature = "functions", feature = "vtab"))]
371            Self::InvalidParameterType(..) => None,
372
373            #[cfg(feature = "functions")]
374            Self::UserFunctionError(ref err) => Some(&**err),
375
376            Self::FromSqlConversionFailure(_, _, ref err)
377            | Self::ToSqlConversionFailure(ref err) => Some(&**err),
378
379            #[cfg(feature = "vtab")]
380            Self::ModuleError(_) => None,
381
382            Self::UnwindingPanic => None,
383
384            #[cfg(feature = "functions")]
385            Self::GetAuxWrongType => None,
386
387            #[cfg(feature = "blob")]
388            Self::BlobSizeError => None,
389            Self::SqlInputError { ref error, .. } => Some(error),
390            #[cfg(feature = "loadable_extension")]
391            Self::InitError(ref err) => Some(err),
392            Self::InvalidDatabaseIndex(_) => None,
393        }
394    }
395}
396
397impl Error {
398    /// Returns the underlying SQLite error if this is [`Error::SqliteFailure`].
399    #[inline]
400    #[must_use]
401    pub fn sqlite_error(&self) -> Option<&ffi::Error> {
402        match self {
403            Self::SqliteFailure(error, _) => Some(error),
404            _ => None,
405        }
406    }
407
408    /// Returns the underlying SQLite error code if this is
409    /// [`Error::SqliteFailure`].
410    #[inline]
411    #[must_use]
412    pub fn sqlite_error_code(&self) -> Option<ffi::ErrorCode> {
413        self.sqlite_error().map(|error| error.code)
414    }
415
416    /// Returns the underlying SQLite extended error code if this is
417    /// [`Error::SqliteFailure`].
418    #[inline]
419    #[must_use]
420    pub fn sqlite_extended_error_code(&self) -> Option<c_int> {
421        self.sqlite_error().map(|error| error.extended_code)
422    }
423}
424
425// These are public but not re-exported by lib.rs, so only visible within crate.
426
427#[cold]
428pub fn error_from_sqlite_code(code: c_int, message: Option<String>) -> Error {
429    Error::SqliteFailure(ffi::Error::new(code), message)
430}
431
432macro_rules! err {
433    ($code:expr $(,)?) => {
434        $crate::error::error_from_sqlite_code($code, None)
435    };
436    ($code:expr, $msg:literal $(,)?) => {
437        $crate::error::error_from_sqlite_code($code, Some(format!($msg)))
438    };
439    ($code:expr, $err:expr $(,)?) => {
440        $crate::error::error_from_sqlite_code($code, Some(format!($err)))
441    };
442    ($code:expr, $fmt:expr, $($arg:tt)*) => {
443        $crate::error::error_from_sqlite_code($code, Some(format!($fmt, $($arg)*)))
444    };
445}
446
447#[cold]
448pub unsafe fn error_from_handle(db: *mut ffi::sqlite3, code: c_int) -> Error {
449    error_from_sqlite_code(code, unsafe { error_msg(db, code) })
450}
451
452unsafe fn error_msg(db: *mut ffi::sqlite3, code: c_int) -> Option<String> {
453    unsafe {
454        if db.is_null() || ffi::sqlite3_errcode(db) != code {
455            let err_str = ffi::sqlite3_errstr(code);
456            if err_str.is_null() {
457                None
458            } else {
459                Some(errmsg_to_string(err_str))
460            }
461        } else {
462            Some(errmsg_to_string(ffi::sqlite3_errmsg(db)))
463        }
464    }
465}
466
467pub unsafe fn decode_result_raw(db: *mut ffi::sqlite3, code: c_int) -> Result<()> {
468    if code == ffi::SQLITE_OK {
469        Ok(())
470    } else {
471        Err(unsafe { error_from_handle(db, code) })
472    }
473}
474
475#[cold]
476#[allow(unused_variables)]
477pub unsafe fn error_with_offset(db: *mut ffi::sqlite3, code: c_int, sql: &str) -> Error {
478    unsafe {
479        if db.is_null() {
480            error_from_sqlite_code(code, None)
481        } else {
482            let error = ffi::Error::new(code);
483            let msg = error_msg(db, code);
484            if ffi::ErrorCode::Unknown == error.code {
485                let offset = ffi::sqlite3_error_offset(db);
486                if offset >= 0 {
487                    return Error::SqlInputError {
488                        error,
489                        msg: msg.unwrap_or("error".to_owned()),
490                        sql: sql.to_owned(),
491                        offset,
492                    };
493                }
494            }
495            Error::SqliteFailure(error, msg)
496        }
497    }
498}
499
500pub fn check(code: c_int) -> Result<()> {
501    if code == ffi::SQLITE_OK {
502        Ok(())
503    } else {
504        Err(error_from_sqlite_code(code, None))
505    }
506}
507
508/// Transform Rust error to SQLite error (message and code).
509/// # Safety
510/// This function is unsafe because it uses raw pointer
511pub unsafe fn to_sqlite_error(e: &Error, err_msg: *mut *mut c_char) -> c_int {
512    use crate::util::alloc;
513
514    match e {
515        Error::SqliteFailure(err, s) => {
516            if let Some(s) = s {
517                unsafe { *err_msg = alloc(s) };
518            }
519            err.extended_code
520        }
521        err => {
522            unsafe { *err_msg = alloc(&err.to_string()) };
523            ffi::SQLITE_ERROR
524        }
525    }
526}
527
528/// Set error code and message
529/// # Safety
530/// This function is unsafe because it uses raw pointer
531#[cfg(feature = "modern_sqlite")] // 3.51.0
532pub unsafe fn set_errmsg(
533    db: *mut ffi::sqlite3,
534    code: c_int,
535    msg: Option<&std::ffi::CStr>,
536) -> Result<()> {
537    unsafe {
538        decode_result_raw(
539            db,
540            ffi::sqlite3_set_errmsg(
541                db,
542                code,
543                msg.map_or(std::ptr::null(), std::ffi::CStr::as_ptr),
544            ),
545        )
546    }
547}