drizzle-core 0.1.9

A type-safe SQL query builder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
//! Deserialization from JSON columns in query results.

use core::fmt;
use core::marker::PhantomData;

use serde::Deserialize;
use serde::de::{self, IgnoredAny, MapAccess, SeqAccess, Visitor};

use crate::error::DrizzleError;
use crate::prelude::*;
use crate::relation::RelationDef;

use super::row::QueryRow;
use super::store::RelEntry;

/// Decodes one field from a JSON object map.
///
/// Generated table models implement this so relation rows can be decoded in a
/// single serde pass without building an intermediate JSON tree.
pub trait JsonObjectDecoder<'de>: Sized {
    /// Scratch state used while a JSON object is being read.
    type State;

    /// Creates an empty decode state.
    fn begin() -> Self::State;

    /// Attempts to decode `key` from `map` into `state`.
    ///
    /// Returns `true` when the key was consumed. If this returns `false`, the
    /// caller remains responsible for consuming the map value.
    ///
    /// # Errors
    /// Returns the serde map error when a matched field fails to decode.
    fn decode_field<A>(state: &mut Self::State, key: &str, map: &mut A) -> Result<bool, A::Error>
    where
        A: MapAccess<'de>;

    /// Builds the decoded value from its completed state.
    ///
    /// # Errors
    /// Returns a serde error when required fields were not present.
    fn finish<E>(state: Self::State) -> Result<Self, E>
    where
        E: de::Error;
}

/// Deserializes a value directly from JSON text.
pub trait FromJsonObject: Sized {
    /// Reads `Self` from a JSON string.
    ///
    /// # Errors
    /// Returns `DrizzleError` if the JSON text cannot be decoded as `Self`.
    fn from_json_str(json: &str, context: &str) -> Result<Self, DrizzleError>;
}

impl<T> FromJsonObject for T
where
    T: for<'de> Deserialize<'de>,
{
    #[inline]
    fn from_json_str(json: &str, context: &str) -> Result<Self, DrizzleError> {
        serde_json::from_str(json)
            .map_err(|e| DrizzleError::Other(format!("failed to parse {context} JSON: {e}").into()))
    }
}

/// Deserializes a `RelEntry` chain from relation JSON columns.
pub trait DeserializeStore: Sized {
    /// Reads relation JSON columns from a row reader.
    ///
    /// Each relation column is parsed when its matching relation field is
    /// decoded.
    ///
    /// # Errors
    /// Returns `DrizzleError` if a JSON column is missing or fails to decode.
    fn from_json_columns<F>(next: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut() -> Result<Option<String>, DrizzleError>;
}

impl DeserializeStore for () {
    #[inline]
    fn from_json_columns<F>(_next: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut() -> Result<Option<String>, DrizzleError>,
    {
        Ok(())
    }
}

impl<'de> JsonObjectDecoder<'de> for () {
    type State = ();

    #[inline]
    fn begin() -> Self::State {}

    #[inline]
    fn decode_field<A>(_state: &mut Self::State, _key: &str, _map: &mut A) -> Result<bool, A::Error>
    where
        A: MapAccess<'de>,
    {
        Ok(false)
    }

    #[inline]
    fn finish<E>(_state: Self::State) -> Result<Self, E>
    where
        E: de::Error,
    {
        Ok(())
    }
}

impl<Rel, Data, Rest> DeserializeStore for RelEntry<Rel, Data, Rest>
where
    Rel: RelationDef,
    Data: FromJsonColumn,
    Rest: DeserializeStore,
{
    fn from_json_columns<F>(next: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut() -> Result<Option<String>, DrizzleError>,
    {
        let json = next()?;
        let data = Data::from_json_column(json.as_deref(), Rel::NAME)
            .map_err(|e| DrizzleError::Other(format!("relation '{}': {e}", Rel::NAME).into()))?;
        let rest = Rest::from_json_columns(next)?;
        Ok(Self::new(data, rest))
    }
}

impl<'de, Rel, Data, Rest> JsonObjectDecoder<'de> for RelEntry<Rel, Data, Rest>
where
    Rel: RelationDef,
    Data: FromJsonField<'de>,
    Rest: JsonObjectDecoder<'de>,
{
    type State = (Option<Data>, Rest::State);

    fn begin() -> Self::State {
        (None, Rest::begin())
    }

    fn decode_field<A>(state: &mut Self::State, key: &str, map: &mut A) -> Result<bool, A::Error>
    where
        A: MapAccess<'de>,
    {
        if key == Rel::NAME {
            state.0 = Some(Data::decode_json_field(map, Rel::NAME)?);
            return Ok(true);
        }

        Rest::decode_field(&mut state.1, key, map)
    }

    fn finish<E>(state: Self::State) -> Result<Self, E>
    where
        E: de::Error,
    {
        let data = match state.0 {
            Some(data) => data,
            None => Data::missing_json_field(Rel::NAME)?,
        };
        let rest = Rest::finish(state.1)?;
        Ok(Self::new(data, rest))
    }
}

/// Parses a relation's wrapped data from JSON text.
///
/// Implemented for `Vec<T>` (Many), `Option<T>` (`OptionalOne`), and
/// `QueryRow<Base, Store>` (One).
pub trait FromJsonColumn: Sized {
    /// Converts an optional JSON column into this relation data type.
    ///
    /// # Errors
    /// Returns `DrizzleError` when the JSON text does not match the expected
    /// shape for this type.
    fn from_json_column(json: Option<&str>, context: &str) -> Result<Self, DrizzleError>;
}

/// Decodes a relation field from a parent JSON object.
pub trait FromJsonField<'de>: Sized {
    /// Reads this value from a serde map entry.
    ///
    /// # Errors
    /// Returns the serde map error if the value fails to decode.
    fn decode_json_field<A>(map: &mut A, context: &str) -> Result<Self, A::Error>
    where
        A: MapAccess<'de>;

    /// Supplies the value for a missing relation field.
    ///
    /// # Errors
    /// Returns a serde error when the relation is required.
    fn missing_json_field<E>(context: &str) -> Result<Self, E>
    where
        E: de::Error;
}

impl<T> FromJsonColumn for Vec<T>
where
    T: for<'de> Deserialize<'de>,
{
    fn from_json_column(json: Option<&str>, context: &str) -> Result<Self, DrizzleError> {
        match json {
            Some(json) => serde_json::from_str::<JsonVec<T>>(json)
                .map(|items| items.0)
                .map_err(|e| {
                    DrizzleError::Other(format!("failed to parse {context} JSON: {e}").into())
                }),
            None => Ok(Self::new()),
        }
    }
}

impl<'de, T> FromJsonField<'de> for Vec<T>
where
    T: Deserialize<'de>,
{
    fn decode_json_field<A>(map: &mut A, _context: &str) -> Result<Self, A::Error>
    where
        A: MapAccess<'de>,
    {
        map.next_value::<JsonVec<T>>().map(|items| items.0)
    }

    fn missing_json_field<E>(_context: &str) -> Result<Self, E>
    where
        E: de::Error,
    {
        Ok(Self::new())
    }
}

impl<T> FromJsonColumn for Option<T>
where
    T: for<'de> Deserialize<'de>,
{
    fn from_json_column(json: Option<&str>, context: &str) -> Result<Self, DrizzleError> {
        match json {
            Some(json) => serde_json::from_str(json).map_err(|e| {
                DrizzleError::Other(format!("failed to parse {context} JSON: {e}").into())
            }),
            None => Ok(None),
        }
    }
}

impl<'de, T> FromJsonField<'de> for Option<T>
where
    T: Deserialize<'de>,
{
    fn decode_json_field<A>(map: &mut A, _context: &str) -> Result<Self, A::Error>
    where
        A: MapAccess<'de>,
    {
        map.next_value()
    }

    fn missing_json_field<E>(_context: &str) -> Result<Self, E>
    where
        E: de::Error,
    {
        Ok(None)
    }
}

impl<Base, Store> FromJsonColumn for QueryRow<Base, Store>
where
    Self: for<'de> Deserialize<'de>,
{
    fn from_json_column(json: Option<&str>, context: &str) -> Result<Self, DrizzleError> {
        let Some(json) = json else {
            return Err(DrizzleError::Other(
                format!("missing JSON column for {context}").into(),
            ));
        };

        let row: Option<Self> = serde_json::from_str(json).map_err(|e| {
            DrizzleError::Other(format!("failed to parse {context} JSON: {e}").into())
        })?;
        row.ok_or_else(|| {
            DrizzleError::Other(format!("expected non-null relation '{context}'").into())
        })
    }
}

impl<'de, Base, Store> FromJsonField<'de> for QueryRow<Base, Store>
where
    Self: Deserialize<'de>,
{
    fn decode_json_field<A>(map: &mut A, context: &str) -> Result<Self, A::Error>
    where
        A: MapAccess<'de>,
    {
        let row: Option<Self> = map.next_value()?;
        row.ok_or_else(|| de::Error::custom(format!("expected non-null relation '{context}'")))
    }

    fn missing_json_field<E>(context: &str) -> Result<Self, E>
    where
        E: de::Error,
    {
        Err(de::Error::custom(format!(
            "missing non-null relation '{context}'"
        )))
    }
}

impl<'de, Base, Store> Deserialize<'de> for QueryRow<Base, Store>
where
    Base: JsonObjectDecoder<'de>,
    Store: JsonObjectDecoder<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct QueryRowVisitor<Base, Store>(PhantomData<(Base, Store)>);

        impl<'de, Base, Store> Visitor<'de> for QueryRowVisitor<Base, Store>
        where
            Base: JsonObjectDecoder<'de>,
            Store: JsonObjectDecoder<'de>,
        {
            type Value = QueryRow<Base, Store>;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a relation row JSON object")
            }

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut base = Base::begin();
                let mut store = Store::begin();

                while let Some(key) = map.next_key::<Cow<'de, str>>()? {
                    let key = key.as_ref();
                    if Base::decode_field(&mut base, key, &mut map)? {
                        continue;
                    }
                    if Store::decode_field(&mut store, key, &mut map)? {
                        continue;
                    }
                    map.next_value::<IgnoredAny>()?;
                }

                Ok(QueryRow::new(Base::finish(base)?, Store::finish(store)?))
            }
        }

        deserializer.deserialize_map(QueryRowVisitor::<Base, Store>(PhantomData))
    }
}

/// Deserializes JSON booleans that may be represented as `0` or `1`.
pub struct JsonBool(pub bool);

impl<'de> Deserialize<'de> for JsonBool {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct BoolVisitor;

        impl Visitor<'_> for BoolVisitor {
            type Value = JsonBool;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a boolean or integer")
            }

            fn visit_bool<E>(self, value: bool) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonBool(value))
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonBool(value != 0))
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonBool(value != 0))
            }
        }

        deserializer.deserialize_any(BoolVisitor)
    }
}

/// Deserializes nullable JSON booleans that may be represented as `0` or `1`.
pub struct JsonOptionalBool(pub Option<bool>);

impl<'de> Deserialize<'de> for JsonOptionalBool {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct OptionalBoolVisitor;

        impl<'de> Visitor<'de> for OptionalBoolVisitor {
            type Value = JsonOptionalBool;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a nullable boolean or integer")
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonOptionalBool(None))
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonOptionalBool(None))
            }

            fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
            where
                D: serde::Deserializer<'de>,
            {
                JsonBool::deserialize(deserializer).map(|value| JsonOptionalBool(Some(value.0)))
            }
        }

        deserializer.deserialize_option(OptionalBoolVisitor)
    }
}

struct JsonVec<T>(Vec<T>);

impl<'de, T> Deserialize<'de> for JsonVec<T>
where
    T: Deserialize<'de>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct JsonVecVisitor<T>(PhantomData<T>);

        impl<'de, T> Visitor<'de> for JsonVecVisitor<T>
        where
            T: Deserialize<'de>,
        {
            type Value = JsonVec<T>;

            fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                f.write_str("a JSON array or null")
            }

            fn visit_unit<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonVec(Vec::new()))
            }

            fn visit_none<E>(self) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                Ok(JsonVec(Vec::new()))
            }

            fn visit_seq<A>(self, mut seq: A) -> Result<Self::Value, A::Error>
            where
                A: SeqAccess<'de>,
            {
                let mut out = Vec::with_capacity(seq.size_hint().unwrap_or(0));
                while let Some(value) = seq.next_element::<Option<T>>()? {
                    if let Some(value) = value {
                        out.push(value);
                    }
                }
                Ok(JsonVec(out))
            }
        }

        deserializer.deserialize_any(JsonVecVisitor::<T>(PhantomData))
    }
}