Skip to main content

sql_builder/value/
conversions.rs

1use super::*;
2
3impl From<&[u8]> for Value {
4    fn from(x: &[u8]) -> Value {
5        Value::Bytes(Some(x.into()))
6    }
7}
8
9impl From<&str> for Value {
10    fn from(x: &str) -> Value {
11        Value::String(Some(x.to_owned()))
12    }
13}
14
15impl From<&String> for Value {
16    fn from(x: &String) -> Value {
17        Value::String(Some(x.clone()))
18    }
19}
20
21impl<T> From<Option<T>> for Value
22where
23    T: Into<Value> + Nullable,
24{
25    fn from(x: Option<T>) -> Value {
26        match x {
27            Some(v) => v.into(),
28            None => T::null(),
29        }
30    }
31}
32
33impl From<Cow<'_, str>> for Value {
34    fn from(x: Cow<'_, str>) -> Value {
35        x.into_owned().into()
36    }
37}
38
39impl From<Enum> for Value {
40    fn from(value: Enum) -> Value {
41        Value::Enum(OptionEnum::Some(Box::new(value)))
42    }
43}
44
45impl IntoIterator for Values {
46    type Item = Value;
47    type IntoIter = std::vec::IntoIter<Self::Item>;
48
49    fn into_iter(self) -> Self::IntoIter {
50        self.0.into_iter()
51    }
52}
53
54impl std::fmt::Display for Value {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        let mut sql = String::new();
57        CommonSqlQueryBuilder
58            .write_value(&mut sql, self)
59            .map_err(|_| std::fmt::Error)?;
60        f.write_str(&sql)
61    }
62}
63
64#[diagnostic::on_unimplemented(
65    message = "`{Self}` is not a type a column can hold",
66    label = "not a column type",
67    note = "a column's type implements `ValueType`: derive `DeriveValueType` for a newtype or `DeriveActiveEnum` for an enum, or store the value as a `String`"
68)]
69pub trait ValueType: Sized {
70    fn try_from(v: Value) -> Result<Self, ValueTypeErr>;
71
72    fn unwrap(v: Value) -> Self {
73        Self::try_from(v).unwrap()
74    }
75
76    fn expect(v: Value, msg: &str) -> Self {
77        Self::try_from(v).expect(msg)
78    }
79
80    fn is_option() -> bool {
81        false
82    }
83
84    fn type_name() -> String;
85
86    fn array_type() -> ArrayType;
87
88    fn column_type() -> ColumnType;
89
90    /// The [`kind`](ColumnType::kind) of [`column_type`](Self::column_type),
91    /// readable in a `const`; [`ColumnKind::Other`] unless the type sets it.
92    const COLUMN_KIND: ColumnKind = ColumnKind::Other;
93
94    fn enum_type_name() -> Option<&'static str> {
95        None
96    }
97}
98
99impl<T> ValueType for Option<T>
100where
101    T: ValueType + Nullable,
102{
103    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
104        if v == T::null() {
105            Ok(None)
106        } else {
107            Ok(Some(T::try_from(v)?))
108        }
109    }
110
111    fn is_option() -> bool {
112        true
113    }
114
115    fn type_name() -> String {
116        format!("Option<{}>", T::type_name())
117    }
118
119    fn array_type() -> ArrayType {
120        T::array_type()
121    }
122
123    fn column_type() -> ColumnType {
124        T::column_type()
125    }
126
127    const COLUMN_KIND: ColumnKind = T::COLUMN_KIND;
128}
129
130impl ValueType for Cow<'_, str> {
131    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
132        match v {
133            Value::String(Some(x)) => Ok((x).into()),
134            _ => Err(ValueTypeErr),
135        }
136    }
137
138    fn type_name() -> String {
139        "Cow<str>".into()
140    }
141
142    fn array_type() -> ArrayType {
143        ArrayType::String
144    }
145
146    fn column_type() -> ColumnType {
147        ColumnType::Text
148    }
149
150    const COLUMN_KIND: ColumnKind = ColumnKind::Text;
151}
152
153#[derive(Debug)]
154pub struct ValueTypeErr;
155
156impl std::error::Error for ValueTypeErr {}
157
158impl std::fmt::Display for ValueTypeErr {
159    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
160        f.write_str("Value type mismatch")
161    }
162}
163
164#[derive(Clone, Debug, PartialEq)]
165pub struct Values(pub Vec<Value>);
166
167impl Values {
168    pub fn iter(&self) -> impl Iterator<Item = &Value> {
169        self.0.iter()
170    }
171}
172
173pub trait Nullable {
174    fn null() -> Value;
175}
176
177impl Nullable for &str {
178    fn null() -> Value {
179        Value::String(None)
180    }
181}
182
183impl Nullable for Enum {
184    fn null() -> Value {
185        Value::Enum(OptionEnum::None("".into()))
186    }
187}
188
189impl ValueType for Enum {
190    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
191        match v {
192            Value::Enum(OptionEnum::Some(v)) => Ok(*v),
193            _ => Err(ValueTypeErr),
194        }
195    }
196
197    fn type_name() -> String {
198        "Enum".into()
199    }
200
201    // These implementations probably won’t actually be used, so there
202    // shouldn’t cause any runtime issues.
203    fn array_type() -> ArrayType {
204        ArrayType::String
205    }
206
207    fn column_type() -> ColumnType {
208        ColumnType::String(StringLen::None)
209    }
210
211    const COLUMN_KIND: ColumnKind = ColumnKind::Text;
212}
213
214macro_rules! type_to_value {
215    ( $type: ty, $name: ident, $col_type: expr ) => {
216        impl From<$type> for Value {
217            fn from(x: $type) -> Value {
218                Value::$name(Some(x))
219            }
220        }
221
222        impl Nullable for $type {
223            fn null() -> Value {
224                Value::$name(None)
225            }
226        }
227
228        impl ValueType for $type {
229            fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
230                match v {
231                    Value::$name(Some(x)) => Ok(x),
232                    _ => Err(ValueTypeErr),
233                }
234            }
235
236            fn type_name() -> String {
237                stringify!($type).to_owned()
238            }
239
240            fn array_type() -> ArrayType {
241                ArrayType::$name
242            }
243
244            fn column_type() -> ColumnType {
245                use ColumnType::*;
246                $col_type
247            }
248
249            const COLUMN_KIND: ColumnKind = {
250                use ColumnType::*;
251                $col_type
252            }
253            .kind();
254        }
255    };
256}
257
258pub(crate) use type_to_value;
259
260type_to_value!(bool, Bool, Boolean);
261type_to_value!(i8, TinyInt, TinyInteger);
262type_to_value!(i16, SmallInt, SmallInteger);
263type_to_value!(i32, Int, Integer);
264type_to_value!(i64, BigInt, BigInteger);
265type_to_value!(u8, TinyUnsigned, TinyUnsigned);
266type_to_value!(u16, SmallUnsigned, SmallUnsigned);
267type_to_value!(u32, Unsigned, Unsigned);
268type_to_value!(u64, BigUnsigned, BigUnsigned);
269type_to_value!(f32, Float, Float);
270type_to_value!(f64, Double, Double);
271type_to_value!(char, Char, Char(None));
272type_to_value!(Vec<u8>, Bytes, Blob);
273type_to_value!(String, String, Text);
274
275macro_rules! type_ref_to_value {
276    ( $type: ty, $name: ident ) => {
277        impl From<&$type> for Value {
278            fn from(x: &$type) -> Value {
279                Value::$name(Some(*x))
280            }
281        }
282    };
283}
284
285type_ref_to_value!(bool, Bool);
286type_ref_to_value!(i8, TinyInt);
287type_ref_to_value!(i16, SmallInt);
288type_ref_to_value!(i32, Int);
289type_ref_to_value!(i64, BigInt);
290type_ref_to_value!(u8, TinyUnsigned);
291type_ref_to_value!(u16, SmallUnsigned);
292type_ref_to_value!(u32, Unsigned);
293type_ref_to_value!(u64, BigUnsigned);
294type_ref_to_value!(f32, Float);
295type_ref_to_value!(f64, Double);
296type_ref_to_value!(char, Char);
297
298/// `From<&T>` for a value type that converts by clone, so a borrowed list
299/// (`&ids`, `&uuids`) converts as its items do.
300macro_rules! type_ref_clone_to_value {
301    ( $($type: ty),+ ) => {$(
302        impl From<&$type> for Value {
303            fn from(x: &$type) -> Value {
304                x.clone().into()
305            }
306        }
307    )+};
308}
309
310pub(crate) use type_ref_clone_to_value;
311
312type_ref_clone_to_value!(Vec<u8>);
313
314macro_rules! type_to_box_value {
315    ( $type: ty, $name: ident, $col_type: expr ) => {
316        impl From<$type> for Value {
317            fn from(x: $type) -> Value {
318                Value::$name(Some(Box::new(x)))
319            }
320        }
321
322        impl Nullable for $type {
323            fn null() -> Value {
324                Value::$name(None)
325            }
326        }
327
328        impl ValueType for $type {
329            fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
330                match v {
331                    Value::$name(Some(x)) => Ok(*x),
332                    _ => Err(ValueTypeErr),
333                }
334            }
335
336            fn type_name() -> String {
337                stringify!($type).to_owned()
338            }
339
340            fn array_type() -> ArrayType {
341                ArrayType::$name
342            }
343
344            fn column_type() -> ColumnType {
345                use ColumnType::*;
346                $col_type
347            }
348
349            const COLUMN_KIND: ColumnKind = {
350                use ColumnType::*;
351                $col_type
352            }
353            .kind();
354        }
355    };
356}
357
358pub(crate) use type_to_box_value;