Skip to main content

rusqlite/types/
to_sql.rs

1use super::{Null, Value, ValueRef};
2use crate::Error;
3use crate::Result;
4use std::borrow::Cow;
5
6/// `ToSqlOutput` represents the possible output types for implementers of the
7/// [`ToSql`] trait.
8#[derive(Clone, Debug, PartialEq)]
9#[non_exhaustive]
10pub enum ToSqlOutput<'a> {
11    /// A borrowed SQLite-representable value.
12    Borrowed(ValueRef<'a>),
13
14    /// An owned SQLite-representable value.
15    Owned(Value),
16
17    /// A BLOB of the given length that is filled with
18    /// zeroes.
19    #[cfg(feature = "blob")]
20    ZeroBlob(u64),
21
22    /// n-th arg of an SQL scalar function
23    #[cfg(feature = "functions")]
24    Arg(usize),
25
26    /// Pointer passing interface
27    #[cfg(feature = "pointer")]
28    Pointer(
29        (
30            *const std::ffi::c_void,
31            &'static std::ffi::CStr,
32            crate::ffi::sqlite3_destructor_type,
33        ),
34    ),
35}
36
37#[cfg(feature = "pointer")]
38impl<'a> ToSqlOutput<'a> {
39    /// Pass an `Rc` as a raw pointer to SQLite
40    ///
41    /// # Warning
42    /// Leak memory if an error happens before the returned pointer is bound to an SQLite statement.
43    pub fn from_rc<T>(rc: std::rc::Rc<T>, ptr_type: &'static std::ffi::CStr) -> ToSqlOutput<'a> {
44        unsafe extern "C" fn free_rc<T>(p: *mut std::ffi::c_void) {
45            unsafe {
46                std::rc::Rc::decrement_strong_count(p.cast::<T>());
47            }
48        }
49        ToSqlOutput::Pointer((
50            std::rc::Rc::into_raw(rc).cast::<std::ffi::c_void>(),
51            ptr_type,
52            Some(free_rc::<T>),
53        ))
54    }
55
56    /// Pass a `Box` as a raw pointer to SQLite
57    ///
58    /// # Warning
59    /// Leak memory if an error happens before the returned pointer is bound to an SQLite statement.
60    pub fn new_boxed<T>(v: T, ptr_type: &'static std::ffi::CStr) -> ToSqlOutput<'a> {
61        use crate::util::free_boxed_value;
62
63        ToSqlOutput::Pointer((
64            Box::into_raw(Box::new(v)).cast::<std::ffi::c_void>(),
65            ptr_type,
66            Some(free_boxed_value::<T>),
67        ))
68    }
69}
70
71// Generically allow any type that can be converted into a ValueRef
72// to be converted into a ToSqlOutput as well.
73impl<'a, T: ?Sized> From<&'a T> for ToSqlOutput<'a>
74where
75    &'a T: Into<ValueRef<'a>>,
76{
77    #[inline]
78    fn from(t: &'a T) -> Self {
79        ToSqlOutput::Borrowed(t.into())
80    }
81}
82
83// We cannot also generically allow any type that can be converted
84// into a Value to be converted into a ToSqlOutput because of
85// coherence rules (https://github.com/rust-lang/rust/pull/46192),
86// so we'll manually implement it for all the types we know can
87// be converted into Values.
88macro_rules! from_value(
89    ($t:ty) => (
90        impl From<$t> for ToSqlOutput<'_> {
91            #[inline]
92            fn from(t: $t) -> Self { ToSqlOutput::Owned(t.into())}
93        }
94    );
95    (non_zero $t:ty) => (
96        impl From<$t> for ToSqlOutput<'_> {
97            #[inline]
98            fn from(t: $t) -> Self { ToSqlOutput::Owned(t.get().into())}
99        }
100    )
101);
102from_value!(String);
103from_value!(Null);
104from_value!(bool);
105from_value!(i8);
106from_value!(i16);
107from_value!(i32);
108from_value!(i64);
109from_value!(isize);
110from_value!(u8);
111from_value!(u16);
112from_value!(u32);
113from_value!(f32);
114from_value!(f64);
115from_value!(Vec<u8>);
116
117from_value!(non_zero std::num::NonZeroI8);
118from_value!(non_zero std::num::NonZeroI16);
119from_value!(non_zero std::num::NonZeroI32);
120from_value!(non_zero std::num::NonZeroI64);
121from_value!(non_zero std::num::NonZeroIsize);
122from_value!(non_zero std::num::NonZeroU8);
123from_value!(non_zero std::num::NonZeroU16);
124from_value!(non_zero std::num::NonZeroU32);
125
126// It would be nice if we could avoid the heap allocation (of the `Vec`) that
127// `i128` needs in `Into<Value>`, but it's probably fine for the moment, and not
128// worth adding another case to Value.
129#[cfg(feature = "i128_blob")]
130from_value!(i128);
131
132#[cfg(feature = "i128_blob")]
133from_value!(non_zero std::num::NonZeroI128);
134
135#[cfg(feature = "uuid")]
136from_value!(uuid::Uuid);
137
138impl ToSql for ToSqlOutput<'_> {
139    #[inline]
140    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
141        Ok(match *self {
142            ToSqlOutput::Borrowed(v) => ToSqlOutput::Borrowed(v),
143            ToSqlOutput::Owned(ref v) => ToSqlOutput::Borrowed(ValueRef::from(v)),
144
145            #[cfg(feature = "blob")]
146            ToSqlOutput::ZeroBlob(i) => ToSqlOutput::ZeroBlob(i),
147            #[cfg(feature = "functions")]
148            ToSqlOutput::Arg(i) => ToSqlOutput::Arg(i),
149            #[cfg(feature = "pointer")]
150            ToSqlOutput::Pointer(p) => ToSqlOutput::Pointer(p),
151        })
152    }
153}
154
155/// A trait for types that can be converted into SQLite values. Returns
156/// [`crate::Error::ToSqlConversionFailure`] if the conversion fails.
157pub trait ToSql {
158    /// Converts Rust value to SQLite value
159    fn to_sql(&self) -> Result<ToSqlOutput<'_>>;
160}
161
162impl<T: ToSql + ToOwned + ?Sized> ToSql for Cow<'_, T> {
163    #[inline]
164    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
165        self.as_ref().to_sql()
166    }
167}
168
169impl<T: ToSql + ?Sized> ToSql for Box<T> {
170    #[inline]
171    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
172        self.as_ref().to_sql()
173    }
174}
175
176impl<T: ToSql + ?Sized> ToSql for std::rc::Rc<T> {
177    #[inline]
178    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
179        self.as_ref().to_sql()
180    }
181}
182
183impl<T: ToSql + ?Sized> ToSql for std::sync::Arc<T> {
184    #[inline]
185    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
186        self.as_ref().to_sql()
187    }
188}
189
190// We should be able to use a generic impl like this:
191//
192// impl<T: Copy> ToSql for T where T: Into<Value> {
193//     fn to_sql(&self) -> Result<ToSqlOutput> {
194//         Ok(ToSqlOutput::from((*self).into()))
195//     }
196// }
197//
198// instead of the following macro, but this runs afoul of
199// https://github.com/rust-lang/rust/issues/30191 and reports conflicting
200// implementations even when there aren't any.
201
202macro_rules! to_sql_self(
203    ($t:ty) => (
204        impl ToSql for $t {
205            #[inline]
206            fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
207                Ok(ToSqlOutput::from(*self))
208            }
209        }
210    )
211);
212
213to_sql_self!(Null);
214to_sql_self!(bool);
215to_sql_self!(i8);
216to_sql_self!(i16);
217to_sql_self!(i32);
218to_sql_self!(i64);
219to_sql_self!(isize);
220to_sql_self!(u8);
221to_sql_self!(u16);
222to_sql_self!(u32);
223to_sql_self!(f32);
224to_sql_self!(f64);
225
226to_sql_self!(std::num::NonZeroI8);
227to_sql_self!(std::num::NonZeroI16);
228to_sql_self!(std::num::NonZeroI32);
229to_sql_self!(std::num::NonZeroI64);
230to_sql_self!(std::num::NonZeroIsize);
231to_sql_self!(std::num::NonZeroU8);
232to_sql_self!(std::num::NonZeroU16);
233to_sql_self!(std::num::NonZeroU32);
234
235#[cfg(feature = "i128_blob")]
236to_sql_self!(i128);
237
238#[cfg(feature = "i128_blob")]
239to_sql_self!(std::num::NonZeroI128);
240
241#[cfg(feature = "uuid")]
242to_sql_self!(uuid::Uuid);
243
244macro_rules! to_sql_self_fallible(
245    ($t:ty) => (
246        impl ToSql for $t {
247            #[inline]
248            fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
249                Ok(ToSqlOutput::Owned(Value::Integer(
250                    i64::try_from(*self).map_err(
251                        // TODO: Include the values in the error message.
252                        |err| Error::ToSqlConversionFailure(err.into())
253                    )?
254                )))
255            }
256        }
257    );
258    (non_zero $t:ty) => (
259        impl ToSql for $t {
260            #[inline]
261            fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
262                Ok(ToSqlOutput::Owned(Value::Integer(
263                    i64::try_from(self.get()).map_err(
264                        // TODO: Include the values in the error message.
265                        |err| Error::ToSqlConversionFailure(err.into())
266                    )?
267                )))
268            }
269        }
270    )
271);
272
273// Special implementations for usize and u64 because these conversions can fail.
274to_sql_self_fallible!(u64);
275to_sql_self_fallible!(usize);
276to_sql_self_fallible!(non_zero std::num::NonZeroU64);
277to_sql_self_fallible!(non_zero std::num::NonZeroUsize);
278
279impl<T: ?Sized> ToSql for &'_ T
280where
281    T: ToSql,
282{
283    #[inline]
284    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
285        (*self).to_sql()
286    }
287}
288
289impl ToSql for String {
290    #[inline]
291    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
292        Ok(ToSqlOutput::from(self.as_str()))
293    }
294}
295
296impl ToSql for str {
297    #[inline]
298    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
299        Ok(ToSqlOutput::from(self))
300    }
301}
302
303impl ToSql for Vec<u8> {
304    #[inline]
305    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
306        Ok(ToSqlOutput::from(self.as_slice()))
307    }
308}
309
310impl<const N: usize> ToSql for [u8; N] {
311    #[inline]
312    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
313        Ok(ToSqlOutput::from(&self[..]))
314    }
315}
316
317impl ToSql for [u8] {
318    #[inline]
319    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
320        Ok(ToSqlOutput::from(self))
321    }
322}
323
324impl ToSql for Value {
325    #[inline]
326    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
327        Ok(ToSqlOutput::from(self))
328    }
329}
330
331impl<T: ToSql> ToSql for Option<T> {
332    #[inline]
333    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
334        match *self {
335            None => Ok(ToSqlOutput::from(Null)),
336            Some(ref t) => t.to_sql(),
337        }
338    }
339}
340
341#[cfg(test)]
342mod test {
343    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
344    use wasm_bindgen_test::wasm_bindgen_test as test;
345
346    use super::{ToSql, ToSqlOutput};
347    use crate::{Result, types::Value, types::ValueRef};
348
349    fn is_to_sql<T: ToSql>() {}
350
351    #[test]
352    fn to_sql() -> Result<()> {
353        assert_eq!(
354            ToSqlOutput::Borrowed(ValueRef::Null).to_sql()?,
355            ToSqlOutput::Borrowed(ValueRef::Null)
356        );
357        assert_eq!(
358            ToSqlOutput::Owned(Value::Null).to_sql()?,
359            ToSqlOutput::Borrowed(ValueRef::Null)
360        );
361        Ok(())
362    }
363
364    #[test]
365    fn test_integral_types() {
366        is_to_sql::<i8>();
367        is_to_sql::<i16>();
368        is_to_sql::<i32>();
369        is_to_sql::<i64>();
370        is_to_sql::<isize>();
371        is_to_sql::<u8>();
372        is_to_sql::<u16>();
373        is_to_sql::<u32>();
374        is_to_sql::<u64>();
375        is_to_sql::<usize>();
376    }
377
378    #[test]
379    fn test_nonzero_types() {
380        is_to_sql::<std::num::NonZeroI8>();
381        is_to_sql::<std::num::NonZeroI16>();
382        is_to_sql::<std::num::NonZeroI32>();
383        is_to_sql::<std::num::NonZeroI64>();
384        is_to_sql::<std::num::NonZeroIsize>();
385        is_to_sql::<std::num::NonZeroU8>();
386        is_to_sql::<std::num::NonZeroU16>();
387        is_to_sql::<std::num::NonZeroU32>();
388        is_to_sql::<std::num::NonZeroU64>();
389        is_to_sql::<std::num::NonZeroUsize>();
390    }
391
392    #[test]
393    fn test_u8_array() {
394        let a: [u8; 99] = [0u8; 99];
395        let _a: &[&dyn ToSql] = crate::params![a];
396        let r = ToSql::to_sql(&a);
397
398        r.unwrap();
399    }
400
401    #[test]
402    fn test_cow_str() {
403        use std::borrow::Cow;
404        let s = "str";
405        let cow: Cow<str> = Cow::Borrowed(s);
406        let r = cow.to_sql();
407        r.unwrap();
408        let cow: Cow<str> = Cow::Owned::<str>(String::from(s));
409        let r = cow.to_sql();
410        r.unwrap();
411        // Ensure this compiles.
412        let _p: &[&dyn ToSql] = crate::params![cow];
413    }
414
415    #[test]
416    fn test_box_dyn() {
417        let s: Box<dyn ToSql> = Box::new("Hello world!");
418        let _s: &[&dyn ToSql] = crate::params![s];
419        let r = ToSql::to_sql(&s);
420
421        r.unwrap();
422    }
423
424    #[test]
425    fn test_box_deref() {
426        let s: Box<str> = "Hello world!".into();
427        let _s: &[&dyn ToSql] = crate::params![s];
428        let r = s.to_sql();
429
430        r.unwrap();
431    }
432
433    #[test]
434    fn test_box_direct() {
435        let s: Box<str> = "Hello world!".into();
436        let _s: &[&dyn ToSql] = crate::params![s];
437        let r = ToSql::to_sql(&s);
438
439        r.unwrap();
440    }
441
442    #[test]
443    fn test_cells() {
444        use std::{rc::Rc, sync::Arc};
445
446        let source_str: Box<str> = "Hello world!".into();
447
448        let s: Rc<Box<str>> = Rc::new(source_str.clone());
449        let _s: &[&dyn ToSql] = crate::params![s];
450        let r = s.to_sql();
451        r.unwrap();
452
453        let s: Arc<Box<str>> = Arc::new(source_str.clone());
454        let _s: &[&dyn ToSql] = crate::params![s];
455        let r = s.to_sql();
456        r.unwrap();
457
458        let s: Arc<str> = Arc::from(&*source_str);
459        let _s: &[&dyn ToSql] = crate::params![s];
460        let r = s.to_sql();
461        r.unwrap();
462
463        let s: Arc<dyn ToSql> = Arc::new(source_str.clone());
464        let _s: &[&dyn ToSql] = crate::params![s];
465        let r = s.to_sql();
466        r.unwrap();
467
468        let s: Rc<str> = Rc::from(&*source_str);
469        let _s: &[&dyn ToSql] = crate::params![s];
470        let r = s.to_sql();
471        r.unwrap();
472
473        let s: Rc<dyn ToSql> = Rc::new(source_str);
474        let _s: &[&dyn ToSql] = crate::params![s];
475        let r = s.to_sql();
476        r.unwrap();
477    }
478
479    #[cfg(feature = "i128_blob")]
480    #[test]
481    #[cfg_attr(miri, ignore)]
482    fn test_i128() -> Result<()> {
483        use crate::Connection;
484        let db = Connection::open_in_memory()?;
485        db.execute_batch("CREATE TABLE foo (i128 BLOB, desc TEXT)")?;
486        db.execute(
487            "
488            INSERT INTO foo(i128, desc) VALUES
489                (?1, 'zero'),
490                (?2, 'neg one'), (?3, 'neg two'),
491                (?4, 'pos one'), (?5, 'pos two'),
492                (?6, 'min'), (?7, 'max')",
493            [0i128, -1i128, -2i128, 1i128, 2i128, i128::MIN, i128::MAX],
494        )?;
495
496        let mut stmt = db.prepare("SELECT i128, desc FROM foo ORDER BY i128 ASC")?;
497
498        let res = stmt
499            .query_map([], |row| {
500                Ok((row.get::<_, i128>(0)?, row.get::<_, String>(1)?))
501            })?
502            .collect::<Result<Vec<_>, _>>()?;
503
504        assert_eq!(
505            res,
506            &[
507                (i128::MIN, "min".to_owned()),
508                (-2, "neg two".to_owned()),
509                (-1, "neg one".to_owned()),
510                (0, "zero".to_owned()),
511                (1, "pos one".to_owned()),
512                (2, "pos two".to_owned()),
513                (i128::MAX, "max".to_owned()),
514            ]
515        );
516        Ok(())
517    }
518
519    #[cfg(feature = "i128_blob")]
520    #[test]
521    #[cfg_attr(miri, ignore)]
522    fn test_non_zero_i128() -> Result<()> {
523        use std::num::NonZeroI128;
524        macro_rules! nz {
525            ($x:expr) => {
526                NonZeroI128::new($x).unwrap()
527            };
528        }
529
530        let db = crate::Connection::open_in_memory()?;
531        db.execute_batch("CREATE TABLE foo (i128 BLOB, desc TEXT)")?;
532        db.execute(
533            "INSERT INTO foo(i128, desc) VALUES
534                (?1, 'neg one'), (?2, 'neg two'),
535                (?3, 'pos one'), (?4, 'pos two'),
536                (?5, 'min'), (?6, 'max')",
537            [
538                nz!(-1),
539                nz!(-2),
540                nz!(1),
541                nz!(2),
542                nz!(i128::MIN),
543                nz!(i128::MAX),
544            ],
545        )?;
546        let mut stmt = db.prepare("SELECT i128, desc FROM foo ORDER BY i128 ASC")?;
547
548        let res = stmt
549            .query_map([], |row| Ok((row.get(0)?, row.get(1)?)))?
550            .collect::<Result<Vec<(NonZeroI128, String)>, _>>()?;
551
552        assert_eq!(
553            res,
554            &[
555                (nz!(i128::MIN), "min".to_owned()),
556                (nz!(-2), "neg two".to_owned()),
557                (nz!(-1), "neg one".to_owned()),
558                (nz!(1), "pos one".to_owned()),
559                (nz!(2), "pos two".to_owned()),
560                (nz!(i128::MAX), "max".to_owned()),
561            ]
562        );
563        let err = db.query_row("SELECT ?1", [0i128], |row| row.get::<_, NonZeroI128>(0));
564        assert_eq!(err, Err(crate::Error::IntegralValueOutOfRange(0, 0)));
565        Ok(())
566    }
567
568    #[cfg(feature = "uuid")]
569    #[test]
570    #[cfg_attr(miri, ignore)]
571    fn test_uuid() -> Result<()> {
572        use crate::{Connection, params};
573        use uuid::Uuid;
574
575        let db = Connection::open_in_memory()?;
576        db.execute_batch("CREATE TABLE foo (id BLOB CHECK(length(id) = 16), label TEXT);")?;
577
578        let id = Uuid::new_v4();
579
580        db.execute(
581            "INSERT INTO foo (id, label) VALUES (?1, ?2)",
582            params![id, "target"],
583        )?;
584
585        let mut stmt = db.prepare("SELECT id, label FROM foo WHERE id = ?1")?;
586
587        let mut rows = stmt.query(params![id])?;
588        let row = rows.next()?.unwrap();
589
590        let found_id: Uuid = row.get_unwrap(0);
591        let found_label: String = row.get_unwrap(1);
592
593        assert_eq!(found_id, id);
594        assert_eq!(found_label, "target");
595        Ok(())
596    }
597
598    #[cfg(feature = "pointer")]
599    #[test]
600    fn from_rc() {
601        let rc = std::rc::Rc::new("rc".to_owned());
602        if let ToSqlOutput::Pointer((ptr, _, Some(destructor))) = ToSqlOutput::from_rc(rc, c"rc") {
603            unsafe { destructor(ptr.cast_mut()) }
604        }
605    }
606
607    #[cfg(feature = "pointer")]
608    #[test]
609    fn new_boxed() {
610        let data = "box".to_owned();
611        if let ToSqlOutput::Pointer((ptr, _, Some(destructor))) =
612            ToSqlOutput::new_boxed(data, c"box")
613        {
614            unsafe { destructor(ptr.cast_mut()) }
615        }
616    }
617}