sqlite_bindings_lunatic/
error.rs

1use std::{error, fmt};
2
3/// An error.
4#[derive(Debug)]
5pub struct Error {
6    /// The error code.
7    pub code: Option<isize>,
8    /// The error message.
9    pub message: Option<String>,
10}
11
12/// A result.
13pub type Result<T> = std::result::Result<T, Error>;
14
15macro_rules! error(
16    ($connection:expr, $code:expr) => (
17        match ::error::last($connection) {
18            Some(error) => return Err(error),
19            _ => return Err(::Error {
20                code: Some($code as isize),
21                message: None,
22            }),
23        }
24    );
25);
26
27macro_rules! ok(
28    ($connection:expr, $result:expr) => (
29        match $result {
30            ::ffi::SQLITE_OK => {}
31            code => error!($connection, code),
32        }
33    );
34    ($result:expr) => (
35        match $result {
36            ::ffi::SQLITE_OK => {}
37            code => return Err(::Error {
38                code: Some(code as isize),
39                message: None,
40            }),
41        }
42    );
43);
44
45macro_rules! raise(
46    ($message:expr $(, $($token:tt)* )?) => (
47        return Err(::Error {
48            code: None,
49            message: Some(format!($message $(, $($token)* )*)),
50        })
51    );
52);
53
54impl fmt::Display for Error {
55    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
56        match (self.code, &self.message) {
57            (Some(code), &Some(ref message)) => write!(formatter, "{} (code {})", message, code),
58            (Some(code), _) => write!(formatter, "an SQLite error (code {})", code),
59            (_, &Some(ref message)) => message.fmt(formatter),
60            _ => write!(formatter, "an SQLite error"),
61        }
62    }
63}
64
65impl error::Error for Error {
66    fn description(&self) -> &str {
67        match self.message {
68            Some(ref message) => message,
69            _ => "an SQLite error",
70        }
71    }
72}
73
74pub fn last(raw: *mut ffi::sqlite3) -> Option<Error> {
75    unsafe {
76        let code = ffi::sqlite3_errcode(raw);
77        if code == ffi::SQLITE_OK {
78            return None;
79        }
80        let message = ffi::sqlite3_errmsg(raw);
81        if message.is_null() {
82            return None;
83        }
84        Some(Error {
85            code: Some(code as isize),
86            message: Some(c_str_to_string!(message)),
87        })
88    }
89}