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
258#[allow(unused_imports)]
259pub(crate) use type_to_value;
260
261type_to_value!(bool, Bool, Boolean);
262type_to_value!(i8, TinyInt, TinyInteger);
263type_to_value!(i16, SmallInt, SmallInteger);
264type_to_value!(i32, Int, Integer);
265type_to_value!(i64, BigInt, BigInteger);
266type_to_value!(u8, TinyUnsigned, TinyUnsigned);
267type_to_value!(u16, SmallUnsigned, SmallUnsigned);
268type_to_value!(u32, Unsigned, Unsigned);
269type_to_value!(u64, BigUnsigned, BigUnsigned);
270type_to_value!(f32, Float, Float);
271type_to_value!(f64, Double, Double);
272type_to_value!(char, Char, Char(None));
273type_to_value!(Vec<u8>, Bytes, Blob);
274type_to_value!(String, String, Text);
275
276macro_rules! type_ref_to_value {
277    ( $type: ty, $name: ident ) => {
278        impl From<&$type> for Value {
279            fn from(x: &$type) -> Value {
280                Value::$name(Some(*x))
281            }
282        }
283    };
284}
285
286type_ref_to_value!(bool, Bool);
287type_ref_to_value!(i8, TinyInt);
288type_ref_to_value!(i16, SmallInt);
289type_ref_to_value!(i32, Int);
290type_ref_to_value!(i64, BigInt);
291type_ref_to_value!(u8, TinyUnsigned);
292type_ref_to_value!(u16, SmallUnsigned);
293type_ref_to_value!(u32, Unsigned);
294type_ref_to_value!(u64, BigUnsigned);
295type_ref_to_value!(f32, Float);
296type_ref_to_value!(f64, Double);
297type_ref_to_value!(char, Char);
298
299/// `From<&T>` for a value type that converts by clone, so a borrowed list
300/// (`&ids`, `&uuids`) converts as its items do.
301macro_rules! type_ref_clone_to_value {
302    ( $($type: ty),+ ) => {$(
303        impl From<&$type> for Value {
304            fn from(x: &$type) -> Value {
305                x.clone().into()
306            }
307        }
308    )+};
309}
310
311pub(crate) use type_ref_clone_to_value;
312
313type_ref_clone_to_value!(Vec<u8>);
314
315#[allow(unused_macros)]
316macro_rules! type_to_box_value {
317    ( $type: ty, $name: ident, $col_type: expr ) => {
318        impl From<$type> for Value {
319            fn from(x: $type) -> Value {
320                Value::$name(Some(Box::new(x)))
321            }
322        }
323
324        impl Nullable for $type {
325            fn null() -> Value {
326                Value::$name(None)
327            }
328        }
329
330        impl ValueType for $type {
331            fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
332                match v {
333                    Value::$name(Some(x)) => Ok(*x),
334                    _ => Err(ValueTypeErr),
335                }
336            }
337
338            fn type_name() -> String {
339                stringify!($type).to_owned()
340            }
341
342            fn array_type() -> ArrayType {
343                ArrayType::$name
344            }
345
346            fn column_type() -> ColumnType {
347                use ColumnType::*;
348                $col_type
349            }
350
351            const COLUMN_KIND: ColumnKind = {
352                use ColumnType::*;
353                $col_type
354            }
355            .kind();
356        }
357    };
358}
359
360#[allow(unused_imports)]
361pub(crate) use type_to_box_value;