Skip to main content

rusqlite/types/
from_sql.rs

1use super::{Value, ValueRef};
2use std::borrow::Cow;
3use std::error::Error;
4use std::fmt;
5use std::str::Utf8Error;
6
7/// Enum listing possible errors from [`FromSql`] trait.
8#[derive(Debug)]
9#[non_exhaustive]
10pub enum FromSqlError {
11    /// Error when an SQLite value is requested, but the type of the result
12    /// cannot be converted to the requested Rust type.
13    InvalidType,
14
15    /// Error when the i64 value returned by SQLite cannot be stored into the
16    /// requested type.
17    OutOfRange(i64),
18
19    /// Error converting a string to UTF-8.
20    Utf8Error(Utf8Error),
21
22    /// Error when the blob result returned by SQLite cannot be stored into the
23    /// requested type due to a size mismatch.
24    InvalidBlobSize {
25        /// The expected size of the blob.
26        expected_size: usize,
27        /// The actual size of the blob that was returned.
28        blob_size: usize,
29    },
30
31    /// An error case available for implementors of the [`FromSql`] trait.
32    Other(Box<dyn Error + Send + Sync + 'static>),
33}
34
35impl FromSqlError {
36    /// Converts an arbitrary error type to [`FromSqlError`].
37    ///
38    /// This is a convenience function that boxes and unsizes the error type. It's main purpose is
39    /// to be usable in the `map_err` method. So instead of
40    /// `result.map_err(|error| FromSqlError::Other(Box::new(error))` you can write
41    /// `result.map_err(FromSqlError::other)`.
42    pub fn other<E: Error + Send + Sync + 'static>(error: E) -> Self {
43        Self::Other(Box::new(error))
44    }
45}
46
47impl PartialEq for FromSqlError {
48    fn eq(&self, other: &Self) -> bool {
49        match (self, other) {
50            (Self::InvalidType, Self::InvalidType) => true,
51            (Self::OutOfRange(n1), Self::OutOfRange(n2)) => n1 == n2,
52            (Self::Utf8Error(u1), Self::Utf8Error(u2)) => u1 == u2,
53            (
54                Self::InvalidBlobSize {
55                    expected_size: es1,
56                    blob_size: bs1,
57                },
58                Self::InvalidBlobSize {
59                    expected_size: es2,
60                    blob_size: bs2,
61                },
62            ) => es1 == es2 && bs1 == bs2,
63            (..) => false,
64        }
65    }
66}
67
68impl fmt::Display for FromSqlError {
69    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70        match *self {
71            Self::InvalidType => write!(f, "Invalid type"),
72            Self::OutOfRange(i) => write!(f, "Value {i} out of range"),
73            Self::Utf8Error(ref err) => err.fmt(f),
74            Self::InvalidBlobSize {
75                expected_size,
76                blob_size,
77            } => {
78                write!(
79                    f,
80                    "Cannot read {expected_size} byte value out of {blob_size} byte blob"
81                )
82            }
83            Self::Other(ref err) => err.fmt(f),
84        }
85    }
86}
87
88impl Error for FromSqlError {
89    fn source(&self) -> Option<&(dyn Error + 'static)> {
90        match self {
91            Self::Utf8Error(err) => Some(err),
92            Self::Other(err) => Some(&**err),
93            _ => None,
94        }
95    }
96}
97
98impl From<Utf8Error> for FromSqlError {
99    #[cold]
100    fn from(err: Utf8Error) -> Self {
101        Self::Utf8Error(err)
102    }
103}
104
105/// Result type for implementors of the [`FromSql`] trait.
106pub type FromSqlResult<T> = Result<T, FromSqlError>;
107
108/// A trait for types that can be created from a SQLite value.
109pub trait FromSql: Sized {
110    /// Converts SQLite value into Rust value.
111    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self>;
112}
113
114macro_rules! from_sql_integral(
115    ($t:ident) => (
116        impl FromSql for $t {
117            #[inline]
118            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
119                let i = i64::column_result(value)?;
120                i.try_into().map_err(|_| FromSqlError::OutOfRange(i))
121            }
122        }
123    );
124    (non_zero $nz:ty, $z:ty) => (
125        impl FromSql for $nz {
126            #[inline]
127            fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
128                let i = <$z>::column_result(value)?;
129                <$nz>::new(i).ok_or(FromSqlError::OutOfRange(0))
130            }
131        }
132    )
133);
134
135from_sql_integral!(i8);
136from_sql_integral!(i16);
137from_sql_integral!(i32);
138// from_sql_integral!(i64); // Not needed because the native type is i64.
139from_sql_integral!(isize);
140from_sql_integral!(u8);
141from_sql_integral!(u16);
142from_sql_integral!(u32);
143from_sql_integral!(u64);
144from_sql_integral!(usize);
145
146from_sql_integral!(non_zero std::num::NonZeroIsize, isize);
147from_sql_integral!(non_zero std::num::NonZeroI8, i8);
148from_sql_integral!(non_zero std::num::NonZeroI16, i16);
149from_sql_integral!(non_zero std::num::NonZeroI32, i32);
150from_sql_integral!(non_zero std::num::NonZeroI64, i64);
151#[cfg(feature = "i128_blob")]
152from_sql_integral!(non_zero std::num::NonZeroI128, i128);
153
154from_sql_integral!(non_zero std::num::NonZeroUsize, usize);
155from_sql_integral!(non_zero std::num::NonZeroU8, u8);
156from_sql_integral!(non_zero std::num::NonZeroU16, u16);
157from_sql_integral!(non_zero std::num::NonZeroU32, u32);
158from_sql_integral!(non_zero std::num::NonZeroU64, u64);
159// std::num::NonZeroU128 is not supported since u128 isn't either
160
161impl FromSql for i64 {
162    #[inline]
163    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
164        value.as_i64()
165    }
166}
167
168impl FromSql for f32 {
169    #[inline]
170    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
171        match value {
172            ValueRef::Integer(i) => Ok(i as Self),
173            ValueRef::Real(f) => Ok(f as Self),
174            _ => Err(FromSqlError::InvalidType),
175        }
176    }
177}
178
179impl FromSql for f64 {
180    #[inline]
181    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
182        match value {
183            ValueRef::Integer(i) => Ok(i as Self),
184            ValueRef::Real(f) => Ok(f),
185            _ => Err(FromSqlError::InvalidType),
186        }
187    }
188}
189
190impl FromSql for bool {
191    #[inline]
192    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
193        i64::column_result(value).map(|i| i != 0)
194    }
195}
196
197impl FromSql for String {
198    #[inline]
199    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
200        value.as_str().map(ToString::to_string)
201    }
202}
203
204impl FromSql for Box<str> {
205    #[inline]
206    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
207        value.as_str().map(Into::into)
208    }
209}
210
211impl FromSql for std::rc::Rc<str> {
212    #[inline]
213    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
214        value.as_str().map(Into::into)
215    }
216}
217
218impl FromSql for std::sync::Arc<str> {
219    #[inline]
220    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
221        value.as_str().map(Into::into)
222    }
223}
224
225impl FromSql for Vec<u8> {
226    #[inline]
227    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
228        value.as_blob().map(<[u8]>::to_vec)
229    }
230}
231
232impl FromSql for Box<[u8]> {
233    #[inline]
234    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
235        value.as_blob().map(Box::<[u8]>::from)
236    }
237}
238
239impl FromSql for std::rc::Rc<[u8]> {
240    #[inline]
241    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
242        value.as_blob().map(std::rc::Rc::<[u8]>::from)
243    }
244}
245
246impl FromSql for std::sync::Arc<[u8]> {
247    #[inline]
248    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
249        value.as_blob().map(std::sync::Arc::<[u8]>::from)
250    }
251}
252
253impl<const N: usize> FromSql for [u8; N] {
254    #[inline]
255    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
256        let slice = value.as_blob()?;
257        slice.try_into().map_err(|_| FromSqlError::InvalidBlobSize {
258            expected_size: N,
259            blob_size: slice.len(),
260        })
261    }
262}
263
264#[cfg(feature = "i128_blob")]
265impl FromSql for i128 {
266    #[inline]
267    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
268        let bytes = <[u8; 16]>::column_result(value)?;
269        Ok(Self::from_be_bytes(bytes) ^ (1_i128 << 127))
270    }
271}
272
273#[cfg(feature = "uuid")]
274impl FromSql for uuid::Uuid {
275    #[inline]
276    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
277        let bytes = <[u8; 16]>::column_result(value)?;
278        Ok(Self::from_u128(u128::from_be_bytes(bytes)))
279    }
280}
281
282impl<T: FromSql> FromSql for Option<T> {
283    #[inline]
284    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
285        match value {
286            ValueRef::Null => Ok(None),
287            _ => FromSql::column_result(value).map(Some),
288        }
289    }
290}
291
292impl<T: ?Sized> FromSql for Cow<'_, T>
293where
294    T: ToOwned,
295    T::Owned: FromSql,
296{
297    #[inline]
298    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
299        <T::Owned>::column_result(value).map(Cow::Owned)
300    }
301}
302
303impl FromSql for Value {
304    #[inline]
305    fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
306        value.try_into()
307    }
308}
309
310#[cfg(test)]
311mod test {
312    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
313    use wasm_bindgen_test::wasm_bindgen_test as test;
314
315    use super::{FromSql, FromSqlError};
316    use crate::{Connection, Error, Result};
317    use std::borrow::Cow;
318    use std::rc::Rc;
319    use std::sync::Arc;
320
321    #[test]
322    #[cfg_attr(miri, ignore)]
323    fn test_integral_ranges() -> Result<()> {
324        let db = Connection::open_in_memory()?;
325
326        fn check_ranges<T>(db: &Connection, out_of_range: &[i64], in_range: &[i64])
327        where
328            T: Into<i64> + FromSql + std::fmt::Debug,
329        {
330            for n in out_of_range {
331                let err = db
332                    .query_row("SELECT ?1", [n], |r| r.get::<_, T>(0))
333                    .unwrap_err();
334                match err {
335                    Error::IntegralValueOutOfRange(_, value) => assert_eq!(*n, value),
336                    _ => panic!("unexpected error: {err}"),
337                }
338            }
339            for n in in_range {
340                assert_eq!(
341                    *n,
342                    db.query_row("SELECT ?1", [n], |r| r.get::<_, T>(0))
343                        .unwrap()
344                        .into()
345                );
346            }
347        }
348
349        check_ranges::<i8>(&db, &[-129, 128], &[-128, 0, 1, 127]);
350        check_ranges::<i16>(&db, &[-32769, 32768], &[-32768, -1, 0, 1, 32767]);
351        check_ranges::<i32>(
352            &db,
353            &[-2_147_483_649, 2_147_483_648],
354            &[-2_147_483_648, -1, 0, 1, 2_147_483_647],
355        );
356        check_ranges::<u8>(&db, &[-2, -1, 256], &[0, 1, 255]);
357        check_ranges::<u16>(&db, &[-2, -1, 65536], &[0, 1, 65535]);
358        check_ranges::<u32>(&db, &[-2, -1, 4_294_967_296], &[0, 1, 4_294_967_295]);
359        Ok(())
360    }
361
362    #[test]
363    #[cfg_attr(miri, ignore)]
364    fn test_nonzero_ranges() -> Result<()> {
365        let db = Connection::open_in_memory()?;
366
367        macro_rules! check_ranges {
368            ($nz:ty, $out_of_range:expr, $in_range:expr) => {
369                for &n in $out_of_range {
370                    assert_eq!(
371                        db.query_row("SELECT ?1", [n], |r| r.get::<_, $nz>(0)),
372                        Err(Error::IntegralValueOutOfRange(0, n)),
373                        "{}",
374                        std::any::type_name::<$nz>()
375                    );
376                }
377                for &n in $in_range {
378                    let non_zero = <$nz>::new(n).unwrap();
379                    assert_eq!(
380                        Ok(non_zero),
381                        db.query_row("SELECT ?1", [non_zero], |r| r.get::<_, $nz>(0))
382                    );
383                }
384            };
385        }
386
387        check_ranges!(std::num::NonZeroI8, &[0, -129, 128], &[-128, 1, 127]);
388        check_ranges!(
389            std::num::NonZeroI16,
390            &[0, -32769, 32768],
391            &[-32768, -1, 1, 32767]
392        );
393        check_ranges!(
394            std::num::NonZeroI32,
395            &[0, -2_147_483_649, 2_147_483_648],
396            &[-2_147_483_648, -1, 1, 2_147_483_647]
397        );
398        check_ranges!(
399            std::num::NonZeroI64,
400            &[0],
401            &[-2_147_483_648, -1, 1, 2_147_483_647, i64::MAX, i64::MIN]
402        );
403        check_ranges!(
404            std::num::NonZeroIsize,
405            &[0],
406            &[-2_147_483_648, -1, 1, 2_147_483_647]
407        );
408        check_ranges!(std::num::NonZeroU8, &[0, -2, -1, 256], &[1, 255]);
409        check_ranges!(std::num::NonZeroU16, &[0, -2, -1, 65536], &[1, 65535]);
410        check_ranges!(
411            std::num::NonZeroU32,
412            &[0, -2, -1, 4_294_967_296],
413            &[1, 4_294_967_295]
414        );
415        check_ranges!(
416            std::num::NonZeroU64,
417            &[0, -2, -1, -4_294_967_296],
418            &[1, 4_294_967_295, i64::MAX as u64]
419        );
420        check_ranges!(
421            std::num::NonZeroUsize,
422            &[0, -2, -1, -4_294_967_296],
423            &[1, 4_294_967_295]
424        );
425
426        Ok(())
427    }
428
429    #[test]
430    #[cfg_attr(miri, ignore)]
431    fn test_cow() -> Result<()> {
432        let db = Connection::open_in_memory()?;
433
434        assert_eq!(
435            db.query_row("SELECT 'this is a string'", [], |r| r
436                .get::<_, Cow<'_, str>>(0)),
437            Ok(Cow::Borrowed("this is a string")),
438        );
439        assert_eq!(
440            db.query_row("SELECT x'09ab20fdee87'", [], |r| r
441                .get::<_, Cow<'_, [u8]>>(0)),
442            Ok(Cow::Owned(vec![0x09, 0xab, 0x20, 0xfd, 0xee, 0x87])),
443        );
444        assert_eq!(
445            db.query_row("SELECT 24.5", [], |r| r.get::<_, Cow<'_, f32>>(0),),
446            Ok(Cow::Borrowed(&24.5)),
447        );
448
449        Ok(())
450    }
451
452    #[test]
453    #[cfg_attr(miri, ignore)]
454    fn test_heap_slice() -> Result<()> {
455        let db = Connection::open_in_memory()?;
456
457        assert_eq!(
458            db.query_row("SELECT 'text'", [], |r| r.get::<_, Box<str>>(0)),
459            Ok(Box::from("text")),
460        );
461        assert_eq!(
462            db.query_row("SELECT 'Some string slice!'", [], |r| r
463                .get::<_, Rc<str>>(0)),
464            Ok(Rc::from("Some string slice!")),
465        );
466        assert_eq!(
467            db.query_row("SELECT x'012366779988fedc'", [], |r| r
468                .get::<_, Rc<[u8]>>(0)),
469            Ok(Rc::from(b"\x01\x23\x66\x77\x99\x88\xfe\xdc".as_slice())),
470        );
471
472        assert_eq!(
473            db.query_row(
474                "SELECT x'6120737472696e672043414e206265206120626c6f62'",
475                [],
476                |r| r.get::<_, Box<[u8]>>(0)
477            ),
478            Ok(b"a string CAN be a blob".to_vec().into_boxed_slice()),
479        );
480        assert_eq!(
481            db.query_row("SELECT 'This is inside an Arc.'", [], |r| r
482                .get::<_, Arc<str>>(0)),
483            Ok(Arc::from("This is inside an Arc.")),
484        );
485        assert_eq!(
486            db.query_row("SELECT x'afd374'", [], |r| r.get::<_, Arc<[u8]>>(0),),
487            Ok(Arc::from(b"\xaf\xd3\x74".as_slice())),
488        );
489
490        Ok(())
491    }
492
493    #[test]
494    fn from_sql_error() {
495        use std::error::Error as _;
496        assert_ne!(FromSqlError::InvalidType, FromSqlError::OutOfRange(0));
497        assert_ne!(FromSqlError::OutOfRange(0), FromSqlError::OutOfRange(1));
498        assert_ne!(
499            FromSqlError::InvalidBlobSize {
500                expected_size: 0,
501                blob_size: 0
502            },
503            FromSqlError::InvalidBlobSize {
504                expected_size: 0,
505                blob_size: 1
506            }
507        );
508        assert!(FromSqlError::InvalidType.source().is_none());
509        let err = std::io::Error::from(std::io::ErrorKind::UnexpectedEof);
510        assert!(FromSqlError::Other(Box::new(err)).source().is_some());
511    }
512}