Skip to main content

rusqlite/types/
mod.rs

1//! Traits dealing with SQLite data types.
2//!
3//! SQLite uses a [dynamic type system](https://www.sqlite.org/datatype3.html). Implementations of
4//! the [`ToSql`] and [`FromSql`] traits are provided for the basic types that
5//! SQLite provides methods for:
6//!
7//! * Strings (`String` and `&str`)
8//! * Blobs (`Vec<u8>` and `&[u8]`)
9//! * Numbers
10//!
11//! The number situation is a little complicated due to the fact that all
12//! numbers in SQLite are stored as `INTEGER` (`i64`) or `REAL` (`f64`).
13//!
14//! [`ToSql`] and [`FromSql`] are implemented for all primitive number types.
15//! [`FromSql`] has different behaviour depending on the SQL and Rust types, and
16//! the value.
17//!
18//! * `INTEGER` to integer: returns an
19//!   [`Error::IntegralValueOutOfRange`](crate::Error::IntegralValueOutOfRange)
20//!   error if the value does not fit in the Rust type.
21//! * `REAL` to integer: always returns an
22//!   [`Error::InvalidColumnType`](crate::Error::InvalidColumnType) error.
23//! * `INTEGER` to float: casts using `as` operator. Never fails.
24//! * `REAL` to float: casts using `as` operator. Never fails.
25//!
26//! [`ToSql`] always succeeds except when storing a `u64` or `usize` value that
27//! cannot fit in an `INTEGER` (`i64`). Also note that SQLite ignores column
28//! types, so if you store an `i64` in a column with type `REAL` it will be
29//! stored as an `INTEGER`, not a `REAL` (unless the column is part of a
30//! [STRICT table](https://www.sqlite.org/stricttables.html)).
31//!
32//! If the `time` feature is enabled, implementations are
33//! provided for `time::OffsetDateTime` that use the RFC 3339 date/time format,
34//! `"%Y-%m-%dT%H:%M:%S.%fZ"`, to store time values as strings.  These values
35//! can be parsed by SQLite's builtin
36//! [datetime](https://www.sqlite.org/lang_datefunc.html) functions.  If you
37//! want different storage for datetimes, you can use a newtype.
38#![cfg_attr(
39    feature = "time",
40    doc = r"
41For example, to store datetimes as `i64`s counting the number of seconds since
42the Unix epoch:
43
44```
45use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
46use rusqlite::Result;
47
48pub struct DateTimeSql(pub time::OffsetDateTime);
49
50impl FromSql for DateTimeSql {
51    fn column_result(value: ValueRef) -> FromSqlResult<Self> {
52        i64::column_result(value).and_then(|as_i64| {
53            time::OffsetDateTime::from_unix_timestamp(as_i64)
54            .map(|odt| DateTimeSql(odt))
55            .map_err(FromSqlError::other)
56        })
57    }
58}
59
60impl ToSql for DateTimeSql {
61    fn to_sql(&self) -> Result<ToSqlOutput> {
62        Ok(self.0.unix_timestamp().into())
63    }
64}
65```
66
67"
68)]
69//! [`ToSql`] and [`FromSql`] are also implemented for `Option<T>` where `T`
70//! implements [`ToSql`] or [`FromSql`] for the cases where you want to know if
71//! a value was NULL (which gets translated to `None`).
72
73pub use self::from_sql::{FromSql, FromSqlError, FromSqlResult};
74#[cfg(any(feature = "functions", feature = "vtab"))]
75pub use self::raw_value::{RawValue, ValueIter, Values};
76pub use self::to_sql::{ToSql, ToSqlOutput};
77pub use self::value::Value;
78pub use self::value_ref::ValueRef;
79
80use std::fmt;
81
82#[cfg(feature = "chrono")]
83mod chrono;
84mod from_sql;
85#[cfg(feature = "jiff")]
86mod jiff;
87#[cfg(any(feature = "functions", feature = "vtab"))]
88mod raw_value;
89#[cfg(feature = "serde_json")]
90mod serde_json;
91#[cfg(feature = "time")]
92mod time;
93mod to_sql;
94#[cfg(feature = "url")]
95mod url;
96mod value;
97mod value_ref;
98
99/// Empty struct that can be used to fill in a query parameter as `NULL`.
100///
101/// ## Example
102///
103/// ```rust,no_run
104/// # use rusqlite::{Connection, Result};
105/// # use rusqlite::types::{Null};
106///
107/// fn insert_null(conn: &Connection) -> Result<usize> {
108///     conn.execute("INSERT INTO people (name) VALUES (?1)", [Null])
109/// }
110/// ```
111#[derive(Copy, Clone)]
112pub struct Null;
113
114/// SQLite data types.
115/// See [Fundamental Datatypes](https://sqlite.org/c3ref/c_blob.html).
116#[derive(Copy, Clone, Debug, PartialEq, Eq)]
117pub enum Type {
118    /// NULL
119    Null,
120    /// 64-bit signed integer
121    Integer,
122    /// 64-bit IEEE floating point number
123    Real,
124    /// String
125    Text,
126    /// BLOB
127    Blob,
128}
129
130impl fmt::Display for Type {
131    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132        match *self {
133            Self::Null => f.pad("Null"),
134            Self::Integer => f.pad("Integer"),
135            Self::Real => f.pad("Real"),
136            Self::Text => f.pad("Text"),
137            Self::Blob => f.pad("Blob"),
138        }
139    }
140}
141
142#[cfg(all(test, not(miri)))]
143mod test {
144    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
145    use wasm_bindgen_test::wasm_bindgen_test as test;
146
147    use super::Value;
148    use crate::{Connection, Error, Result, Statement, params};
149    use std::ffi::{c_double, c_int};
150
151    fn checked_memory_handle() -> Result<Connection> {
152        let db = Connection::open_in_memory()?;
153        db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)")?;
154        Ok(db)
155    }
156
157    #[test]
158    fn test_blob() -> Result<()> {
159        let db = checked_memory_handle()?;
160
161        let v1234 = vec![1u8, 2, 3, 4];
162        db.execute("INSERT INTO foo(b) VALUES (?1)", [&v1234])?;
163
164        let v: Vec<u8> = db.one_column("SELECT b FROM foo", [])?;
165        assert_eq!(v, v1234);
166        Ok(())
167    }
168
169    #[test]
170    fn test_empty_blob() -> Result<()> {
171        let db = checked_memory_handle()?;
172
173        let empty = vec![];
174        db.execute("INSERT INTO foo(b) VALUES (?1)", [&empty])?;
175
176        let v: Vec<u8> = db.one_column("SELECT b FROM foo", [])?;
177        assert_eq!(v, empty);
178        Ok(())
179    }
180
181    #[test]
182    fn test_str() -> Result<()> {
183        let db = checked_memory_handle()?;
184
185        let s = "hello, world!";
186        db.execute("INSERT INTO foo(t) VALUES (?1)", [&s])?;
187
188        let from: String = db.one_column("SELECT t FROM foo", [])?;
189        assert_eq!(from, s);
190        Ok(())
191    }
192
193    #[test]
194    fn test_string() -> Result<()> {
195        let db = checked_memory_handle()?;
196
197        let s = "hello, world!";
198        db.execute("INSERT INTO foo(t) VALUES (?1)", [s.to_owned()])?;
199
200        let from: String = db.one_column("SELECT t FROM foo", [])?;
201        assert_eq!(from, s);
202        Ok(())
203    }
204
205    #[test]
206    fn test_value() -> Result<()> {
207        let db = checked_memory_handle()?;
208
209        db.execute("INSERT INTO foo(i) VALUES (?1)", [Value::Integer(10)])?;
210
211        assert_eq!(10, db.one_column::<i64, _>("SELECT i FROM foo", [])?);
212        Ok(())
213    }
214
215    #[test]
216    fn test_option() -> Result<()> {
217        let db = checked_memory_handle()?;
218
219        let s = "hello, world!";
220        let b = Some(vec![1u8, 2, 3, 4]);
221
222        db.execute("INSERT INTO foo(t) VALUES (?1)", [Some(s)])?;
223        db.execute("INSERT INTO foo(b) VALUES (?1)", [&b])?;
224
225        let mut stmt = db.prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")?;
226        let mut rows = stmt.query([])?;
227
228        {
229            let row1 = rows.next()?.unwrap();
230            let s1: Option<String> = row1.get_unwrap(0);
231            let b1: Option<Vec<u8>> = row1.get_unwrap(1);
232            assert_eq!(s, s1.unwrap());
233            assert!(b1.is_none());
234        }
235
236        {
237            let row2 = rows.next()?.unwrap();
238            let s2: Option<String> = row2.get_unwrap(0);
239            let b2: Option<Vec<u8>> = row2.get_unwrap(1);
240            assert!(s2.is_none());
241            assert_eq!(b, b2);
242        }
243        Ok(())
244    }
245
246    #[test]
247    #[expect(clippy::cognitive_complexity)]
248    fn test_mismatched_types() -> Result<()> {
249        fn is_invalid_column_type(err: Error) -> bool {
250            matches!(err, Error::InvalidColumnType(..))
251        }
252
253        let db = checked_memory_handle()?;
254
255        db.execute(
256            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
257            [],
258        )?;
259
260        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo")?;
261        let mut rows = stmt.query([])?;
262
263        let row = rows.next()?.unwrap();
264
265        // check the correct types come back as expected
266        assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0)?);
267        assert_eq!("text", row.get::<_, String>(1)?);
268        assert_eq!(1, row.get::<_, c_int>(2)?);
269        assert!((1.5 - row.get::<_, c_double>(3)?).abs() < f64::EPSILON);
270        assert_eq!(row.get::<_, Option<c_int>>(4)?, None);
271        assert_eq!(row.get::<_, Option<c_double>>(4)?, None);
272        assert_eq!(row.get::<_, Option<String>>(4)?, None);
273
274        // check some invalid types
275
276        // 0 is actually a blob (Vec<u8>)
277        assert!(is_invalid_column_type(row.get::<_, c_int>(0).unwrap_err()));
278        assert!(is_invalid_column_type(row.get::<_, c_int>(0).unwrap_err()));
279        assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
280        assert!(is_invalid_column_type(
281            row.get::<_, c_double>(0).unwrap_err()
282        ));
283        assert!(is_invalid_column_type(row.get::<_, String>(0).unwrap_err()));
284        #[cfg(feature = "time")]
285        assert!(is_invalid_column_type(
286            row.get::<_, time::OffsetDateTime>(0).unwrap_err()
287        ));
288        assert!(is_invalid_column_type(
289            row.get::<_, Option<c_int>>(0).unwrap_err()
290        ));
291
292        // 1 is actually a text (String)
293        assert!(is_invalid_column_type(row.get::<_, c_int>(1).unwrap_err()));
294        assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
295        assert!(is_invalid_column_type(
296            row.get::<_, c_double>(1).unwrap_err()
297        ));
298        assert!(is_invalid_column_type(
299            row.get::<_, Vec<u8>>(1).unwrap_err()
300        ));
301        assert!(is_invalid_column_type(
302            row.get::<_, Option<c_int>>(1).unwrap_err()
303        ));
304
305        // 2 is actually an integer
306        assert!(is_invalid_column_type(row.get::<_, String>(2).unwrap_err()));
307        assert!(is_invalid_column_type(
308            row.get::<_, Vec<u8>>(2).unwrap_err()
309        ));
310        assert!(is_invalid_column_type(
311            row.get::<_, Option<String>>(2).unwrap_err()
312        ));
313
314        // 3 is actually a float (c_double)
315        assert!(is_invalid_column_type(row.get::<_, c_int>(3).unwrap_err()));
316        assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
317        assert!(is_invalid_column_type(row.get::<_, String>(3).unwrap_err()));
318        assert!(is_invalid_column_type(
319            row.get::<_, Vec<u8>>(3).unwrap_err()
320        ));
321        assert!(is_invalid_column_type(
322            row.get::<_, Option<c_int>>(3).unwrap_err()
323        ));
324
325        // 4 is actually NULL
326        assert!(is_invalid_column_type(row.get::<_, c_int>(4).unwrap_err()));
327        assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
328        assert!(is_invalid_column_type(
329            row.get::<_, c_double>(4).unwrap_err()
330        ));
331        assert!(is_invalid_column_type(row.get::<_, String>(4).unwrap_err()));
332        assert!(is_invalid_column_type(
333            row.get::<_, Vec<u8>>(4).unwrap_err()
334        ));
335        #[cfg(feature = "time")]
336        assert!(is_invalid_column_type(
337            row.get::<_, time::OffsetDateTime>(4).unwrap_err()
338        ));
339        Ok(())
340    }
341
342    #[test]
343    fn test_dynamic_type() -> Result<()> {
344        use super::Value;
345        let db = checked_memory_handle()?;
346
347        db.execute(
348            "INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
349            [],
350        )?;
351
352        let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo")?;
353        let mut rows = stmt.query([])?;
354
355        let row = rows.next()?.unwrap();
356        assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0)?);
357        assert_eq!(Value::Text(String::from("text")), row.get::<_, Value>(1)?);
358        assert_eq!(Value::Integer(1), row.get::<_, Value>(2)?);
359        match row.get::<_, Value>(3)? {
360            Value::Real(val) => assert!((1.5 - val).abs() < f64::EPSILON),
361            x => panic!("Invalid Value {x:?}"),
362        }
363        assert_eq!(Value::Null, row.get::<_, Value>(4)?);
364        Ok(())
365    }
366
367    macro_rules! test_conversion {
368        ($db_etc:ident, $insert_value:expr, $get_type:ty,expect $expected_value:expr) => {
369            $db_etc.insert_statement.execute(params![$insert_value])?;
370            let res = $db_etc
371                .query_statement
372                .query_row([], |row| row.get::<_, $get_type>(0));
373            assert_eq!(res?, $expected_value);
374            $db_etc.delete_statement.execute([])?;
375        };
376        ($db_etc:ident, $insert_value:expr, $get_type:ty,expect_from_sql_error) => {
377            $db_etc.insert_statement.execute(params![$insert_value])?;
378            let res = $db_etc
379                .query_statement
380                .query_row([], |row| row.get::<_, $get_type>(0));
381            res.unwrap_err();
382            $db_etc.delete_statement.execute([])?;
383        };
384        ($db_etc:ident, $insert_value:expr, $get_type:ty,expect_to_sql_error) => {
385            $db_etc
386                .insert_statement
387                .execute(params![$insert_value])
388                .unwrap_err();
389        };
390    }
391
392    #[test]
393    fn test_numeric_conversions() -> Result<()> {
394        // Test what happens when we store a f32 and retrieve an i32 etc.
395        let db = Connection::open_in_memory()?;
396        db.execute_batch("CREATE TABLE foo (x)")?;
397
398        // SQLite actually ignores the column types, so we just need to test
399        // different numeric values.
400
401        struct DbEtc<'conn> {
402            insert_statement: Statement<'conn>,
403            query_statement: Statement<'conn>,
404            delete_statement: Statement<'conn>,
405        }
406
407        let mut db_etc = DbEtc {
408            insert_statement: db.prepare("INSERT INTO foo VALUES (?1)")?,
409            query_statement: db.prepare("SELECT x FROM foo")?,
410            delete_statement: db.prepare("DELETE FROM foo")?,
411        };
412
413        // Basic non-converting test.
414        test_conversion!(db_etc, 0u8, u8, expect 0u8);
415
416        // In-range integral conversions.
417        test_conversion!(db_etc, 100u8, i8, expect 100i8);
418        test_conversion!(db_etc, 200u8, u8, expect 200u8);
419        test_conversion!(db_etc, 100u16, i8, expect 100i8);
420        test_conversion!(db_etc, 200u16, u8, expect 200u8);
421        #[cfg(feature = "fallible_uint")]
422        test_conversion!(db_etc, u32::MAX, u64, expect u32::MAX as u64);
423
424        test_conversion!(db_etc, i64::MIN, i64, expect i64::MIN);
425        test_conversion!(db_etc, i64::MAX, i64, expect i64::MAX);
426        #[cfg(feature = "fallible_uint")]
427        test_conversion!(db_etc, i64::MAX, u64, expect i64::MAX as u64);
428        #[cfg(feature = "fallible_uint")]
429        test_conversion!(db_etc, 100usize, usize, expect 100usize);
430        #[cfg(feature = "fallible_uint")]
431        test_conversion!(db_etc, 100u64, u64, expect 100u64);
432        #[cfg(feature = "fallible_uint")]
433        test_conversion!(db_etc, i64::MAX as u64, u64, expect i64::MAX as u64);
434
435        // Out-of-range integral conversions.
436        test_conversion!(db_etc, 200u8, i8, expect_from_sql_error);
437        test_conversion!(db_etc, 400u16, i8, expect_from_sql_error);
438        test_conversion!(db_etc, 400u16, u8, expect_from_sql_error);
439        test_conversion!(db_etc, -1i8, u8, expect_from_sql_error);
440        #[cfg(feature = "fallible_uint")]
441        test_conversion!(db_etc, i64::MIN, u64, expect_from_sql_error);
442        #[cfg(feature = "fallible_uint")]
443        test_conversion!(db_etc, u64::MAX, i64, expect_to_sql_error);
444        #[cfg(feature = "fallible_uint")]
445        test_conversion!(db_etc, u64::MAX, u64, expect_to_sql_error);
446        #[cfg(feature = "fallible_uint")]
447        test_conversion!(db_etc, i64::MAX as u64 + 1, u64, expect_to_sql_error);
448
449        // FromSql integer to float, always works.
450        test_conversion!(db_etc, i64::MIN, f32, expect i64::MIN as f32);
451        test_conversion!(db_etc, i64::MAX, f32, expect i64::MAX as f32);
452        test_conversion!(db_etc, i64::MIN, f64, expect i64::MIN as f64);
453        test_conversion!(db_etc, i64::MAX, f64, expect i64::MAX as f64);
454
455        // FromSql float to int conversion, never works even if the actual value
456        // is an integer.
457        test_conversion!(db_etc, 0f64, i64, expect_from_sql_error);
458        Ok(())
459    }
460}