1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
//! Interface to [SQLite][1].
//!
//! ## Example
//!
//! Open a connection, create a table, and insert a few rows:
//!
//! ```
//! let connection = sqlite::open(":memory:").unwrap();
//!
//! connection
//!     .execute(
//!         "
//!         CREATE TABLE users (name TEXT, age INTEGER);
//!         INSERT INTO users VALUES ('Alice', 42);
//!         INSERT INTO users VALUES ('Bob', 69);
//!         ",
//!     )
//!     .unwrap();
//! ```
//!
//! Select some rows and process them one by one as plain text:
//!
//! ```
//! # let connection = sqlite::open(":memory:").unwrap();
//! # connection
//! #     .execute(
//! #         "
//! #         CREATE TABLE users (name TEXT, age INTEGER);
//! #         INSERT INTO users VALUES ('Alice', 42);
//! #         INSERT INTO users VALUES ('Bob', 69);
//! #         ",
//! #     )
//! #     .unwrap();
//! connection
//!     .iterate("SELECT * FROM users WHERE age > 50", |pairs| {
//!         for &(column, value) in pairs.iter() {
//!             println!("{} = {}", column, value.unwrap());
//!         }
//!         true
//!     })
//!     .unwrap();
//! ```
//!
//! Run the same query but using a prepared statement, which is much more
//! efficient than the previous technique:
//!
//! ```
//! use sqlite::State;
//! # let connection = sqlite::open(":memory:").unwrap();
//! # connection
//! #     .execute(
//! #         "
//! #         CREATE TABLE users (name TEXT, age INTEGER);
//! #         INSERT INTO users VALUES ('Alice', 42);
//! #         INSERT INTO users VALUES ('Bob', 69);
//! #         ",
//! #     )
//! #     .unwrap();
//!
//! let mut statement = connection.prepare("SELECT * FROM users WHERE age > ?").unwrap();
//! statement.bind(1, 50).unwrap();
//!
//! while let Ok(State::Row) = statement.next() {
//!     println!("name = {}", statement.read::<String>(0).unwrap());
//!     println!("age = {}", statement.read::<i64>(1).unwrap());
//! }
//! ```
//!
//! Run the same query but using a cursor, which is a wrapper around a prepared
//! statement providing the notion of row and featuring all-at-once binding:
//!
//! ```
//! use sqlite::Value;
//! # let connection = sqlite::open(":memory:").unwrap();
//! # connection
//! #     .execute(
//! #         "
//! #         CREATE TABLE users (name TEXT, age INTEGER);
//! #         INSERT INTO users VALUES ('Alice', 42);
//! #         INSERT INTO users VALUES ('Bob', 69);
//! #         ",
//! #     )
//! #     .unwrap();
//!
//! let cursor = connection
//!     .prepare("SELECT * FROM users WHERE age > ?")
//!     .unwrap()
//!     .into_cursor()
//!     .bind(&[50.into()])
//!     .unwrap();
//!
//! for row in cursor.map(|row| row.unwrap()) {
//!     println!("name = {}", row.get::<String, _>("name"));
//!     println!("age = {}", row.get::<i64, _>("age"));
//! }
//! ```
//!
//! [1]: https://www.sqlite.org

extern crate libc;
extern crate sqlite3_sys as ffi;

use std::{error, fmt};

macro_rules! raise(
    ($message:expr $(, $($token:tt)* )?) => (
        return Err(::Error {
            code: None,
            message: Some(format!($message $(, $($token)* )*)),
        })
    );
);

macro_rules! error(
    ($connection:expr, $code:expr) => (
        match ::last_error($connection) {
            Some(error) => return Err(error),
            _ => return Err(::Error {
                code: Some($code as isize),
                message: None,
            }),
        }
    );
);

macro_rules! ok(
    ($connection:expr, $result:expr) => (
        match $result {
            ::ffi::SQLITE_OK => {}
            code => error!($connection, code),
        }
    );
    ($result:expr) => (
        match $result {
            ::ffi::SQLITE_OK => {}
            code => return Err(::Error {
                code: Some(code as isize),
                message: None,
            }),
        }
    );
);

macro_rules! c_str_to_str(
    ($string:expr) => (::std::str::from_utf8(::std::ffi::CStr::from_ptr($string).to_bytes()));
);

macro_rules! c_str_to_string(
    ($string:expr) => (
        String::from_utf8_lossy(::std::ffi::CStr::from_ptr($string as *const _).to_bytes())
               .into_owned()
    );
);

macro_rules! path_to_cstr(
    ($path:expr) => (
        match $path.to_str() {
            Some(path) => {
                match ::std::ffi::CString::new(path) {
                    Ok(string) => string,
                    _ => raise!("failed to process a path"),
                }
            }
            _ => raise!("failed to process a path"),
        }
    );
);

macro_rules! str_to_cstr(
    ($string:expr) => (
        match ::std::ffi::CString::new($string) {
            Ok(string) => string,
            _ => raise!("failed to process a string"),
        }
    );
);

/// An error.
#[derive(Debug)]
pub struct Error {
    /// The error code.
    pub code: Option<isize>,
    /// The error message.
    pub message: Option<String>,
}

/// A result.
pub type Result<T> = std::result::Result<T, Error>;

/// A data type.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Type {
    /// The binary type.
    Binary,
    /// The floating-point type.
    Float,
    /// The integer type.
    Integer,
    /// The string type.
    String,
    /// The null type.
    Null,
}

/// A value of a specific type.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// Binary data.
    Binary(Vec<u8>),
    /// A floating-point number.
    Float(f64),
    /// An integer number.
    Integer(i64),
    /// A string.
    String(String),
    /// A null value.
    Null,
}

impl fmt::Display for Error {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match (self.code, &self.message) {
            (Some(code), &Some(ref message)) => write!(formatter, "{} (code {})", message, code),
            (Some(code), _) => write!(formatter, "an SQLite error (code {})", code),
            (_, &Some(ref message)) => message.fmt(formatter),
            _ => write!(formatter, "an SQLite error"),
        }
    }
}

impl error::Error for Error {
    fn description(&self) -> &str {
        match self.message {
            Some(ref message) => message,
            _ => "an SQLite error",
        }
    }
}

impl Value {
    /// Return the binary data if the value is `Binary`.
    #[inline]
    pub fn as_binary(&self) -> Option<&[u8]> {
        if let &Value::Binary(ref value) = self {
            return Some(value);
        }
        None
    }

    /// Return the floating-point number if the value is `Float`.
    #[inline]
    pub fn as_float(&self) -> Option<f64> {
        if let &Value::Float(value) = self {
            return Some(value);
        }
        None
    }

    /// Return the integer number if the value is `Integer`.
    #[inline]
    pub fn as_integer(&self) -> Option<i64> {
        if let &Value::Integer(value) = self {
            return Some(value);
        }
        None
    }

    /// Return the string if the value is `String`.
    #[inline]
    pub fn as_string(&self) -> Option<&str> {
        if let &Value::String(ref value) = self {
            return Some(value);
        }
        None
    }

    /// Return the type.
    pub fn kind(&self) -> Type {
        match self {
            &Value::Binary(_) => Type::Binary,
            &Value::Float(_) => Type::Float,
            &Value::Integer(_) => Type::Integer,
            &Value::String(_) => Type::String,
            &Value::Null => Type::Null,
        }
    }
}

impl From<Vec<u8>> for Value {
    #[inline]
    fn from(value: Vec<u8>) -> Self {
        Value::Binary(value)
    }
}

impl From<f64> for Value {
    #[inline]
    fn from(value: f64) -> Self {
        Value::Float(value)
    }
}

impl From<i64> for Value {
    #[inline]
    fn from(value: i64) -> Self {
        Value::Integer(value)
    }
}

impl From<String> for Value {
    #[inline]
    fn from(value: String) -> Self {
        Value::String(value)
    }
}

impl From<()> for Value {
    #[inline]
    fn from(_: ()) -> Self {
        Value::Null
    }
}

mod connection;
mod cursor;
mod statement;

pub use connection::{Connection, ConnectionWithFullMutex, OpenFlags};
pub use cursor::{ColumnIndex, Cursor, Row, ValueInto};
pub use statement::{Bindable, Readable, State, Statement};

/// Open a read-write connection to a new or existing database.
#[inline]
pub fn open<T: AsRef<std::path::Path>>(path: T) -> Result<Connection> {
    Connection::open(path)
}

/// Return the version number of SQLite.
///
/// For instance, the version `3.8.11.1` corresponds to the integer `3008011`.
#[inline]
pub fn version() -> usize {
    unsafe { ffi::sqlite3_libversion_number() as usize }
}

fn last_error(raw: *mut ffi::sqlite3) -> Option<Error> {
    unsafe {
        let code = ffi::sqlite3_errcode(raw);
        if code == ffi::SQLITE_OK {
            return None;
        }
        let message = ffi::sqlite3_errmsg(raw);
        if message.is_null() {
            return None;
        }
        Some(Error {
            code: Some(code as isize),
            message: Some(c_str_to_string!(message)),
        })
    }
}