rbdc_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_extended_errcode};
8
9// Error Codes And Messages
10// https://www.sqlite.org/c3ref/errcode.html
11
12#[derive(Debug)]
13pub struct SqliteError {
14    code: c_int,
15    message: String,
16}
17
18impl SqliteError {
19    pub(crate) fn new(handle: *mut sqlite3) -> Self {
20        // returns the extended result code even when extended result codes are disabled
21        let code: c_int = unsafe { sqlite3_extended_errcode(handle) };
22
23        // return English-language text that describes the error
24        let message = unsafe {
25            let msg = sqlite3_errmsg(handle);
26            debug_assert!(!msg.is_null());
27
28            from_utf8_unchecked(CStr::from_ptr(msg).to_bytes())
29        };
30
31        Self {
32            code,
33            message: message.to_owned(),
34        }
35    }
36}
37
38impl Display for SqliteError {
39    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
40        f.pad(&self.message)
41    }
42}
43
44impl StdError for SqliteError {}
45
46impl SqliteError {
47    /// The extended result code.
48    #[inline]
49    pub fn code(&self) -> Option<Cow<'_, str>> {
50        Some(format!("{}", self.code).into())
51    }
52
53    #[inline]
54    pub fn message(&self) -> &str {
55        &self.message
56    }
57
58    #[doc(hidden)]
59    pub fn as_error(&self) -> &(dyn StdError + Send + Sync + 'static) {
60        self
61    }
62
63    #[doc(hidden)]
64    pub fn as_error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
65        self
66    }
67
68    #[doc(hidden)]
69    pub fn into_error(self: Box<Self>) -> Box<dyn StdError + Send + Sync + 'static> {
70        self
71    }
72}
73
74impl From<SqliteError> for rbdc::Error {
75    fn from(e: SqliteError) -> Self {
76        Self::from(e.to_string())
77    }
78}