drizzle-core 0.2.0

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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
//! Deserialization from JSON columns in query results.

use core::fmt;
use core::marker::PhantomData;
use core::str::FromStr;

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

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

use super::builder::BuildRow;
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 positional 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>;

    /// Reads relation JSON columns through a by-name lookup.
    ///
    /// Each entry in the chain requests its own relation name, so callers
    /// holding column-keyed rows need no positional bookkeeping. A lookup
    /// result of `Ok(None)` means the column was SQL `NULL` or absent.
    ///
    /// # Errors
    /// Returns `DrizzleError` if the lookup fails or a JSON column fails to
    /// decode.
    fn from_named_json_columns<F>(lookup: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut(&str) -> 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(())
    }

    #[inline]
    fn from_named_json_columns<F>(_lookup: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut(&str) -> 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))
    }

    fn from_named_json_columns<F>(lookup: &mut F) -> Result<Self, DrizzleError>
    where
        F: FnMut(&str) -> Result<Option<String>, DrizzleError>,
    {
        let json = lookup(Rel::NAME)?;
        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_named_json_columns(lookup)?;
        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))
    }
}

// =============================================================================
// JSON-text row transport
// =============================================================================

/// A relational query row transported entirely as JSON text columns.
///
/// Produced by [`build_query_sql`](super::build_query_sql) with
/// `wrap_base_json = true`: the base model arrives as a single `"__base"`
/// JSON text column (BLOBs hex-encoded in SQL) and each relation as a
/// `"__rel_<name>"` JSON text column.
///
/// This is the row shape for drivers whose rows are column-keyed serde
/// objects rather than positional columns (Cloudflare D1 and Durable
/// Objects). For those transports JSON text is also the only lossless value
/// carrier: raw values cross the JS boundary as `f64`, truncating 64-bit
/// integers, and raw blob bytes don't match the hex contract of the
/// generated model decoders.
#[derive(Debug)]
pub struct JsonQueryRow {
    /// JSON text of the `"__base"` column.
    base: String,
    /// `(relation name, JSON text)` pairs; `None` marks SQL `NULL`.
    rels: Vec<(String, Option<String>)>,
}

impl JsonQueryRow {
    /// Parses the base model and every relation, assembling the public row.
    ///
    /// Relations resolve by name in whatever order `Rels` declares them, so
    /// the transported column order is irrelevant.
    ///
    /// # Errors
    /// Returns `DrizzleError` if the base or a relation's JSON fails to
    /// decode.
    pub fn into_row<Base, Rels>(mut self) -> Result<Rels::Row, DrizzleError>
    where
        Base: FromJsonObject,
        Rels: BuildRow<Base>,
        Rels::Store: DeserializeStore,
    {
        let base = Base::from_json_str(&self.base, "base")?;
        let store = Rels::Store::from_named_json_columns(&mut |name| Ok(self.take_rel(name)))?;
        Ok(Rels::assemble(base, store))
    }

    /// Removes and returns the JSON text for `name`, once.
    fn take_rel(&mut self, name: &str) -> Option<String> {
        self.rels
            .iter_mut()
            .find(|(rel, _)| rel == name)
            .and_then(|(_, json)| json.take())
    }
}

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

        impl<'de> Visitor<'de> for RowVisitor {
            type Value = JsonQueryRow;

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

            fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
            where
                A: MapAccess<'de>,
            {
                let mut base = None;
                let mut rels = Vec::new();

                while let Some(key) = map.next_key::<Cow<'de, str>>()? {
                    if key == "__base" {
                        base = Some(map.next_value()?);
                    } else if let Some(name) = key.strip_prefix("__rel_") {
                        rels.push((name.to_owned(), map.next_value()?));
                    } else {
                        map.next_value::<IgnoredAny>()?;
                    }
                }

                let base = base.ok_or_else(|| de::Error::missing_field("__base"))?;
                Ok(JsonQueryRow { base, rels })
            }
        }

        deserializer.deserialize_map(RowVisitor)
    }
}

// =============================================================================
// Field decoding helpers for generated row decoders
// =============================================================================

/// A field value read from a relational query's JSON projection.
///
/// Generated row decoders read a field into `RawJson` before applying the
/// column's codec, so the generated code never names the JSON library.
pub type RawJson = serde_json::Value;

/// Decodes a JSON column whose storage is text, such as a SQLite JSON
/// column.
///
/// A relational projection embeds such a column as a JSON string that holds
/// the document; this parses the string. A value that arrives already
/// embedded as JSON is decoded directly.
///
/// # Errors
///
/// Returns a serde error naming `column` when the document does not match
/// `T`.
#[doc(hidden)]
pub fn decode_json_text<T, E>(raw: RawJson, column: &str) -> Result<T, E>
where
    T: DeserializeOwned,
    E: de::Error,
{
    let decoded = match raw {
        serde_json::Value::String(text) => serde_json::from_str(&text),
        value => serde_json::from_value(value),
    };
    decoded.map_err(|e| E::custom(format!("field '{column}': invalid JSON: {e}")))
}

/// Decodes JSON bytes, such as a JSON document stored in a BLOB.
///
/// # Errors
///
/// Returns a serde error naming `column` when `bytes` are not a JSON
/// document matching `T`.
#[doc(hidden)]
pub fn decode_json_bytes<T, E>(bytes: &[u8], column: &str) -> Result<T, E>
where
    T: DeserializeOwned,
    E: de::Error,
{
    serde_json::from_slice(bytes)
        .map_err(|e| E::custom(format!("field '{column}': invalid JSON blob: {e}")))
}

/// Decodes an enum projected either as a JSON string (a native enum stored
/// by name) or as a JSON integer (an integer-backed enum).
///
/// # Errors
///
/// Returns a serde error naming `column` when the value is neither form, or
/// names no variant of `T`.
#[doc(hidden)]
pub fn decode_enum_value<T, E>(raw: RawJson, column: &str) -> Result<T, E>
where
    T: TryFrom<i64> + FromStr,
    <T as FromStr>::Err: fmt::Display,
    E: de::Error,
{
    match raw {
        serde_json::Value::Number(number) => {
            let value = number.as_i64().ok_or_else(|| {
                E::custom(format!(
                    "enum field '{column}': invalid integer value {number}"
                ))
            })?;
            T::try_from(value).map_err(|_| {
                E::custom(format!(
                    "enum field '{column}': invalid integer value {value}"
                ))
            })
        }
        serde_json::Value::String(value) => T::from_str(&value)
            .map_err(|error| E::custom(format!("enum field '{column}': {error}"))),
        value => Err(E::custom(format!(
            "enum field '{column}': expected string or integer, got {value}"
        ))),
    }
}

/// 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))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn parse_row(json: &str) -> JsonQueryRow {
        serde_json::from_str(json).expect("row should deserialize")
    }

    #[test]
    fn json_query_row_splits_base_and_relation_columns() {
        let mut row = parse_row(
            r#"{"__base":"{\"id\":1}","__rel_posts":"[]","__rel_author":null,"noise":42}"#,
        );

        assert_eq!(row.base, r#"{"id":1}"#);
        assert_eq!(row.take_rel("posts").as_deref(), Some("[]"));
        assert_eq!(row.take_rel("posts"), None, "each relation decodes once");
        assert_eq!(row.take_rel("author"), None, "SQL NULL maps to None");
        assert_eq!(row.take_rel("missing"), None);
    }

    #[test]
    fn json_query_row_requires_base_column() {
        let error = serde_json::from_str::<JsonQueryRow>(r#"{"__rel_posts":"[]"}"#)
            .expect_err("a row without __base is malformed");
        assert!(error.to_string().contains("__base"));
    }

    #[test]
    fn into_row_parses_base_json() {
        let row = parse_row(r#"{"__base":"{\"id\":7,\"name\":\"a\"}"}"#);
        let value = row
            .into_row::<serde_json::Value, ()>()
            .expect("base JSON should parse");
        assert_eq!(value["id"], 7);
        assert_eq!(value["name"], "a");
    }

    #[test]
    fn json_text_fields_parse_the_embedded_document() {
        let embedded = RawJson::String(r#"{"id":7}"#.into());
        let value: serde_json::Value =
            decode_json_text::<_, serde_json::Error>(embedded, "meta").unwrap();
        assert_eq!(value["id"], 7);

        let native: Vec<i64> =
            decode_json_text::<_, serde_json::Error>(serde_json::json!([1, 2]), "tags").unwrap();
        assert_eq!(native, [1, 2]);

        let error =
            decode_json_text::<Vec<i64>, serde_json::Error>(RawJson::String("oops".into()), "tags")
                .unwrap_err();
        assert!(error.to_string().contains("field 'tags'"));
    }

    #[test]
    fn json_bytes_fields_report_the_column() {
        let tags: Vec<i64> = decode_json_bytes::<_, serde_json::Error>(b"[3]", "tags").unwrap();
        assert_eq!(tags, [3]);
        let error = decode_json_bytes::<Vec<i64>, serde_json::Error>(b"{", "tags").unwrap_err();
        assert!(error.to_string().contains("field 'tags'"));
    }

    #[test]
    fn enum_values_accept_names_and_integers() {
        let from_integer: i32 =
            decode_enum_value::<_, serde_json::Error>(serde_json::json!(5), "rank").unwrap();
        assert_eq!(from_integer, 5);
        let from_name: i32 =
            decode_enum_value::<_, serde_json::Error>(serde_json::json!("6"), "rank").unwrap();
        assert_eq!(from_name, 6);
        let error = decode_enum_value::<i32, serde_json::Error>(serde_json::json!(true), "rank")
            .unwrap_err();
        assert!(error.to_string().contains("expected string or integer"));
    }

    #[test]
    fn into_row_reports_invalid_base_json() {
        let row = parse_row(r#"{"__base":"not json"}"#);
        let error = row
            .into_row::<serde_json::Value, ()>()
            .expect_err("invalid base JSON should fail");
        assert!(error.to_string().contains("base"));
    }
}