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