rusqlite/src/types/mod.rs

469 lines
16 KiB
Rust
Raw Normal View History

2014-11-04 06:11:00 +08:00
//! Traits dealing with SQLite data types.
//!
//! SQLite uses a [dynamic type system](https://www.sqlite.org/datatype3.html). Implementations of
2020-11-22 16:34:03 +08:00
//! the [`ToSql`] and [`FromSql`] traits are provided for the basic types that
2018-08-17 00:29:46 +08:00
//! SQLite provides methods for:
2014-11-04 06:11:00 +08:00
//!
//! * Strings (`String` and `&str`)
//! * Blobs (`Vec<u8>` and `&[u8]`)
//! * Numbers
//!
//! The number situation is a little complicated due to the fact that all
//! numbers in SQLite are stored as `INTEGER` (`i64`) or `REAL` (`f64`).
//!
2020-11-22 16:34:03 +08:00
//! [`ToSql`] and [`FromSql`] are implemented for all primitive number types.
//! [`FromSql`] has different behaviour depending on the SQL and Rust types, and
//! the value.
//!
//! * `INTEGER` to integer: returns an
//! [`Error::IntegralValueOutOfRange`](crate::Error::IntegralValueOutOfRange)
//! error if the value does not fit in the Rust type.
//! * `REAL` to integer: always returns an
//! [`Error::InvalidColumnType`](crate::Error::InvalidColumnType) error.
//! * `INTEGER` to float: casts using `as` operator. Never fails.
//! * `REAL` to float: casts using `as` operator. Never fails.
2014-11-04 06:11:00 +08:00
//!
2020-11-22 16:34:03 +08:00
//! [`ToSql`] always succeeds except when storing a `u64` or `usize` value that
//! cannot fit in an `INTEGER` (`i64`). Also note that SQLite ignores column
//! types, so if you store an `i64` in a column with type `REAL` it will be
//! stored as an `INTEGER`, not a `REAL`.
//!
//! If the `time` feature is enabled, implementations are
//! provided for `time::OffsetDateTime` 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 datetimes, you can use a newtype.
2020-10-04 13:39:35 +08:00
#![cfg_attr(
feature = "time",
doc = r##"
For example, to store datetimes as `i64`s counting the number of seconds since
the Unix epoch:
```
use rusqlite::types::{FromSql, FromSqlError, FromSqlResult, ToSql, ToSqlOutput, ValueRef};
use rusqlite::Result;
pub struct DateTimeSql(pub time::OffsetDateTime);
impl FromSql for DateTimeSql {
fn column_result(value: ValueRef) -> FromSqlResult<Self> {
i64::column_result(value).and_then(|as_i64| {
time::OffsetDateTime::from_unix_timestamp(as_i64)
.map(|odt| DateTimeSql(odt))
.map_err(|err| FromSqlError::Other(Box::new(err)))
})
}
}
impl ToSql for DateTimeSql {
fn to_sql(&self) -> Result<ToSqlOutput> {
Ok(self.0.unix_timestamp().into())
}
}
```
2020-10-04 13:39:35 +08:00
"##
)]
2020-11-22 16:34:03 +08:00
//! [`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`).
2014-11-04 06:11:00 +08:00
pub use self::from_sql::{FromSql, FromSqlError, FromSqlResult};
pub use self::to_sql::{ToSql, ToSqlOutput};
2016-05-26 11:30:34 +08:00
pub use self::value::Value;
2016-05-25 09:34:18 +08:00
pub use self::value_ref::ValueRef;
use std::fmt;
2016-02-23 03:36:49 +08:00
#[cfg(feature = "chrono")]
2021-06-13 15:17:35 +08:00
#[cfg_attr(docsrs, doc(cfg(feature = "chrono")))]
2016-02-23 03:36:49 +08:00
mod chrono;
2018-08-11 18:48:21 +08:00
mod from_sql;
#[cfg(feature = "serde_json")]
2021-06-13 15:17:35 +08:00
#[cfg_attr(docsrs, doc(cfg(feature = "serde_json")))]
mod serde_json;
#[cfg(feature = "time")]
2021-06-13 15:17:35 +08:00
#[cfg_attr(docsrs, doc(cfg(feature = "time")))]
2018-08-11 18:48:21 +08:00
mod time;
mod to_sql;
2019-03-10 11:16:37 +08:00
#[cfg(feature = "url")]
2021-06-13 15:17:35 +08:00
#[cfg_attr(docsrs, doc(cfg(feature = "url")))]
2019-03-10 11:16:37 +08:00
mod url;
2018-08-11 18:48:21 +08:00
mod value;
mod value_ref;
2016-02-23 03:36:49 +08:00
2014-11-04 06:11:00 +08:00
/// Empty struct that can be used to fill in a query parameter as `NULL`.
///
/// ## Example
///
/// ```rust,no_run
2015-12-13 03:06:03 +08:00
/// # use rusqlite::{Connection, Result};
2014-11-04 06:11:00 +08:00
/// # use rusqlite::types::{Null};
2019-10-13 19:08:33 +08:00
///
/// fn insert_null(conn: &Connection) -> Result<usize> {
/// conn.execute("INSERT INTO people (name) VALUES (?)", [Null])
2014-11-04 06:11:00 +08:00
/// }
/// ```
2018-08-11 18:48:21 +08:00
#[derive(Copy, Clone)]
2014-10-20 07:56:41 +08:00
pub struct Null;
2020-05-17 17:21:10 +08:00
/// SQLite data types.
/// See [Fundamental Datatypes](https://sqlite.org/c3ref/c_blob.html).
2018-08-11 18:48:21 +08:00
#[derive(Clone, Debug, PartialEq)]
pub enum Type {
2020-05-17 17:21:10 +08:00
/// NULL
Null,
2020-05-17 17:21:10 +08:00
/// 64-bit signed integer
Integer,
2020-05-17 17:21:10 +08:00
/// 64-bit IEEE floating point number
Real,
2020-05-17 17:21:10 +08:00
/// String
Text,
2020-05-17 17:21:10 +08:00
/// BLOB
Blob,
}
impl fmt::Display for Type {
2018-12-08 04:57:04 +08:00
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Type::Null => f.pad("Null"),
Type::Integer => f.pad("Integer"),
Type::Real => f.pad("Real"),
Type::Text => f.pad("Text"),
Type::Blob => f.pad("Blob"),
}
}
}
2014-10-20 07:56:41 +08:00
#[cfg(test)]
mod test {
2018-08-11 18:48:21 +08:00
use super::Value;
2020-11-06 05:14:00 +08:00
use crate::{params, Connection, Error, Result, Statement};
2018-08-11 18:48:21 +08:00
use std::f64::EPSILON;
use std::os::raw::{c_double, c_int};
2014-10-20 07:56:41 +08:00
2020-11-06 05:14:00 +08:00
fn checked_memory_handle() -> Result<Connection> {
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE foo (b BLOB, t TEXT, i INTEGER, f FLOAT, n)")?;
Ok(db)
2014-10-20 07:56:41 +08:00
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_blob() -> Result<()> {
let db = checked_memory_handle()?;
2014-10-20 07:56:41 +08:00
2015-12-11 05:48:09 +08:00
let v1234 = vec![1u8, 2, 3, 4];
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(b) VALUES (?)", &[&v1234])?;
2014-10-20 07:56:41 +08:00
2020-11-06 05:14:00 +08:00
let v: Vec<u8> = db.query_row("SELECT b FROM foo", [], |r| r.get(0))?;
2014-10-20 07:56:41 +08:00
assert_eq!(v, v1234);
2020-11-06 05:14:00 +08:00
Ok(())
2014-10-20 07:56:41 +08:00
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_empty_blob() -> Result<()> {
let db = checked_memory_handle()?;
2016-06-14 02:22:21 +08:00
let empty = vec![];
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(b) VALUES (?)", &[&empty])?;
2016-06-14 02:22:21 +08:00
2020-11-06 05:14:00 +08:00
let v: Vec<u8> = db.query_row("SELECT b FROM foo", [], |r| r.get(0))?;
2016-06-14 02:22:21 +08:00
assert_eq!(v, empty);
2020-11-06 05:14:00 +08:00
Ok(())
2016-06-14 02:22:21 +08:00
}
2014-10-20 07:56:41 +08:00
#[test]
2020-11-06 05:14:00 +08:00
fn test_str() -> Result<()> {
let db = checked_memory_handle()?;
2014-10-20 07:56:41 +08:00
let s = "hello, world!";
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s])?;
2020-11-06 05:14:00 +08:00
let from: String = db.query_row("SELECT t FROM foo", [], |r| r.get(0))?;
assert_eq!(from, s);
2020-11-06 05:14:00 +08:00
Ok(())
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_string() -> Result<()> {
let db = checked_memory_handle()?;
2014-10-20 07:56:41 +08:00
let s = "hello, world!";
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(t) VALUES (?)", [s.to_owned()])?;
2014-10-20 07:56:41 +08:00
2020-11-06 05:14:00 +08:00
let from: String = db.query_row("SELECT t FROM foo", [], |r| r.get(0))?;
2015-03-17 12:55:28 +08:00
assert_eq!(from, s);
2020-11-06 05:14:00 +08:00
Ok(())
2014-10-20 07:56:41 +08:00
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_value() -> Result<()> {
let db = checked_memory_handle()?;
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(i) VALUES (?)", [Value::Integer(10)])?;
2018-08-11 18:48:21 +08:00
assert_eq!(
10i64,
2020-11-06 05:14:00 +08:00
db.query_row::<i64, _, _>("SELECT i FROM foo", [], |r| r.get(0))?
2018-08-11 18:48:21 +08:00
);
2020-11-06 05:14:00 +08:00
Ok(())
}
2014-10-20 07:56:41 +08:00
#[test]
2020-11-06 05:14:00 +08:00
fn test_option() -> Result<()> {
let db = checked_memory_handle()?;
2014-10-20 07:56:41 +08:00
let s = Some("hello, world!");
2015-12-11 05:48:09 +08:00
let b = Some(vec![1u8, 2, 3, 4]);
2014-10-20 07:56:41 +08:00
2020-11-06 05:14:00 +08:00
db.execute("INSERT INTO foo(t) VALUES (?)", &[&s])?;
db.execute("INSERT INTO foo(b) VALUES (?)", &[&b])?;
2014-10-20 07:56:41 +08:00
2020-11-06 05:14:00 +08:00
let mut stmt = db.prepare("SELECT t, b FROM foo ORDER BY ROWID ASC")?;
let mut rows = stmt.query([])?;
2014-10-20 07:56:41 +08:00
{
2020-11-06 05:14:00 +08:00
let row1 = rows.next()?.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());
}
{
2020-11-06 05:14:00 +08:00
let row2 = rows.next()?.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);
}
2020-11-06 05:14:00 +08:00
Ok(())
2014-10-20 07:56:41 +08:00
}
#[test]
2019-03-22 02:13:55 +08:00
#[allow(clippy::cognitive_complexity)]
2020-11-06 05:14:00 +08:00
fn test_mismatched_types() -> Result<()> {
fn is_invalid_column_type(err: Error) -> bool {
2020-10-04 13:38:52 +08:00
matches!(err, Error::InvalidColumnType(..))
}
2020-11-06 05:14:00 +08:00
let db = checked_memory_handle()?;
2018-08-11 18:48:21 +08:00
db.execute(
"INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
[],
2020-11-06 05:14:00 +08:00
)?;
2020-11-06 05:14:00 +08:00
let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo")?;
let mut rows = stmt.query([])?;
2020-11-06 05:14:00 +08:00
let row = rows.next()?.unwrap();
// check the correct types come back as expected
2020-11-06 05:14:00 +08:00
assert_eq!(vec![1, 2], row.get::<_, Vec<u8>>(0)?);
assert_eq!("text", row.get::<_, String>(1)?);
assert_eq!(1, row.get::<_, c_int>(2)?);
assert!((1.5 - row.get::<_, c_double>(3)?).abs() < EPSILON);
assert_eq!(row.get::<_, Option<c_int>>(4)?, None);
assert_eq!(row.get::<_, Option<c_double>>(4)?, None);
assert_eq!(row.get::<_, Option<String>>(4)?, None);
// check some invalid types
// 0 is actually a blob (Vec<u8>)
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_int>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, c_int>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(row.get::<_, i64>(0).err().unwrap()));
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_double>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, String>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
#[cfg(feature = "time")]
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, time::OffsetDateTime>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Option<c_int>>(0).err().unwrap()
2018-08-11 18:48:21 +08:00
));
// 1 is actually a text (String)
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_int>(1).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(row.get::<_, i64>(1).err().unwrap()));
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_double>(1).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Vec<u8>>(1).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Option<c_int>>(1).err().unwrap()
2018-08-11 18:48:21 +08:00
));
// 2 is actually an integer
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, String>(2).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Vec<u8>>(2).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Option<String>>(2).err().unwrap()
2018-08-11 18:48:21 +08:00
));
// 3 is actually a float (c_double)
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_int>(3).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(row.get::<_, i64>(3).err().unwrap()));
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, String>(3).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Vec<u8>>(3).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Option<c_int>>(3).err().unwrap()
2018-08-11 18:48:21 +08:00
));
// 4 is actually NULL
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_int>(4).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(row.get::<_, i64>(4).err().unwrap()));
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, c_double>(4).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, String>(4).err().unwrap()
2018-08-11 18:48:21 +08:00
));
assert!(is_invalid_column_type(
row.get::<_, Vec<u8>>(4).err().unwrap()
2018-08-11 18:48:21 +08:00
));
#[cfg(feature = "time")]
2018-08-11 18:48:21 +08:00
assert!(is_invalid_column_type(
row.get::<_, time::OffsetDateTime>(4).err().unwrap()
2018-08-11 18:48:21 +08:00
));
2020-11-06 05:14:00 +08:00
Ok(())
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_dynamic_type() -> Result<()> {
use super::Value;
2020-11-06 05:14:00 +08:00
let db = checked_memory_handle()?;
2018-08-11 18:48:21 +08:00
db.execute(
"INSERT INTO foo(b, t, i, f) VALUES (X'0102', 'text', 1, 1.5)",
[],
2020-11-06 05:14:00 +08:00
)?;
2020-11-06 05:14:00 +08:00
let mut stmt = db.prepare("SELECT b, t, i, f, n FROM foo")?;
let mut rows = stmt.query([])?;
2020-11-06 05:14:00 +08:00
let row = rows.next()?.unwrap();
assert_eq!(Value::Blob(vec![1, 2]), row.get::<_, Value>(0)?);
assert_eq!(Value::Text(String::from("text")), row.get::<_, Value>(1)?);
assert_eq!(Value::Integer(1), row.get::<_, Value>(2)?);
match row.get::<_, Value>(3)? {
2016-03-30 02:18:56 +08:00
Value::Real(val) => assert!((1.5 - val).abs() < EPSILON),
x => panic!("Invalid Value {:?}", x),
}
2020-11-06 05:14:00 +08:00
assert_eq!(Value::Null, row.get::<_, Value>(4)?);
Ok(())
}
macro_rules! test_conversion {
2020-10-29 04:12:29 +08:00
($db_etc:ident, $insert_value:expr, $get_type:ty,expect $expected_value:expr) => {
2020-11-06 05:14:00 +08:00
$db_etc.insert_statement.execute(params![$insert_value])?;
2020-10-23 04:56:59 +08:00
let res = $db_etc
.query_statement
.query_row([], |row| row.get::<_, $get_type>(0));
2020-11-06 05:14:00 +08:00
assert_eq!(res?, $expected_value);
$db_etc.delete_statement.execute([])?;
};
($db_etc:ident, $insert_value:expr, $get_type:ty,expect_from_sql_error) => {
2020-11-06 05:14:00 +08:00
$db_etc.insert_statement.execute(params![$insert_value])?;
2020-10-23 04:56:59 +08:00
let res = $db_etc
.query_statement
.query_row([], |row| row.get::<_, $get_type>(0));
res.unwrap_err();
2020-11-06 05:14:00 +08:00
$db_etc.delete_statement.execute([])?;
};
($db_etc:ident, $insert_value:expr, $get_type:ty,expect_to_sql_error) => {
$db_etc
.insert_statement
.execute(params![$insert_value])
.unwrap_err();
};
}
#[test]
2020-11-06 05:14:00 +08:00
fn test_numeric_conversions() -> Result<()> {
2020-10-23 05:00:17 +08:00
#![allow(clippy::float_cmp)]
// Test what happens when we store an f32 and retrieve an i32 etc.
2020-11-06 05:14:00 +08:00
let db = Connection::open_in_memory()?;
db.execute_batch("CREATE TABLE foo (x)")?;
// SQLite actually ignores the column types, so we just need to test
// different numeric values.
struct DbEtc<'conn> {
insert_statement: Statement<'conn>,
query_statement: Statement<'conn>,
delete_statement: Statement<'conn>,
}
let mut db_etc = DbEtc {
2020-11-06 05:14:00 +08:00
insert_statement: db.prepare("INSERT INTO foo VALUES (?1)")?,
query_statement: db.prepare("SELECT x FROM foo")?,
delete_statement: db.prepare("DELETE FROM foo")?,
};
// Basic non-converting test.
test_conversion!(db_etc, 0u8, u8, expect 0u8);
// In-range integral conversions.
test_conversion!(db_etc, 100u8, i8, expect 100i8);
test_conversion!(db_etc, 200u8, u8, expect 200u8);
test_conversion!(db_etc, 100u16, i8, expect 100i8);
test_conversion!(db_etc, 200u16, u8, expect 200u8);
test_conversion!(db_etc, u32::MAX, u64, expect u32::MAX as u64);
test_conversion!(db_etc, i64::MIN, i64, expect i64::MIN);
test_conversion!(db_etc, i64::MAX, i64, expect i64::MAX);
test_conversion!(db_etc, i64::MAX, u64, expect i64::MAX as u64);
test_conversion!(db_etc, 100usize, usize, expect 100usize);
test_conversion!(db_etc, 100u64, u64, expect 100u64);
test_conversion!(db_etc, i64::MAX as u64, u64, expect i64::MAX as u64);
// Out-of-range integral conversions.
test_conversion!(db_etc, 200u8, i8, expect_from_sql_error);
test_conversion!(db_etc, 400u16, i8, expect_from_sql_error);
test_conversion!(db_etc, 400u16, u8, expect_from_sql_error);
test_conversion!(db_etc, -1i8, u8, expect_from_sql_error);
test_conversion!(db_etc, i64::MIN, u64, expect_from_sql_error);
test_conversion!(db_etc, u64::MAX, i64, expect_to_sql_error);
test_conversion!(db_etc, u64::MAX, u64, expect_to_sql_error);
test_conversion!(db_etc, i64::MAX as u64 + 1, u64, expect_to_sql_error);
// FromSql integer to float, always works.
test_conversion!(db_etc, i64::MIN, f32, expect i64::MIN as f32);
test_conversion!(db_etc, i64::MAX, f32, expect i64::MAX as f32);
test_conversion!(db_etc, i64::MIN, f64, expect i64::MIN as f64);
test_conversion!(db_etc, i64::MAX, f64, expect i64::MAX as f64);
// FromSql float to int conversion, never works even if the actual value
// is an integer.
test_conversion!(db_etc, 0f64, i64, expect_from_sql_error);
2020-11-06 05:14:00 +08:00
Ok(())
}
2014-10-20 07:56:41 +08:00
}