qbrs-core 0.1.0

Core type-level machinery for the qbrs query builder (scope tracking, expressions, builders).
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
//! Rows keyed by column rather than by position.
//!
//! A tuple selection decodes to `Row<..>`: a type-level list of
//! `(key, value)` cells. A column's key is its `expr::ColumnKey`, a computed
//! expression's is the identity it carries (`expr::Count`,
//! `window::RowNumber`), and `.label(label::..)` supplies one for anything that has
//! none. `Field` looks a key up the way `scope::Find` looks a table up, with
//! the same `Here`/`There` index.
//!
//! Keying by column is what makes adding a column to a selection a
//! non-breaking change, and what makes two same-typed columns
//! (`orders::user_id` and `orders::total` are both `BigInt`) impossible to
//! transpose. `into_tuple`/`into_tuples` recover the positional view where
//! destructuring is what's wanted, and `FromRow` fills a plain struct by
//! matching field *names*, so a DTO names no column and no table.
//!
//! Naming a row type takes a type alias long enough to trip
//! `clippy::type_complexity`, the same lint `qbrs-core` allows crate-wide.
//! Inference covers every use that stays inside a function.
//!
//! **Known limitations**: a key selected twice is ambiguous at the point it
//! is read, rather than resolving to the first — give one of them a
//! `label!{}` label. `into_tuple` is implemented up to 16 columns; `Row`
//! itself has no such limit. A field with no name (a bare `sql!{}`
//! fragment) can only be reached positionally until `.label(label::..)` gives it one.

use std::marker::PhantomData;

use crate::expr::{Column, ColumnKey, Keyed, Labeled, SqlType};
use crate::scope::{Here, There};

/// The empty row.
pub struct RowNil;

/// One field: `V`, filed under key `K`, followed by the rest in `Tail`.
pub struct RowCons<K, V, Tail> {
    value: V,
    tail: Tail,
    _key: PhantomData<fn() -> K>,
}

impl<K, V, Tail> RowCons<K, V, Tail> {
    /// This cell's value. With `tail` and the key's `Named::NAME`, this is
    /// everything a downstream crate needs to walk a row under whatever
    /// bounds it wants — `serde::Serialize`, `Display`, anything — which
    /// `qbrs-core` can't offer itself, having no dependencies.
    pub fn value(&self) -> &V {
        &self.value
    }

    /// The rest of the row.
    pub fn tail(&self) -> &Tail {
        &self.tail
    }

    #[doc(hidden)]
    pub fn new(value: V, tail: Tail) -> Self {
        RowCons {
            value,
            tail,
            _key: PhantomData,
        }
    }

    /// This cell's value and the rest, by value — what a walk that consumes
    /// the chain needs (`insert::InsertValues`).
    #[doc(hidden)]
    pub fn into_cell(self) -> (V, Tail) {
        (self.value, self.tail)
    }
}

mod field {
    /// Carries the trait's own parameters and is implemented only for the
    /// honest pairs, for the reason `scope::proof` explains: a column
    /// marker is the caller's own type, so a seal on `Self` alone — or a
    /// private proof *type*, which projection reaches — would let a schema
    /// crate prove its column is in a row that doesn't hold it.
    pub trait Sealed<K, Idx> {}
}

/// Proof that a row holds a field under key `K`, at compile-time-inferred
/// position `Idx`. `Idx` is never spelled out by callers, exactly as in
/// `scope::Find`, and is what keeps the two impls below structurally
/// distinct rather than overlapping.
///
/// Borrowing and moving are one trait because they are one search: `pluck`
/// additionally reports what the row is left holding, so several fields can
/// be moved out in turn.
#[diagnostic::on_unimplemented(
    message = "`{K}` is not in this query's selection",
    label = "a row can only be read by a key the query selected",
    note = "add `{K}` to the query's selection list, or `.label(label::..)` the expression you meant — and in a generic helper give each column its own `Idx` parameter, since one shared index matches no row"
)]
pub trait Field<K, Idx>: field::Sealed<K, Idx> {
    type Value;
    type Rest;
    fn peek(&self) -> &Self::Value;
    fn pluck(self) -> (Self::Value, Self::Rest);
}

impl<K, V, Tail> field::Sealed<K, Here> for RowCons<K, V, Tail> {}

impl<K, V, Tail> Field<K, Here> for RowCons<K, V, Tail> {
    type Value = V;
    type Rest = Tail;
    fn peek(&self) -> &V {
        &self.value
    }
    fn pluck(self) -> (V, Tail) {
        (self.value, self.tail)
    }
}

#[diagnostic::do_not_recommend]
impl<K, Other, V, Tail, I> field::Sealed<K, There<I>> for RowCons<Other, V, Tail> where
    Tail: Field<K, I>
{
}

impl<K, Other, V, Tail, I> Field<K, There<I>> for RowCons<Other, V, Tail>
where
    Tail: Field<K, I>,
{
    type Value = <Tail as Field<K, I>>::Value;
    type Rest = RowCons<Other, V, <Tail as Field<K, I>>::Rest>;
    fn peek(&self) -> &Self::Value {
        self.tail.peek()
    }
    fn pluck(self) -> (Self::Value, Self::Rest) {
        let (value, rest) = self.tail.pluck();
        (value, RowCons::new(self.value, rest))
    }
}

/// An identifier spelled one `char` per cell, so two keys declared in
/// different crates can be compared by the *name* they share rather than by
/// being the same type. `char` is one of the three types stable const
/// generics accept.
#[doc(hidden)]
pub struct NameChar<const C: char, Rest>(PhantomData<Rest>);

/// End of a `NameChar` chain.
#[doc(hidden)]
pub struct NameEnd;

/// Builds a `NameChar` chain from character literals.
#[doc(hidden)]
#[macro_export]
macro_rules! type_name {
    () => { $crate::row::NameEnd };
    ($c:literal $(, $rest:literal)*) => {
        $crate::row::NameChar<$c, $crate::type_name!($($rest),*)>
    };
}

/// A key that has a name, so a field can be found by what it is called
/// rather than by which key type produced it, and so a row can print itself
/// keyed. Implemented by `#[derive(Table)]` for columns, by `label!` for
/// labels, and by the built-in expression keys.
pub trait Named: named::Sealed {
    type Name;
    const NAME: &'static str;
}

pub(crate) mod named {
    /// Sealed the way `scope::BaseTable` is: a name is written by a macro —
    /// `#[derive(Table)]`, `with!`, `label!`, or `expr_key!` — so the
    /// spelling in `Named::NAME` and the one in the SQL cannot disagree.
    pub trait Sealed {}
}

#[doc(hidden)]
pub use named::Sealed as NamedSealed;

/// A key someone wrote down: a column, a `label!`, or one of the built-in
/// expression keys. `Anon` is deliberately not one, which is what keeps two
/// unnamed columns from standing in for each other, keeps an unnamed field
/// out of reach of `.get()`, and keeps a by-name lookup from landing on one.
pub trait Spelled: Named {}

/// The key of a selected item that carries no name of its own — a bare
/// `sql!{}` fragment.
pub struct Anon;

#[doc(hidden)]
impl NamedSealed for Anon {}

impl Named for Anon {
    type Name = NameEnd;
    const NAME: &'static str = "?";
}

/// What a `#[derive(FromRow)]` field decodes to, declared beside its name
/// so that a lookup searches for the *pair*. With the type checked
/// afterwards instead — as an equality on `TakeNamed::Value` — a field whose
/// type disagrees with the join reports a bare associated-type mismatch at
/// `into_structs()`, naming neither the field nor the fix.
pub trait FieldValue {
    type Value;
}

mod take_named {
    /// The same shape as `field::Sealed`, and for the same reason.
    pub trait Sealed<F, Idx> {}
}

/// `Field` by name rather than by key identity, which is what lets a struct
/// that has never heard of `users::email` still receive it.
#[diagnostic::on_unimplemented(
    message = "this query's rows have no field matching `{F}`",
    label = "the selection needs a column of that name, decoding to that type",
    note = "a computed expression is matched by name only once `.label(label::..)` gives it one, and a LEFT/RIGHT/FULL JOIN makes a column decode as `Option<T>`, so a struct filled from one declares `Option<T>`"
)]
pub trait TakeNamed<F, Idx>: take_named::Sealed<F, Idx> {
    type Value;
    type Rest;
    fn take_named(self) -> (Self::Value, Self::Rest);
}

impl<F, K, V, Tail> take_named::Sealed<F, Here> for RowCons<K, V, Tail>
where
    K: Spelled,
    F: Spelled<Name = <K as Named>::Name> + FieldValue<Value = V>,
{
}

impl<F, K, V, Tail> TakeNamed<F, Here> for RowCons<K, V, Tail>
where
    K: Spelled,
    F: Spelled<Name = <K as Named>::Name> + FieldValue<Value = V>,
{
    type Value = V;
    type Rest = Tail;
    fn take_named(self) -> (V, Tail) {
        (self.value, self.tail)
    }
}

#[diagnostic::do_not_recommend]
impl<F, K, V, Tail, I> take_named::Sealed<F, There<I>> for RowCons<K, V, Tail> where
    Tail: TakeNamed<F, I>
{
}

impl<F, K, V, Tail, I> TakeNamed<F, There<I>> for RowCons<K, V, Tail>
where
    Tail: TakeNamed<F, I>,
{
    type Value = <Tail as TakeNamed<F, I>>::Value;
    type Rest = RowCons<K, V, <Tail as TakeNamed<F, I>>::Rest>;
    fn take_named(self) -> (Self::Value, Self::Rest) {
        let (value, rest) = self.tail.take_named();
        (value, RowCons::new(self.value, rest))
    }
}

mod same_name {
    /// Sealed with the same bounds the one honest impl has: `Self` is a
    /// column marker local to whoever derived the schema and `Other` is
    /// free, so without this a schema crate could write
    /// `impl SameNameAs<a::columns::one> for b::columns::two {}` and splice
    /// a `UNION` branch or a CTE body in transposed — the failure
    /// `SameShape` is here to stop.
    pub trait Sealed<Other> {}

    impl<A, B> Sealed<B> for A
    where
        A: super::Spelled,
        B: super::Spelled<Name = <A as super::Named>::Name>,
    {
    }
}

/// One column can stand in for another: they are called the same thing.
#[diagnostic::on_unimplemented(
    message = "`{Self}` can't stand in for `{Other}`",
    label = "these two selected items must have the same name",
    note = "matched by name: `.label(label::..)` whichever side is spelled wrong — and an unnamed expression (`Anon`) has no name to match with at all"
)]
pub trait SameNameAs<Other>: same_name::Sealed<Other> {}

#[diagnostic::do_not_recommend]
impl<A, B> SameNameAs<B> for A
where
    A: Spelled,
    B: Spelled<Name = <A as Named>::Name>,
{
}

/// Two selections produce the same row: the same column names, in the same
/// order, decoding to the same types. A one-column selection decodes to a
/// bare value rather than a `Row`, and two of those match when the value
/// types do — there is no name to disagree about. Names as well as types, because a
/// `UNION` branch or a CTE body whose columns merely happen to be
/// type-compatible would otherwise splice in transposed.
#[diagnostic::on_unimplemented(
    message = "these two selections don't produce the same row",
    label = "must select the same names, in the same order, decoding to the same types"
)]
pub trait SameShape<Other> {}

// Walked cell by cell rather than compared as tuples: the positional view
// stops at 16 fields, and two selections agree or don't regardless of how
// wide they are. No `do_not_recommend` on the cons impl — it is what keeps
// the `SameNameAs` obligation the one that gets reported.
impl SameShape<RowNil> for RowNil {}

impl<K1, K2, V, Tail1, Tail2> SameShape<RowCons<K2, V, Tail2>> for RowCons<K1, V, Tail1>
where
    K1: SameNameAs<K2>,
    Tail1: SameShape<Tail2>,
{
}

impl<A, B> SameShape<Row<B>> for Row<A> where A: SameShape<B> {}

/// Maps a value written in a selection list to the type its field is filed
/// under, so a field is read back with the same value that selected it.
/// Carries no message of its own: it is reached both from a selection list
/// (where `SelectionPart` says what belongs in one) and from `.get()`
/// (where `LookupKey` says what can name a field), and each of those is the
/// accurate sentence in its position.
pub trait RowKey {
    type Key;
}

#[diagnostic::do_not_recommend]
impl<C: ColumnKey> RowKey for Column<C> {
    type Key = C;
}

#[diagnostic::do_not_recommend]
impl<K, Req, S: SqlType> RowKey for Keyed<K, Req, S> {
    type Key = K;
}

#[diagnostic::do_not_recommend]
impl<K, Inner> RowKey for Labeled<K, Inner> {
    type Key = K;
}

mod column_names {
    /// Sealed to the two shapes a row has: `CteShape::Row` is bounded by
    /// `ColumnNames`, so an open impl would let a `WITH` header be spelled
    /// by something that is not the row `SameShape` checked — and a local
    /// type in that position is also what makes `SameShape` itself
    /// forgeable.
    pub trait Sealed {}
}

/// The names a declared row spells, in order — read off the row itself so
/// a `WITH name (..)` header cannot disagree with the shape its body was
/// checked against. Implemented here only, for `RowNil` and `RowCons`.
pub trait ColumnNames: column_names::Sealed {
    /// One `push` per field, so the list is built without an allocation per
    /// level of the chain.
    #[doc(hidden)]
    fn push_names(out: &mut Vec<&'static str>);

    fn names() -> Vec<&'static str> {
        let mut out = Vec::new();
        Self::push_names(&mut out);
        out
    }
}

impl column_names::Sealed for RowNil {}

impl ColumnNames for RowNil {
    fn push_names(_out: &mut Vec<&'static str>) {}
}

impl<K: Named, V, Tail: ColumnNames> column_names::Sealed for RowCons<K, V, Tail> {}

impl<K: Named, V, Tail: ColumnNames> ColumnNames for RowCons<K, V, Tail> {
    fn push_names(out: &mut Vec<&'static str>) {
        out.push(<K as Named>::NAME);
        Tail::push_names(out);
    }
}

/// A value that can name a field at a `.get()`/`.take()` call. Every
/// `RowKey` can *file* a field; only these can find one again, which is what
/// keeps an unlabelled expression's `Anon` field out of reach of any other
/// unlabelled expression. `RowKey where Key: Spelled` would say the same
/// rule — this exists to carry the message below, which that bound reports
/// as a bare missing `Spelled` impl on `Anon`.
#[diagnostic::on_unimplemented(
    message = "`{Self}` doesn't name a field",
    label = "an unlabelled expression has no name to look up",
    note = "give it one with `.label(label::..)`, or read it positionally with `into_tuple()`"
)]
pub trait LookupKey: RowKey {}

#[diagnostic::do_not_recommend]
impl<C: ColumnKey> LookupKey for Column<C> {}
#[diagnostic::do_not_recommend]
impl<K: Spelled, Req, S: SqlType> LookupKey for Keyed<K, Req, S> {}
#[diagnostic::do_not_recommend]
impl<K: Spelled, Inner> LookupKey for Labeled<K, Inner> {}

/// A decoded row. Its fields are fixed by the query's selection list, and
/// each is read by the same value that selected it.
pub struct Row<L>(L);

impl<L> Row<L> {
    #[doc(hidden)]
    pub fn new(fields: L) -> Self {
        Row(fields)
    }

    /// The row's fields as a `RowCons` chain, for walking it from another
    /// crate. `get`/`take`/`into_struct` cover reading a known field; this
    /// is for code that has to visit every field it happens to hold.
    pub fn fields(&self) -> &L {
        &self.0
    }

    /// `row.get(users::email)` — the key is the same value that appeared in
    /// the selection list, so there is no name to keep in sync and no
    /// position to get wrong.
    pub fn get<K: LookupKey, Idx>(&self, _key: K) -> &<L as Field<K::Key, Idx>>::Value
    where
        L: Field<K::Key, Idx>,
    {
        self.0.peek()
    }

    /// Moves one field out and hands back the row without it, so several
    /// fields can be taken in turn.
    pub fn take<K: LookupKey, Idx>(
        self,
        _key: K,
    ) -> (
        <L as Field<K::Key, Idx>>::Value,
        Row<<L as Field<K::Key, Idx>>::Rest>,
    )
    where
        L: Field<K::Key, Idx>,
    {
        let (value, rest) = self.0.pluck();
        (value, Row::new(rest))
    }

    /// Reads a field by naming its key type rather than passing the value
    /// that selected it — what the generated accessors use, since a
    /// built-in expression key is never spelled at a call site.
    #[doc(hidden)]
    pub fn peek_key<K, Idx>(&self) -> &<L as Field<K, Idx>>::Value
    where
        L: Field<K, Idx>,
    {
        self.0.peek()
    }

    /// `take` by key type rather than by the value that selected it —
    /// what a `#[from_row(from = ..)]` field uses, since identity is the
    /// one lookup that stays unambiguous when two columns share a name.
    #[doc(hidden)]
    pub fn take_key<K, Idx>(self) -> (<L as Field<K, Idx>>::Value, Row<<L as Field<K, Idx>>::Rest>)
    where
        L: Field<K, Idx>,
    {
        let (value, rest) = self.0.pluck();
        (value, Row::new(rest))
    }

    #[doc(hidden)]
    pub fn take_named<F, Idx>(
        self,
    ) -> (
        <L as TakeNamed<F, Idx>>::Value,
        Row<<L as TakeNamed<F, Idx>>::Rest>,
    )
    where
        L: TakeNamed<F, Idx>,
    {
        let (value, rest) = self.0.take_named();
        (value, Row::new(rest))
    }

    /// Builds a `#[derive(FromRow)]` struct out of this row, matching its
    /// fields by name. Extra columns in the row are ignored, and the order
    /// they were selected in doesn't matter.
    pub fn into_struct<T, Idxs>(self) -> T
    where
        T: FromRow<L, Idxs>,
    {
        T::from_row(self)
    }

    /// The positional view: the plain tuple this selection would decode to
    /// if rows didn't exist.
    pub fn into_tuple(self) -> L::Values
    where
        L: RowValues,
    {
        self.0.into_values()
    }
}

/// Prints a row keyed, since being keyed is the whole point of the type.
pub trait DebugFields {
    fn fmt_fields(&self, f: &mut std::fmt::DebugStruct<'_, '_>);
}

impl DebugFields for RowNil {
    fn fmt_fields(&self, _f: &mut std::fmt::DebugStruct<'_, '_>) {}
}

impl<K: Named, V: std::fmt::Debug, Tail: DebugFields> DebugFields for RowCons<K, V, Tail> {
    fn fmt_fields(&self, f: &mut std::fmt::DebugStruct<'_, '_>) {
        f.field(K::NAME, &self.value);
        self.tail.fmt_fields(f);
    }
}

impl<L: DebugFields> std::fmt::Debug for Row<L> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut s = f.debug_struct("Row");
        self.0.fmt_fields(&mut s);
        s.finish()
    }
}

impl<K, V: Clone, Tail: Clone> Clone for RowCons<K, V, Tail> {
    fn clone(&self) -> Self {
        RowCons::new(self.value.clone(), self.tail.clone())
    }
}

impl Clone for RowNil {
    fn clone(&self) -> Self {
        RowNil
    }
}

impl<L: Clone> Clone for Row<L> {
    fn clone(&self) -> Self {
        Row(self.0.clone())
    }
}

impl<K, V: PartialEq, Tail: PartialEq> PartialEq for RowCons<K, V, Tail> {
    fn eq(&self, other: &Self) -> bool {
        self.value == other.value && self.tail == other.tail
    }
}

impl PartialEq for RowNil {
    fn eq(&self, _other: &Self) -> bool {
        true
    }
}

impl<K, V: Eq, Tail: Eq> Eq for RowCons<K, V, Tail> {}
impl Eq for RowNil {}

impl<L: PartialEq> PartialEq for Row<L> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<L: Eq> Eq for Row<L> {}

/// A row's fields as a plain tuple, in selection order.
pub trait RowValues {
    type Values;
    fn into_values(self) -> Self::Values;
}

/// Adds one element to the front of a tuple. The only place `Row`'s
/// positional view has an arity limit.
#[diagnostic::on_unimplemented(
    message = "this row has no positional view",
    label = "`into_tuple`/`into_tuples` stop at 16 fields, however they were selected",
    note = "read it by key (`row.get(..)`) or fill a struct with `#[derive(FromRow)]`"
)]
pub trait Prepend<H> {
    type Output;
    fn prepend(self, head: H) -> Self::Output;
}

impl<H> Prepend<H> for () {
    type Output = (H,);
    fn prepend(self, head: H) -> (H,) {
        (head,)
    }
}

macro_rules! prepend_impls {
    () => {};
    ($first:ident $(, $rest:ident)*) => {
        #[allow(non_snake_case)]
        impl<H, $first $(, $rest)*> Prepend<H> for ($first, $($rest,)*) {
            type Output = (H, $first, $($rest,)*);
            fn prepend(self, head: H) -> Self::Output {
                let ($first, $($rest,)*) = self;
                (head, $first, $($rest,)*)
            }
        }
        prepend_impls!($($rest),*);
    };
}
prepend_impls!(
    T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
);

impl RowValues for RowNil {
    type Values = ();
    fn into_values(self) {}
}

impl<K, V, Tail> RowValues for RowCons<K, V, Tail>
where
    Tail: RowValues,
    Tail::Values: Prepend<V>,
{
    type Values = <Tail::Values as Prepend<V>>::Output;
    fn into_values(self) -> Self::Values {
        self.tail.into_values().prepend(self.value)
    }
}

/// `Vec<Row<..>> -> Vec<(..)>`.
pub trait IntoTuples {
    type Tuples;
    fn into_tuples(self) -> Self::Tuples;
}

impl<L: RowValues> IntoTuples for Vec<Row<L>> {
    type Tuples = Vec<L::Values>;
    fn into_tuples(self) -> Vec<L::Values> {
        self.into_iter().map(Row::into_tuple).collect()
    }
}

/// Builds a plain struct out of a row by matching field names, generated by
/// `#[derive(FromRow)]`. `Idxs` holds the per-field lookup indices, for the
/// reason `scope::Superset` explains, which is also why this is its own
/// trait rather than `From`.
pub trait FromRow<L, Idxs>: Sized {
    fn from_row(row: Row<L>) -> Self;
}

/// `Vec<Row<..>> -> Vec<T>` for any `#[derive(FromRow)]` struct.
pub trait IntoStructs {
    type Fields;
    fn into_structs<T, Idxs>(self) -> Vec<T>
    where
        T: FromRow<Self::Fields, Idxs>;
}

impl<L> IntoStructs for Vec<Row<L>> {
    type Fields = L;
    fn into_structs<T, Idxs>(self) -> Vec<T>
    where
        T: FromRow<L, Idxs>,
    {
        self.into_iter().map(Row::into_struct).collect()
    }
}

/// Declares an expression's own row key and the `row.<name>()` accessor that
/// reads it, so a selection using one needs nothing declared at the call
/// site.
macro_rules! expr_key {
    ($key:ident, $accessor:ident, $method:ident, $doc:literal, $($ch:literal),+) => {
        #[doc = $doc]
        #[derive(Clone, Copy)]
        pub struct $key;

        #[doc(hidden)]
        impl $crate::row::NamedSealed for $key {}

        #[doc(hidden)]
        impl $crate::row::Named for $key {
            type Name = $crate::type_name!($($ch),+);
            const NAME: &'static str = concat!($($ch),+);
        }

        #[doc(hidden)]
        impl $crate::row::Spelled for $key {}

        #[doc = $doc]
        pub trait $accessor<Idx> {
            type Value;
            fn $method(&self) -> &Self::Value;
        }

        impl<L, Idx> $accessor<Idx> for $crate::row::Row<L>
        where
            L: $crate::row::Field<$key, Idx>,
        {
            type Value = <L as $crate::row::Field<$key, Idx>>::Value;
            fn $method(&self) -> &Self::Value {
                self.peek_key::<$key, Idx>()
            }
        }
    };
}
pub(crate) use expr_key;