Skip to main content

rok_db_core/
value.rs

1use std::fmt;
2use std::sync::Arc;
3
4use sqlx::encode::IsNull;
5use sqlx::postgres::{PgArgumentBuffer, PgArguments};
6use sqlx::{Arguments, Encode, Postgres, Type};
7
8use crate::Result;
9
10/// A dynamically typed, bindable SQL value.
11///
12/// Every variant carries an `Option` so that `NULL`s keep their SQL type,
13/// which PostgreSQL requires when binding parameters.
14///
15/// You rarely build a `Value` yourself: anything implementing `Into<Value>`
16/// (integers, floats, strings, `bool`, `Vec<u8>`, their `Option`s and, with
17/// the matching features, `chrono`, `uuid` and JSON types) can be passed to
18/// the query builder directly.
19#[derive(Debug, Clone, PartialEq)]
20#[non_exhaustive]
21pub enum Value {
22    /// `BOOLEAN`
23    Bool(Option<bool>),
24    /// `SMALLINT` (`INT2`)
25    I16(Option<i16>),
26    /// `INTEGER` (`INT4`)
27    I32(Option<i32>),
28    /// `BIGINT` (`INT8`)
29    I64(Option<i64>),
30    /// `REAL` (`FLOAT4`)
31    F32(Option<f32>),
32    /// `DOUBLE PRECISION` (`FLOAT8`)
33    F64(Option<f64>),
34    /// `TEXT` / `VARCHAR`
35    String(Option<String>),
36    /// `BYTEA`
37    Bytes(Option<Vec<u8>>),
38    #[cfg(feature = "uuid")]
39    /// `UUID`
40    Uuid(Option<sqlx::types::Uuid>),
41    #[cfg(feature = "chrono")]
42    /// `TIMESTAMPTZ`
43    DateTime(Option<sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>>),
44    #[cfg(feature = "chrono")]
45    /// `TIMESTAMP`
46    NaiveDateTime(Option<sqlx::types::chrono::NaiveDateTime>),
47    #[cfg(feature = "chrono")]
48    /// `DATE`
49    NaiveDate(Option<sqlx::types::chrono::NaiveDate>),
50    #[cfg(feature = "chrono")]
51    /// `TIME`
52    NaiveTime(Option<sqlx::types::chrono::NaiveTime>),
53    #[cfg(feature = "json")]
54    /// `JSONB` / `JSON`
55    Json(Option<serde_json::Value>),
56    /// Any other type sqlx can encode: enums and newtypes from
57    /// `#[derive(DbEnum)]` / `#[derive(DbNewtype)]`, or types registered
58    /// with [`impl_value!`](crate::impl_value). Build one with [`Value::custom`].
59    Custom(CustomValue),
60}
61
62impl Value {
63    /// Wrap any value sqlx can encode for PostgreSQL. `None` binds a `NULL`
64    /// of `T`'s SQL type.
65    pub fn custom<T>(value: Option<T>) -> Self
66    where
67        T: for<'q> Encode<'q, Postgres>
68            + Type<Postgres>
69            + Clone
70            + fmt::Debug
71            + Send
72            + Sync
73            + 'static,
74    {
75        Value::Custom(CustomValue(Arc::new(value)))
76    }
77
78    /// `true` if this value is a (typed) SQL `NULL`.
79    pub fn is_null(&self) -> bool {
80        match self {
81            Value::Bool(v) => v.is_none(),
82            Value::I16(v) => v.is_none(),
83            Value::I32(v) => v.is_none(),
84            Value::I64(v) => v.is_none(),
85            Value::F32(v) => v.is_none(),
86            Value::F64(v) => v.is_none(),
87            Value::String(v) => v.is_none(),
88            Value::Bytes(v) => v.is_none(),
89            #[cfg(feature = "uuid")]
90            Value::Uuid(v) => v.is_none(),
91            #[cfg(feature = "chrono")]
92            Value::DateTime(v) => v.is_none(),
93            #[cfg(feature = "chrono")]
94            Value::NaiveDateTime(v) => v.is_none(),
95            #[cfg(feature = "chrono")]
96            Value::NaiveDate(v) => v.is_none(),
97            #[cfg(feature = "chrono")]
98            Value::NaiveTime(v) => v.is_none(),
99            #[cfg(feature = "json")]
100            Value::Json(v) => v.is_none(),
101            Value::Custom(v) => v.0.is_null(),
102        }
103    }
104
105    /// Decode column `name` of `row` by its PostgreSQL type (used for keyset
106    /// cursors over aliased sort keys).
107    pub(crate) fn from_row_column(row: &sqlx::postgres::PgRow, name: &str) -> Result<Value> {
108        use sqlx::{Row, TypeInfo, ValueRef};
109        let (type_name, is_null) = {
110            let raw = row.try_get_raw(name)?;
111            (raw.type_info().name().to_owned(), raw.is_null())
112        };
113        if is_null {
114            return Err(crate::Error::InvalidQuery(format!(
115                "keyset sort key `{name}` is NULL; keyset pagination needs NOT NULL sort keys"
116            )));
117        }
118        Ok(match type_name.as_str() {
119            "BOOL" => Value::from(row.try_get::<bool, _>(name)?),
120            "INT2" => Value::from(row.try_get::<i16, _>(name)?),
121            "INT4" => Value::from(row.try_get::<i32, _>(name)?),
122            "INT8" => Value::from(row.try_get::<i64, _>(name)?),
123            "FLOAT4" => Value::from(row.try_get::<f32, _>(name)?),
124            "FLOAT8" => Value::from(row.try_get::<f64, _>(name)?),
125            "TEXT" | "VARCHAR" | "BPCHAR" | "NAME" | "CITEXT" => {
126                Value::from(row.try_get::<String, _>(name)?)
127            }
128            "BYTEA" => Value::from(row.try_get::<Vec<u8>, _>(name)?),
129            #[cfg(feature = "uuid")]
130            "UUID" => Value::from(row.try_get::<sqlx::types::Uuid, _>(name)?),
131            #[cfg(feature = "chrono")]
132            "TIMESTAMPTZ" => Value::from(
133                row.try_get::<sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>, _>(name)?,
134            ),
135            #[cfg(feature = "chrono")]
136            "TIMESTAMP" => Value::from(row.try_get::<sqlx::types::chrono::NaiveDateTime, _>(name)?),
137            #[cfg(feature = "chrono")]
138            "DATE" => Value::from(row.try_get::<sqlx::types::chrono::NaiveDate, _>(name)?),
139            #[cfg(feature = "chrono")]
140            "TIME" => Value::from(row.try_get::<sqlx::types::chrono::NaiveTime, _>(name)?),
141            other => {
142                return Err(crate::Error::InvalidQuery(format!(
143                    "can't use a `{other}` value as a keyset sort key"
144                )));
145            }
146        })
147    }
148
149    /// Encode in PostgreSQL's binary format; `None` for `NULL`.
150    pub(crate) fn encode_binary(&self) -> Result<Option<Vec<u8>>> {
151        fn enc<T: for<'q> Encode<'q, Postgres>>(
152            v: &T,
153            buf: &mut PgArgumentBuffer,
154        ) -> std::result::Result<IsNull, sqlx::error::BoxDynError> {
155            v.encode_by_ref(buf)
156        }
157        let mut buf = PgArgumentBuffer::default();
158        let is_null = match self {
159            Value::Bool(v) => enc(v, &mut buf),
160            Value::I16(v) => enc(v, &mut buf),
161            Value::I32(v) => enc(v, &mut buf),
162            Value::I64(v) => enc(v, &mut buf),
163            Value::F32(v) => enc(v, &mut buf),
164            Value::F64(v) => enc(v, &mut buf),
165            Value::String(v) => enc(v, &mut buf),
166            Value::Bytes(v) => enc(v, &mut buf),
167            #[cfg(feature = "uuid")]
168            Value::Uuid(v) => enc(v, &mut buf),
169            #[cfg(feature = "chrono")]
170            Value::DateTime(v) => enc(v, &mut buf),
171            #[cfg(feature = "chrono")]
172            Value::NaiveDateTime(v) => enc(v, &mut buf),
173            #[cfg(feature = "chrono")]
174            Value::NaiveDate(v) => enc(v, &mut buf),
175            #[cfg(feature = "chrono")]
176            Value::NaiveTime(v) => enc(v, &mut buf),
177            #[cfg(feature = "json")]
178            Value::Json(v) => enc(v, &mut buf),
179            Value::Custom(v) => v.0.encode(&mut buf),
180        }
181        .map_err(crate::Error::Encode)?;
182        Ok(match is_null {
183            IsNull::Yes => None,
184            IsNull::No => Some(buf.to_vec()),
185        })
186    }
187
188    pub(crate) fn bind(self, args: &mut PgArguments) -> Result<()> {
189        let res = match self {
190            Value::Bool(v) => args.add(v),
191            Value::I16(v) => args.add(v),
192            Value::I32(v) => args.add(v),
193            Value::I64(v) => args.add(v),
194            Value::F32(v) => args.add(v),
195            Value::F64(v) => args.add(v),
196            Value::String(v) => args.add(v),
197            Value::Bytes(v) => args.add(v),
198            #[cfg(feature = "uuid")]
199            Value::Uuid(v) => args.add(v),
200            #[cfg(feature = "chrono")]
201            Value::DateTime(v) => args.add(v),
202            #[cfg(feature = "chrono")]
203            Value::NaiveDateTime(v) => args.add(v),
204            #[cfg(feature = "chrono")]
205            Value::NaiveDate(v) => args.add(v),
206            #[cfg(feature = "chrono")]
207            Value::NaiveTime(v) => args.add(v),
208            #[cfg(feature = "json")]
209            Value::Json(v) => args.add(v),
210            Value::Custom(v) => v.0.bind(args),
211        };
212        res.map_err(crate::Error::Encode)
213    }
214}
215
216/// A value of a user-defined type; see [`Value::custom`].
217#[derive(Clone)]
218pub struct CustomValue(Arc<dyn DynValue>);
219
220trait DynValue: Send + Sync {
221    fn bind(&self, args: &mut PgArguments) -> std::result::Result<(), sqlx::error::BoxDynError>;
222    fn encode(
223        &self,
224        buf: &mut PgArgumentBuffer,
225    ) -> std::result::Result<IsNull, sqlx::error::BoxDynError>;
226    fn is_null(&self) -> bool;
227    fn show(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result;
228}
229
230impl<T> DynValue for Option<T>
231where
232    T: for<'q> Encode<'q, Postgres> + Type<Postgres> + Clone + fmt::Debug + Send + Sync + 'static,
233{
234    fn bind(&self, args: &mut PgArguments) -> std::result::Result<(), sqlx::error::BoxDynError> {
235        args.add(self.clone())
236    }
237
238    fn encode(
239        &self,
240        buf: &mut PgArgumentBuffer,
241    ) -> std::result::Result<IsNull, sqlx::error::BoxDynError> {
242        Encode::<Postgres>::encode_by_ref(self, buf)
243    }
244
245    fn is_null(&self) -> bool {
246        self.is_none()
247    }
248
249    fn show(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
250        match self {
251            Some(v) => write!(f, "{v:?}"),
252            None => f.write_str("NULL"),
253        }
254    }
255}
256
257impl fmt::Debug for CustomValue {
258    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
259        self.0.show(f)
260    }
261}
262
263impl PartialEq for CustomValue {
264    /// Custom values compare by their debug representation.
265    fn eq(&self, other: &Self) -> bool {
266        format!("{self:?}") == format!("{other:?}")
267    }
268}
269
270/// Marker for user-defined column types stored through [`Value::custom`].
271///
272/// Implemented by [`impl_value!`](crate::impl_value), `#[derive(DbEnum)]` and
273/// `#[derive(DbNewtype)]`; it unlocks `From<Option<T>>` and
274/// `From<&Option<T>>` for [`Value`], which a downstream crate couldn't write
275/// itself.
276pub trait CustomType:
277    for<'q> Encode<'q, Postgres> + Type<Postgres> + Clone + fmt::Debug + Send + Sync + 'static
278{
279}
280
281impl<T: CustomType> From<Option<T>> for Value {
282    fn from(v: Option<T>) -> Self {
283        Value::custom(v)
284    }
285}
286
287impl<T: CustomType> From<&Option<T>> for Value {
288    fn from(v: &Option<T>) -> Self {
289        Value::custom(v.clone())
290    }
291}
292
293/// Make a type usable as a rok-db column value (in models, filters and
294/// `set`), given that it already implements sqlx's `Type` and `Encode` for
295/// PostgreSQL plus `Clone + Debug`. Implements [`CustomType`] and
296/// `From<T>` / `From<&T>` for [`Value`] (`Option<T>` then works too).
297///
298/// `#[derive(DbEnum)]` and `#[derive(DbNewtype)]` do this for you.
299///
300/// ```ignore
301/// rok_db::impl_value!(my_crate::Money);
302/// ```
303#[macro_export]
304macro_rules! impl_value {
305    ($($ty:ty),+ $(,)?) => {$(
306        impl $crate::CustomType for $ty {}
307        impl ::core::convert::From<$ty> for $crate::Value {
308            fn from(v: $ty) -> Self {
309                $crate::Value::custom(::core::option::Option::Some(v))
310            }
311        }
312        impl ::core::convert::From<&$ty> for $crate::Value {
313            fn from(v: &$ty) -> Self {
314                $crate::Value::custom(::core::option::Option::Some(::core::clone::Clone::clone(v)))
315            }
316        }
317    )+};
318}
319
320/// PostgreSQL arrays (`TEXT[]`, `BIGINT[]`, …) as column values.
321macro_rules! impl_array {
322    ($($t:ty),* $(,)?) => {$(
323        impl CustomType for Vec<$t> {}
324        impl From<Vec<$t>> for Value {
325            fn from(v: Vec<$t>) -> Self {
326                Value::custom(Some(v))
327            }
328        }
329        impl From<&Vec<$t>> for Value {
330            fn from(v: &Vec<$t>) -> Self {
331                Value::custom(Some(v.clone()))
332            }
333        }
334        impl From<&[$t]> for Value {
335            fn from(v: &[$t]) -> Self {
336                Value::custom(Some(v.to_vec()))
337            }
338        }
339    )*};
340}
341
342impl_array!(String, bool, i16, i32, i64, f32, f64);
343
344#[cfg(feature = "uuid")]
345impl_array!(sqlx::types::Uuid);
346
347#[cfg(feature = "chrono")]
348impl_array!(
349    sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>,
350    sqlx::types::chrono::NaiveDate,
351);
352
353macro_rules! impl_from {
354    ($($variant:ident => $ty:ty),* $(,)?) => {$(
355        impl From<$ty> for Value {
356            fn from(v: $ty) -> Self { Value::$variant(Some(v.into())) }
357        }
358        impl From<Option<$ty>> for Value {
359            fn from(v: Option<$ty>) -> Self { Value::$variant(v.map(Into::into)) }
360        }
361        impl From<&$ty> for Value {
362            fn from(v: &$ty) -> Self { Value::from(v.clone()) }
363        }
364        impl From<&Option<$ty>> for Value {
365            fn from(v: &Option<$ty>) -> Self { Value::from(v.clone()) }
366        }
367    )*};
368}
369
370impl_from! {
371    Bool => bool,
372    I16 => i16,
373    I32 => i32,
374    I64 => i64,
375    F32 => f32,
376    F64 => f64,
377    String => String,
378    Bytes => Vec<u8>,
379}
380
381#[cfg(feature = "uuid")]
382impl_from! { Uuid => sqlx::types::Uuid }
383
384#[cfg(feature = "chrono")]
385impl_from! {
386    DateTime => sqlx::types::chrono::DateTime<sqlx::types::chrono::Utc>,
387    NaiveDateTime => sqlx::types::chrono::NaiveDateTime,
388    NaiveDate => sqlx::types::chrono::NaiveDate,
389    NaiveTime => sqlx::types::chrono::NaiveTime,
390}
391
392#[cfg(feature = "json")]
393impl_from! { Json => serde_json::Value }
394
395#[cfg(feature = "json")]
396impl<T: serde::Serialize> From<sqlx::types::Json<T>> for Value {
397    fn from(v: sqlx::types::Json<T>) -> Self {
398        Value::Json(serde_json::to_value(&v.0).ok())
399    }
400}
401
402#[cfg(feature = "json")]
403impl<T: serde::Serialize> From<&sqlx::types::Json<T>> for Value {
404    fn from(v: &sqlx::types::Json<T>) -> Self {
405        Value::Json(serde_json::to_value(&v.0).ok())
406    }
407}
408
409#[cfg(feature = "json")]
410impl<T: serde::Serialize> From<&Option<sqlx::types::Json<T>>> for Value {
411    fn from(v: &Option<sqlx::types::Json<T>>) -> Self {
412        Value::Json(v.as_ref().and_then(|v| serde_json::to_value(&v.0).ok()))
413    }
414}
415
416#[cfg(feature = "json")]
417impl<T: serde::Serialize> From<Option<sqlx::types::Json<T>>> for Value {
418    fn from(v: Option<sqlx::types::Json<T>>) -> Self {
419        Value::Json(v.and_then(|v| serde_json::to_value(&v.0).ok()))
420    }
421}
422
423impl From<&str> for Value {
424    fn from(v: &str) -> Self {
425        Value::String(Some(v.to_owned()))
426    }
427}
428
429impl From<Option<&str>> for Value {
430    fn from(v: Option<&str>) -> Self {
431        Value::String(v.map(str::to_owned))
432    }
433}
434
435impl From<&[u8]> for Value {
436    fn from(v: &[u8]) -> Self {
437        Value::Bytes(Some(v.to_vec()))
438    }
439}
440
441impl From<i8> for Value {
442    fn from(v: i8) -> Self {
443        Value::I16(Some(v.into()))
444    }
445}
446
447impl From<u8> for Value {
448    fn from(v: u8) -> Self {
449        Value::I16(Some(v.into()))
450    }
451}
452
453impl From<u16> for Value {
454    fn from(v: u16) -> Self {
455        Value::I32(Some(v.into()))
456    }
457}
458
459impl From<u32> for Value {
460    fn from(v: u32) -> Self {
461        Value::I64(Some(v.into()))
462    }
463}
464
465impl std::fmt::Display for Value {
466    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
467        fn show<T: std::fmt::Debug>(
468            f: &mut std::fmt::Formatter<'_>,
469            v: &Option<T>,
470        ) -> std::fmt::Result {
471            match v {
472                Some(v) => write!(f, "{v:?}"),
473                None => f.write_str("NULL"),
474            }
475        }
476        match self {
477            Value::Bool(v) => show(f, v),
478            Value::I16(v) => show(f, v),
479            Value::I32(v) => show(f, v),
480            Value::I64(v) => show(f, v),
481            Value::F32(v) => show(f, v),
482            Value::F64(v) => show(f, v),
483            Value::String(v) => show(f, v),
484            Value::Bytes(v) => show(f, v),
485            #[cfg(feature = "uuid")]
486            Value::Uuid(v) => show(f, v),
487            #[cfg(feature = "chrono")]
488            Value::DateTime(v) => show(f, v),
489            #[cfg(feature = "chrono")]
490            Value::NaiveDateTime(v) => show(f, v),
491            #[cfg(feature = "chrono")]
492            Value::NaiveDate(v) => show(f, v),
493            #[cfg(feature = "chrono")]
494            Value::NaiveTime(v) => show(f, v),
495            #[cfg(feature = "json")]
496            Value::Json(v) => show(f, v),
497            Value::Custom(v) => v.0.show(f),
498        }
499    }
500}
501
502#[cfg(test)]
503mod tests {
504    use super::*;
505
506    #[test]
507    fn conversions_keep_types() {
508        assert_eq!(Value::from(1_i32), Value::I32(Some(1)));
509        assert_eq!(Value::from("a"), Value::String(Some("a".into())));
510        assert_eq!(Value::from(None::<i64>), Value::I64(None));
511        assert_eq!(Value::from(&Some(true)), Value::Bool(Some(true)));
512        assert!(Value::from(None::<String>).is_null());
513        assert!(!Value::from(0_u8).is_null());
514    }
515}