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    fn enum_type_name() -> Option<&'static str> {
91        None
92    }
93}
94
95impl<T> ValueType for Option<T>
96where
97    T: ValueType + Nullable,
98{
99    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
100        if v == T::null() {
101            Ok(None)
102        } else {
103            Ok(Some(T::try_from(v)?))
104        }
105    }
106
107    fn is_option() -> bool {
108        true
109    }
110
111    fn type_name() -> String {
112        format!("Option<{}>", T::type_name())
113    }
114
115    fn array_type() -> ArrayType {
116        T::array_type()
117    }
118
119    fn column_type() -> ColumnType {
120        T::column_type()
121    }
122}
123
124impl ValueType for Cow<'_, str> {
125    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
126        match v {
127            Value::String(Some(x)) => Ok((x).into()),
128            _ => Err(ValueTypeErr),
129        }
130    }
131
132    fn type_name() -> String {
133        "Cow<str>".into()
134    }
135
136    fn array_type() -> ArrayType {
137        ArrayType::String
138    }
139
140    fn column_type() -> ColumnType {
141        ColumnType::Text
142    }
143}
144
145#[derive(Debug)]
146pub struct ValueTypeErr;
147
148impl std::error::Error for ValueTypeErr {}
149
150impl std::fmt::Display for ValueTypeErr {
151    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
152        f.write_str("Value type mismatch")
153    }
154}
155
156#[derive(Clone, Debug, PartialEq)]
157pub struct Values(pub Vec<Value>);
158
159impl Values {
160    pub fn iter(&self) -> impl Iterator<Item = &Value> {
161        self.0.iter()
162    }
163}
164
165pub trait Nullable {
166    fn null() -> Value;
167}
168
169impl Nullable for &str {
170    fn null() -> Value {
171        Value::String(None)
172    }
173}
174
175impl Nullable for Enum {
176    fn null() -> Value {
177        Value::Enum(OptionEnum::None("".into()))
178    }
179}
180
181impl ValueType for Enum {
182    fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
183        match v {
184            Value::Enum(OptionEnum::Some(v)) => Ok(*v),
185            _ => Err(ValueTypeErr),
186        }
187    }
188
189    fn type_name() -> String {
190        "Enum".into()
191    }
192
193    // These implementations probably won’t actually be used, so there
194    // shouldn’t cause any runtime issues.
195    fn array_type() -> ArrayType {
196        ArrayType::String
197    }
198
199    fn column_type() -> ColumnType {
200        ColumnType::String(StringLen::None)
201    }
202}
203
204macro_rules! type_to_value {
205    ( $type: ty, $name: ident, $col_type: expr ) => {
206        impl From<$type> for Value {
207            fn from(x: $type) -> Value {
208                Value::$name(Some(x))
209            }
210        }
211
212        impl Nullable for $type {
213            fn null() -> Value {
214                Value::$name(None)
215            }
216        }
217
218        impl ValueType for $type {
219            fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
220                match v {
221                    Value::$name(Some(x)) => Ok(x),
222                    _ => Err(ValueTypeErr),
223                }
224            }
225
226            fn type_name() -> String {
227                stringify!($type).to_owned()
228            }
229
230            fn array_type() -> ArrayType {
231                ArrayType::$name
232            }
233
234            fn column_type() -> ColumnType {
235                use ColumnType::*;
236                $col_type
237            }
238        }
239    };
240}
241
242#[allow(unused_imports)]
243pub(crate) use type_to_value;
244
245type_to_value!(bool, Bool, Boolean);
246type_to_value!(i8, TinyInt, TinyInteger);
247type_to_value!(i16, SmallInt, SmallInteger);
248type_to_value!(i32, Int, Integer);
249type_to_value!(i64, BigInt, BigInteger);
250type_to_value!(u8, TinyUnsigned, TinyUnsigned);
251type_to_value!(u16, SmallUnsigned, SmallUnsigned);
252type_to_value!(u32, Unsigned, Unsigned);
253type_to_value!(u64, BigUnsigned, BigUnsigned);
254type_to_value!(f32, Float, Float);
255type_to_value!(f64, Double, Double);
256type_to_value!(char, Char, Char(None));
257type_to_value!(Vec<u8>, Bytes, Blob);
258type_to_value!(String, String, Text);
259
260macro_rules! type_ref_to_value {
261    ( $type: ty, $name: ident ) => {
262        impl From<&$type> for Value {
263            fn from(x: &$type) -> Value {
264                Value::$name(Some(*x))
265            }
266        }
267    };
268}
269
270type_ref_to_value!(bool, Bool);
271type_ref_to_value!(i8, TinyInt);
272type_ref_to_value!(i16, SmallInt);
273type_ref_to_value!(i32, Int);
274type_ref_to_value!(i64, BigInt);
275type_ref_to_value!(u8, TinyUnsigned);
276type_ref_to_value!(u16, SmallUnsigned);
277type_ref_to_value!(u32, Unsigned);
278type_ref_to_value!(u64, BigUnsigned);
279type_ref_to_value!(f32, Float);
280type_ref_to_value!(f64, Double);
281type_ref_to_value!(char, Char);
282
283/// `From<&T>` for a value type that converts by clone, so a borrowed list
284/// (`&ids`, `&uuids`) converts as its items do.
285macro_rules! type_ref_clone_to_value {
286    ( $($type: ty),+ ) => {$(
287        impl From<&$type> for Value {
288            fn from(x: &$type) -> Value {
289                x.clone().into()
290            }
291        }
292    )+};
293}
294
295pub(crate) use type_ref_clone_to_value;
296
297type_ref_clone_to_value!(Vec<u8>);
298
299#[allow(unused_macros)]
300macro_rules! type_to_box_value {
301    ( $type: ty, $name: ident, $col_type: expr ) => {
302        impl From<$type> for Value {
303            fn from(x: $type) -> Value {
304                Value::$name(Some(Box::new(x)))
305            }
306        }
307
308        impl Nullable for $type {
309            fn null() -> Value {
310                Value::$name(None)
311            }
312        }
313
314        impl ValueType for $type {
315            fn try_from(v: Value) -> Result<Self, ValueTypeErr> {
316                match v {
317                    Value::$name(Some(x)) => Ok(*x),
318                    _ => Err(ValueTypeErr),
319                }
320            }
321
322            fn type_name() -> String {
323                stringify!($type).to_owned()
324            }
325
326            fn array_type() -> ArrayType {
327                ArrayType::$name
328            }
329
330            fn column_type() -> ColumnType {
331                use ColumnType::*;
332                $col_type
333            }
334        }
335    };
336}
337
338#[allow(unused_imports)]
339pub(crate) use type_to_box_value;