sqlx_build_trust_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::{
8    sqlite3, sqlite3_errmsg, sqlite3_extended_errcode, SQLITE_CONSTRAINT_CHECK,
9    SQLITE_CONSTRAINT_FOREIGNKEY, SQLITE_CONSTRAINT_NOTNULL, SQLITE_CONSTRAINT_PRIMARYKEY,
10    SQLITE_CONSTRAINT_UNIQUE,
11};
12
13pub(crate) use sqlx_core::error::*;
14
15// Error Codes And Messages
16// https://www.sqlite.org/c3ref/errcode.html
17
18#[derive(Debug)]
19pub struct SqliteError {
20    code: c_int,
21    message: String,
22}
23
24impl SqliteError {
25    pub(crate) fn new(handle: *mut sqlite3) -> Self {
26        // returns the extended result code even when extended result codes are disabled
27        let code: c_int = unsafe { sqlite3_extended_errcode(handle) };
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            message: message.to_owned(),
40        }
41    }
42
43    /// For errors during extension load, the error message is supplied via a separate pointer
44    pub(crate) fn extension(handle: *mut sqlite3, error_msg: &CStr) -> Self {
45        let mut err = Self::new(handle);
46        err.message = unsafe { from_utf8_unchecked(error_msg.to_bytes()).to_owned() };
47        err
48    }
49}
50
51impl Display for SqliteError {
52    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
53        // We include the code as some produce ambiguous messages:
54        // SQLITE_BUSY: "database is locked"
55        // SQLITE_LOCKED: "database table is locked"
56        // Sadly there's no function to get the string label back from an error code.
57        write!(f, "(code: {}) {}", self.code, self.message)
58    }
59}
60
61impl StdError for SqliteError {}
62
63impl DatabaseError for SqliteError {
64    #[inline]
65    fn message(&self) -> &str {
66        &self.message
67    }
68
69    /// The extended result code.
70    #[inline]
71    fn code(&self) -> Option<Cow<'_, str>> {
72        Some(format!("{}", self.code).into())
73    }
74
75    #[doc(hidden)]
76    fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {
77        self
78    }
79
80    #[doc(hidden)]
81    fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
82        self
83    }
84
85    #[doc(hidden)]
86    fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static> {
87        self
88    }
89
90    fn kind(&self) -> ErrorKind {
91        match self.code {
92            SQLITE_CONSTRAINT_UNIQUE | SQLITE_CONSTRAINT_PRIMARYKEY => ErrorKind::UniqueViolation,
93            SQLITE_CONSTRAINT_FOREIGNKEY => ErrorKind::ForeignKeyViolation,
94            SQLITE_CONSTRAINT_NOTNULL => ErrorKind::NotNullViolation,
95            SQLITE_CONSTRAINT_CHECK => ErrorKind::CheckViolation,
96            _ => ErrorKind::Other,
97        }
98    }
99}