sqlx_core_oldapi/sqlite/
error.rs

1use std::error::Error as StdError;
2use std::ffi::CStr;
3use std::fmt::{self, Display, Formatter};
4use std::os::raw::c_int;
5use std::{borrow::Cow, str::from_utf8_unchecked};
6
7use libsqlite3_sys::{sqlite3, sqlite3_errmsg, sqlite3_error_offset, sqlite3_extended_errcode};
8
9use crate::error::DatabaseError;
10
11// Error Codes And Messages
12// https://www.sqlite.org/c3ref/errcode.html
13
14#[derive(Debug)]
15pub struct SqliteError {
16    code: c_int,
17    offset: Option<usize>,
18    message: String,
19}
20
21impl SqliteError {
22    pub(crate) fn new(handle: *mut sqlite3) -> Self {
23        // returns the extended result code even when extended result codes are disabled
24        let code: c_int = unsafe { sqlite3_extended_errcode(handle) };
25
26        // sqlite3_error_offset: byte offset of the start of the token that caused the error, or -1 if unknown
27        let offset = usize::try_from(unsafe { sqlite3_error_offset(handle) }).ok();
28
29        // return English-language text that describes the error
30        let message = unsafe {
31            let msg = sqlite3_errmsg(handle);
32            debug_assert!(!msg.is_null());
33
34            from_utf8_unchecked(CStr::from_ptr(msg).to_bytes())
35        };
36
37        Self {
38            code,
39            offset,
40            message: message.to_owned(),
41        }
42    }
43
44    /// Indicates the byte offset of the start of the statement that failed withing the SQL string that was being executed.
45    pub(crate) fn with_statement_start_index(self, index: usize) -> Self {
46        Self {
47            offset: self.offset.map(|offset| offset + index),
48            ..self
49        }
50    }
51
52    /// For errors during extension load, the error message is supplied via a separate pointer
53    pub(crate) fn extension(handle: *mut sqlite3, error_msg: &CStr) -> Self {
54        let mut err = Self::new(handle);
55        err.message = unsafe { from_utf8_unchecked(error_msg.to_bytes()).to_owned() };
56        err
57    }
58}
59
60impl Display for SqliteError {
61    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
62        // We include the code as some produce ambiguous messages:
63        // SQLITE_BUSY: "database is locked"
64        // SQLITE_LOCKED: "database table is locked"
65        // Sadly there's no function to get the string label back from an error code.
66        write!(f, "(code: {}) {}", self.code, self.message)?;
67        if let Some(offset) = self.offset {
68            write!(f, " (at statement byte offset {})", offset)?;
69        };
70        Ok(())
71    }
72}
73
74impl StdError for SqliteError {}
75
76impl DatabaseError for SqliteError {
77    /// The extended result code.
78    #[inline]
79    fn code(&self) -> Option<Cow<'_, str>> {
80        Some(format!("{}", self.code).into())
81    }
82
83    #[inline]
84    fn message(&self) -> &str {
85        &self.message
86    }
87
88    #[inline]
89    fn offset(&self) -> Option<usize> {
90        self.offset
91    }
92
93    #[doc(hidden)]
94    fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {
95        self
96    }
97
98    #[doc(hidden)]
99    fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
100        self
101    }
102
103    #[doc(hidden)]
104    fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static> {
105        self
106    }
107}