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
362
363
364
365
366
367
368
369
//! Traits dealing with SQLite data types.
//!
//! SQLite uses a [dynamic type system](https://www.sqlite.org/datatype3.html). Implementations of
//! the `ToSql` and `FromSql` traits are provided for the basic types that
//! SQLite provides methods for:
//!
//! * Integers (`i32` and `i64`; SQLite uses `i64` internally, so getting an
//! `i32` will truncate   if the value is too large or too small).
//! * Reals (`f64`)
//! * Strings (`String` and `&str`)
//! * Blobs (`Vec<u8>` and `&[u8]`)
//!
//! Additionally, because it is such a common data type, implementations are
//! provided for `time::Timespec` that use the RFC 3339 date/time format,
//! `"%Y-%m-%dT%H:%M:%S.%fZ"`, to store time values as strings.  These values
//! can be parsed by SQLite's builtin
//! [datetime](https://www.sqlite.org/lang_datefunc.html) functions.  If you
//! want different storage for timespecs, you can use a newtype. For example, to
//! store timespecs as `f64`s:
//!
//! ```rust
//! use rusqlite::types::{FromSql, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
//! use rusqlite::Result;
//!
//! pub struct TimespecSql(pub time::Timespec);
//!
//! impl FromSql for TimespecSql {
//!     fn column_result(value: ValueRef) -> FromSqlResult<Self> {
//!         f64::column_result(value).map(|as_f64| {
//!             TimespecSql(time::Timespec {
//!                 sec: as_f64.trunc() as i64,
//!                 nsec: (as_f64.fract() * 1.0e9) as i32,
//!             })
//!         })
//!     }
//! }
//!
//! impl ToSql for TimespecSql {
//!     fn to_sql(&self) -> Result<ToSqlOutput> {
//!         let TimespecSql(ts) = *self;
//!         let as_f64 = ts.sec as f64 + (ts.nsec as f64) / 1.0e9;
//!         Ok(as_f64.into())
//!     }
//! }
//!
//! # // Prevent this doc test from being wrapped in a `fn main()` so that it
//! # // will compile.
//! # fn main() {}
//! ```
//!
//! `ToSql` and `FromSql` are also implemented for `Option<T>` where `T`
//! implements `ToSql` or `FromSql` for the cases where you want to know if a
//! value was NULL (which gets translated to `None`).

pub use self::from_sql::{FromSql, FromSqlError, FromSqlResult};
pub use self::to_sql::{ToSql, ToSqlOutput};
pub use self::value::Value;
pub use self::value_ref::ValueRef;

use std::fmt;

#[cfg(feature = "chrono")]
mod chrono;
mod from_sql;
#[cfg(feature = "serde_json")]
mod serde_json;
mod time;
mod to_sql;
#[cfg(feature = "url")]
mod url;
mod value;
mod value_ref;

/// Empty struct that can be used to fill in a query parameter as `NULL`.
///
/// ## Example
///
/// ```rust,no_run
/// # use rusqlite::{Connection, Result};
/// # use rusqlite::types::{Null};
/// fn main() {}
/// fn insert_null(conn: &Connection) -> Result<usize> {
///     conn.execute("INSERT INTO people (name) VALUES (?)", &[Null])
/// }
/// ```
#[derive(Copy, Clone)]
pub struct Null;

#[derive(Clone, Debug, PartialEq)]
pub enum Type {
    Null,
    Integer,
    Real,
    Text,
    Blob,
}

impl fmt::Display for Type {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Type::Null => write!(f, "Null"),
            Type::Integer => write!(f, "Integer"),
            Type::Real => write!(f, "Real"),
            Type::Text => write!(f, "Text"),
            Type::Blob => write!(f, "Blob"),
        }
    }
}

#[cfg(test)]
mod test {
    use time;

    use super::Value;
    use crate::{Connection, Error, NO_PARAMS};
    use std::f64::EPSILON;
    use std::os::raw::{c_double, c_int};

    fn checked_memory_handle() -> Connection {
        let db = Connection::open_in_memory().unwrap();
        db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)")
            .unwrap();
        db
    }

    #[test]
    fn test_blob() {
        let db = checked_memory_handle();

        let v1234 = vec![1u8, 2, 3, 4];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&v1234])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, v1234);
    }

    #[test]
    fn test_empty_blob() {
        let db = checked_memory_handle();

        let empty = vec![];
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&empty])
            .unwrap();

        let v: Vec<u8> = db
            .query_row("SELECT b FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(v, empty);
    }

    #[test]
    fn test_str() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_string() {
        let db = checked_memory_handle();

        let s = "hello, world!";
        db.execute("INSERT INTO foo(t) VALUES (?)", &[s.to_owned()])
            .unwrap();

        let from: String = db
            .query_row("SELECT t FROM foo", NO_PARAMS, |r| r.get(0))
            .unwrap();
        assert_eq!(from, s);
    }

    #[test]
    fn test_value() {
        let db = checked_memory_handle();

        db.execute("INSERT INTO foo(i) VALUES (?)", &[Value::Integer(10)])
            .unwrap();

        assert_eq!(
            10i64,
            db.query_row::<i64, _, _>("SELECT i FROM foo", NO_PARAMS, |r| r.get(0))
                .unwrap()
        );
    }

    #[test]
    fn test_option() {
        let db = checked_memory_handle();

        let s = Some("hello, world!");
        let b = Some(vec![1u8, 2, 3, 4]);

        db.execute("INSERT INTO foo(t) VALUES (?)", &[&s]).unwrap();
        db.execute("INSERT INTO foo(b) VALUES (?)", &[&b]).unwrap();

        let mut stmt = db
            .prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")
            .unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        {
            let row1 = rows.next().unwrap().unwrap();
            let s1: Option<String> = row1.get_unwrap(0);
            let b1: Option<Vec<u8>> = row1.get_unwrap(1);
            assert_eq!(s.unwrap(), s1.unwrap());
            assert!(b1.is_none());
        }

        {
            let row2 = rows.next().unwrap().unwrap();
            let s2: Option<String> = row2.get_unwrap(0);
            let b2: Option<Vec<u8>> = row2.get_unwrap(1);
            assert!(s2.is_none());
            assert_eq!(b, b2);
        }
    }

    #[test]
    #[allow(clippy::cognitive_complexity)]
    fn test_mismatched_types() {
        fn is_invalid_column_type(err: Error) -> bool {
            match err {
                Error::InvalidColumnType(_, _, _) => true,
                _ => false,
            }
        }

        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();

        // check the correct types come back as expected
        assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0).unwrap());
        assert_eq!("text", row.get::<_, String>(1).unwrap());
        assert_eq!(1, row.get::<_, c_int>(2).unwrap());
        assert!((1.5 - row.get::<_, c_double>(3).unwrap()).abs() < EPSILON);
        assert!(row.get::<_, Option<c_int>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<c_double>>(4).unwrap().is_none());
        assert!(row.get::<_, Option<String>>(4).unwrap().is_none());

        // check some invalid types

        // 0 is actually a blob (Vec<u8>)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, time::Timespec>(0).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(0).err().unwrap()
        ));

        // 1 is actually a text (String)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(1).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(1).err().unwrap()
        ));

        // 2 is actually an integer
        assert!(is_invalid_column_type(
            row.get::<_, String>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(2).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<String>>(2).err().unwrap()
        ));

        // 3 is actually a float (c_double)
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, String>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(3).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Option<c_int>>(3).err().unwrap()
        ));

        // 4 is actually NULL
        assert!(is_invalid_column_type(
            row.get::<_, c_int>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
        assert!(is_invalid_column_type(
            row.get::<_, c_double>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, String>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, Vec<u8>>(4).err().unwrap()
        ));
        assert!(is_invalid_column_type(
            row.get::<_, time::Timespec>(4).err().unwrap()
        ));
    }

    #[test]
    fn test_dynamic_type() {
        use super::Value;
        let db = checked_memory_handle();

        db.execute(
            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
            NO_PARAMS,
        )
        .unwrap();

        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo").unwrap();
        let mut rows = stmt.query(NO_PARAMS).unwrap();

        let row = rows.next().unwrap().unwrap();
        assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0).unwrap());
        assert_eq!(
            Value::Text(String::from("text")),
            row.get::<_, Value>(1).unwrap()
        );
        assert_eq!(Value::Integer(1), row.get::<_, Value>(2).unwrap());
        match row.get::<_, Value>(3).unwrap() {
            Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
            x => panic!("Invalid Value {:?}", x),
        }
        assert_eq!(Value::Null, row.get::<_, Value>(4).unwrap());
    }
}