ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
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
use super::{
  ListCrossingError, PgCollectionStorage, SqlListComparison, SqlSetComparison, cross_count,
  cross_element, flatten_list, from_stored,
};
// Gated with their only users, the two hand-written rows for the jiff → `time` bridge.
#[cfg(all(feature = "jiff", feature = "time"))]
use super::StrategyOver;
#[cfg(all(feature = "jiff", feature = "time"))]
use crate::Temporal;
use crate::{
  BeI128, BeU64, BeU128, Count, ListFilter, TryMapFilter,
  comparison::{
    At, Backend, ComplexComparison, ToDatabaseComparison, TryFromFilter,
    sql::{
      ELEMENT_ALIAS, ELEMENT_VALUE, SqlConjunction, SqlCountComparison, SqlEdgeComparison,
      SqlEdgeSetComparison, not_wrapped, push_column, push_count_slots, push_element_scope,
      quote_ident, render_column,
    },
  },
};

/// The bound Postgres's two column-stored lowerings share: sqlx's row naming the array type OID this
/// element lives in, beside the two that let a value of it bind at all.
///
/// Written once because both impls below and their four render helpers carry it, and six spellings
/// of one three-part bound are six places for a part to go missing. It is private and blanket-implemented,
/// so it narrows nothing: a type satisfies it exactly when it satisfies the three.
trait PgArrayElement:
  sqlx::postgres::PgHasArrayType
  + sqlx::Type<sqlx::Postgres>
  + for<'q> sqlx::Encode<'q, sqlx::Postgres>
{
}

impl<V> PgArrayElement for V where
  V: sqlx::postgres::PgHasArrayType
    + sqlx::Type<sqlx::Postgres>
    + for<'q> sqlx::Encode<'q, sqlx::Postgres>
{
}

/// State one element type's Postgres collection strategies, owned and borrowed together.
///
/// `$sequence` and `$set` are the comparisons the rows name — [`SqlListComparison`] /
/// [`SqlSetComparison`] for the column, [`SqlEdgeComparison`] / [`SqlEdgeSetComparison`] for the edge
/// table — so the strategy is a token a reader sees at the call site rather than a second macro to
/// keep in step with the first.
///
/// The two answers are stated together because the rows this crate ships agree, and not because the
/// trait makes them agree: an element may name the column for its ordered form and the edge table for
/// its unordered one, and doing so is a second invocation rather than a change here.
///
/// The borrowed row is emitted with the owned one for the reason
/// [`Carrier`](crate::comparison::sql::Carrier) carries a `&T` row: an operand that binds by
/// reference makes `SqlListComparison<&'a V, Db>` a real type, and a strategy table missing the
/// borrowed half would take that back on this dialect alone. It is a fresh row rather than a
/// delegation, because the answer is not `V`'s comparison — it is the same strategy over `&'a V`,
/// and an associated type cannot rewrite the element inside one.
macro_rules! pg_collection_storage {
  ($sequence:ident / $set:ident { $( $ty:ty ),+ $(,)? }) => {
    $(
      impl<VF: ToDatabaseComparison<$ty, sqlx::Postgres>> PgCollectionStorage<VF> for $ty {
        type Sequence = $sequence<$ty, VF::Comparison, sqlx::Postgres>;
        type Set = $set<$ty, VF::Comparison, sqlx::Postgres>;
      }

      impl<'a, VF: ToDatabaseComparison<&'a $ty, sqlx::Postgres>> PgCollectionStorage<VF>
        for &'a $ty
      {
        type Sequence = $sequence<&'a $ty, VF::Comparison, sqlx::Postgres>;
        type Set = $set<&'a $ty, VF::Comparison, sqlx::Postgres>;
      }
    )+
  };
}

// The elements whose native array type IS the array OF the column their `Carrier` row binds into,
// so an operand bound as `V[]` meets the column the schema declares:
//
//   bool                       BOOL       BOOL[]
//   i16 / i32 / i64            INT2/4/8   the matching _ARRAY
//   f32 / f64                  FLOAT4/8   the matching _ARRAY
//   String                     TEXT       TEXT[]
//   Vec<u8>                    BYTEA      BYTEA[]
//   Duration / PgInterval      INTERVAL   INTERVAL[]
pg_collection_storage!(SqlListComparison / SqlSetComparison {
  bool,
  i16,
  i32,
  i64,
  f32,
  f64,
  String,
  Vec<u8>,
  ::core::time::Duration,
  sqlx::postgres::types::PgInterval
});

// The elements that reach an edge table, and the three reasons one does.
//
// THE ARRAY TYPE SAYS A DIFFERENT COLUMN. `i8` and `u8` both have a `PgHasArrayType` row and neither
// is usable: this crate's carrier table WIDENS both to `smallint`, because Postgres has no 1-byte
// integer, while sqlx types `i8` as `"char"` (so `&[i8]` binds `"char"[]`) and gives `u8` the array
// type BYTEA — which is not an array at all, so `&[u8]` binds one blob. Each renders well-formed
// SQL against a column it does not match, which is why the row is where the two facts are read side
// by side.
//
// SQLX TYPES THE ELEMENT FOR NO POSTGRES COLUMN. `u16` and `u32` have no `Type<Postgres>` at all —
// the carrier table reaches them by widening to `i32` and `i64` — so the array path cannot be
// spelled for either, and before this table they resolved to it anyway.
//
// THE ELEMENT IS THIS CRATE'S OWN, AND OWNS ITS ENCODING RATHER THAN SQLX'S. `Score`, the three
// big-endian blob carriers and `Count` reach a column through `Carrier` and implement no
// `PgHasArrayType`, so there is no array type to name. `BeU64` is the case the `mod postgres` note
// already carried, and `Count` is the same fact at a type whose column IS an `int8`: what it has no
// array for is the NARROWING, which lives in its own `Encode` row and not in sqlx's `i64`.
pg_collection_storage!(
  SqlEdgeComparison
    / SqlEdgeSetComparison {
      i8,
      u8,
      u16,
      u32,
      BeU64,
      BeU128,
      BeI128,
      Count
    }
);

/// The confidence's pair, hand-written for the reason this file's other hand-written family is: a
/// free type parameter cannot cross `pg_collection_storage!`'s `$ty:ty`.
///
/// It is in the EDGE-TABLE family for the reason `Score` was — it owns its encoding rather than
/// sqlx's, reaching a column through [`Carrier`](crate::Carrier) and implementing no
/// `PgHasArrayType`, so there is no array type to name. The bound carries the membership: a
/// confidence has this row exactly where the width it measures in has a carrier.
impl<S, VF> PgCollectionStorage<VF> for crate::Confidence<S>
where
  S: crate::ConfidenceCarrier + crate::Carrier<sqlx::Postgres>,
  VF: ToDatabaseComparison<crate::Confidence<S>, sqlx::Postgres>,
{
  type Sequence = SqlEdgeComparison<crate::Confidence<S>, VF::Comparison, sqlx::Postgres>;
  type Set = SqlEdgeSetComparison<crate::Confidence<S>, VF::Comparison, sqlx::Postgres>;
}

impl<'a, S, VF> PgCollectionStorage<VF> for &'a crate::Confidence<S>
where
  S: crate::ConfidenceCarrier + crate::Carrier<sqlx::Postgres>,
  VF: ToDatabaseComparison<&'a crate::Confidence<S>, sqlx::Postgres>,
{
  type Sequence = SqlEdgeComparison<&'a crate::Confidence<S>, VF::Comparison, sqlx::Postgres>;
  type Set = SqlEdgeSetComparison<&'a crate::Confidence<S>, VF::Comparison, sqlx::Postgres>;
}

// `time`'s four carry natively in both shapes — TIMESTAMPTZ / TIMESTAMP / DATE / TIME beside their
// _ARRAYs — so they take the array with the primitives. Gated on `time` alone, exactly as their
// carrier rows are.
#[cfg(feature = "time")]
pg_collection_storage!(SqlListComparison / SqlSetComparison {
  time::OffsetDateTime,
  time::PrimitiveDateTime,
  time::Date,
  time::Time
});

/// The jiff → `time` bridge's row, hand-written for the reason `to_filter!` hand-writes `[u8; N]`'s
/// container family: a free type parameter cannot pass through the macro's `$ty:ty`.
///
/// # It reads `T`'s row rather than stating one of its own
///
/// The where-clause is the whole content: **`Temporal<T>` takes whichever strategies `T` declared,
/// over the wrapper.** [`Temporal<T>`](Temporal) is a conversion wrapper — the column a
/// `Vec<jiff::Timestamp>` lands in IS the column a `Vec<time::OffsetDateTime>` lands in — so a row
/// that could contradict `T`'s would be a wrapper deciding a question about the element it wraps.
/// Delegating makes the two temporal crates agree by CONSTRUCTION rather than for the three storage
/// forms that happen to line up today.
///
/// [`StrategyOver`](crate::comparison::sql::StrategyOver) is what carries the element across, and
/// the reason the row cannot simply repeat `T`'s answer: `T`'s row states COMPARISONS and a
/// comparison names its element, so what is read is `Strategy<T, Postgres>` where the wrapper needs
/// `Strategy<Temporal<T>, Postgres>`.
///
/// Deducing the strategy from `T: PgHasArrayType + Type + Encode` would look equivalent and is not,
/// and `i8` is the measurement: it satisfies all three and still declares the edge table, because
/// this crate's carrier widens it to `smallint` while sqlx types it `"char"` — so a deduced row
/// would send `Temporal<i8>` to an array of the wrong column. The refusal that keeps the strategy
/// DECLARED rather than deduced is the one [`PgCollectionStorage`]'s own note makes; this row
/// inherits it instead of re-litigating it.
///
/// # The lowering promise is kept on the RE-STATED comparisons, and names no capability
///
/// [`PgCollectionStorage`]'s two answers each promise [`ComplexComparison`], and the projections this
/// row states are opaque, so each promise is carried as a bound on its own projection. What those
/// bounds are NOT is a capability of `T`: they say the strategies `T` declared still lower once their
/// element is the wrapper, and each strategy's own impl decides what that costs — the column-stored
/// kinds read sqlx's three off `Temporal<T>`, which delegate to `T`, and the edge kinds read
/// [`Carrier`](crate::comparison::sql::Carrier), which does the same. Spelling either of those here
/// would be this row taking a view on a strategy it has not been told yet.
///
/// # Both strategies, and the annotation is what asserts which
///
/// The projection IS the strategy, so a row that moved is `E0308` here rather than a different
/// rendering. [`BeU64`] is the edge case that occurs in practice: a downstream storage form may be
/// any type with a [`Carrier`](crate::comparison::sql::Carrier) row — the trait naming one is
/// [`TemporalStorage`](crate::TemporalStorage), which is public and open — and this crate's blob
/// carrier is one.
///
/// ```
/// use ingraph::{
///   ListFilter, BeU64, Temporal, ToDatabaseComparison,
///   comparison::sql::{SqlEdgeComparison, SqlScalarComparison},
/// };
///
/// let _: Option<
///   <ListFilter<u64> as ToDatabaseComparison<Temporal<BeU64>, sqlx::Postgres>>::Comparison,
/// > = None::<SqlEdgeComparison<
///   Temporal<BeU64>,
///   SqlScalarComparison<Temporal<BeU64>, sqlx::Postgres>,
///   sqlx::Postgres,
/// >>;
/// ```
///
/// The set half reads the other column of the same row, and a `Vec<jiff::Timestamp>` stored through
/// `time` is where it lands on the array:
///
/// ```
/// use ingraph::{
///   SetFilter, Temporal, ToDatabaseComparison,
///   comparison::sql::{SqlScalarComparison, SqlSetComparison},
/// };
///
/// let _: Option<
///   <SetFilter<jiff::Timestamp> as ToDatabaseComparison<
///     Temporal<time::OffsetDateTime>,
///     sqlx::Postgres,
///   >>::Comparison,
/// > = None::<SqlSetComparison<
///   Temporal<time::OffsetDateTime>,
///   SqlScalarComparison<Temporal<time::OffsetDateTime>, sqlx::Postgres>,
///   sqlx::Postgres,
/// >>;
/// ```
///
/// # The one refusal left, and it names `T`
///
/// A `T` with NO storage row leaves `Temporal<T>` without one, because there is no declaration to
/// read — the wrapper does not invent a strategy for an element that has not stated one. The
/// sentence a reader acts on names `T`, which is where the missing row goes. The two blocks above
/// are this one's positive twins: stable rustdoc runs a `compile_fail` block just far enough to see
/// it fail and never checks why, so the pair shares its shape and one half has to be positive.
///
/// ```compile_fail,E0277
/// use ingraph::{ListFilter, Temporal, ToDatabaseComparison};
///
/// struct Tag;
///
/// let _: Option<
///   <ListFilter<Tag> as ToDatabaseComparison<Temporal<Tag>, sqlx::Postgres>>::Comparison,
/// > = None;
/// ```
// `do_not_recommend` on this pair and on nothing else in the table. Unimplemented, rustc lists the
// element types that DO have a row — truncated to the eight sorting first — and these two are the
// only entries in it whose presence depends on a feature, so they are the whole of why the same
// refusal read differently in a build without `jiff` and `time`. Suppressing them settles the text
// and leaves every other row recommendable, which is what a reader who named an element with no row
// is actually helped by.
#[cfg(all(feature = "jiff", feature = "time"))]
#[diagnostic::do_not_recommend]
impl<T, VF> PgCollectionStorage<VF> for Temporal<T>
where
  T: PgCollectionStorage<VF>,
  <T as PgCollectionStorage<VF>>::Sequence:
    StrategyOver<Temporal<T>, Comparison: ComplexComparison<sqlx::Postgres>>,
  <T as PgCollectionStorage<VF>>::Set:
    StrategyOver<Temporal<T>, Comparison: ComplexComparison<sqlx::Postgres>>,
{
  type Sequence =
    <<T as PgCollectionStorage<VF>>::Sequence as StrategyOver<Temporal<T>>>::Comparison;
  type Set = <<T as PgCollectionStorage<VF>>::Set as StrategyOver<Temporal<T>>>::Comparison;
}

/// The borrowed half, as [`Carrier`](crate::comparison::sql::Carrier) carries one. It reads the same
/// OWNED rows on `T`: what the wrapper is borrowed does not change which column `T` lives in.
#[cfg(all(feature = "jiff", feature = "time"))]
#[diagnostic::do_not_recommend]
impl<'a, T, VF> PgCollectionStorage<VF> for &'a Temporal<T>
where
  T: PgCollectionStorage<VF>,
  <T as PgCollectionStorage<VF>>::Sequence:
    StrategyOver<&'a Temporal<T>, Comparison: ComplexComparison<sqlx::Postgres>>,
  <T as PgCollectionStorage<VF>>::Set:
    StrategyOver<&'a Temporal<T>, Comparison: ComplexComparison<sqlx::Postgres>>,
{
  type Sequence =
    <<T as PgCollectionStorage<VF>>::Sequence as StrategyOver<&'a Temporal<T>>>::Comparison;
  type Set = <<T as PgCollectionStorage<VF>>::Set as StrategyOver<&'a Temporal<T>>>::Comparison;
}

impl<V, C> SqlListComparison<V, C, sqlx::Postgres> {
  /// Cross a [`ListFilter`] into a Postgres sequence comparison through ONE converter — see
  /// [`SqlEdgeComparison::try_from_filter_with`](crate::comparison::sql::SqlEdgeComparison::try_from_filter_with)
  /// for what the single converter is and why a declaration gets one.
  ///
  /// # Errors
  ///
  /// As [`try_from_filter_with_element`](Self::try_from_filter_with_element), with `f`'s refusal
  /// standing for both levels of operand.
  pub fn try_from_filter_with<D, VF, E, F>(
    filter: ListFilter<D, VF>,
    f: F,
  ) -> Result<Self, ListCrossingError<E, <C as TryFromFilter<VF::Mapped>>::Error>>
  where
    F: Fn(D) -> Result<V, E>,
    VF: TryMapFilter<D, V>,
    C: TryFromFilter<VF::Mapped>,
  {
    Self::try_from_filter_with_element(filter, &f, |element| {
      let stored = element
        .try_map_filter(&f)
        .map_err(ListCrossingError::Operand)?;
      C::try_from_filter(stored).map_err(ListCrossingError::Element)
    })
    .map_err(flatten_list)
  }

  /// Cross a [`ListFilter`] into a Postgres sequence comparison, converting each ELEMENT with `f`
  /// and the nested ELEMENT FILTER with `g`.
  ///
  /// This dialect refuses nothing of its own, where the two JSON dialects' crossings do: a native
  /// `ARRAY` keeps its element order and has an element-wise `<`, so all seven operators have an
  /// answer here.
  ///
  /// # Errors
  ///
  /// [`ListCrossingError::Operand`] when `f` refuses an element and [`ListCrossingError::Element`]
  /// when the element filter's own crossing refuses. [`JsonOrdering`](ListCrossingError::JsonOrdering)
  /// is the variant this dialect cannot produce. The error type is the KIND's rather than `f`'s own
  /// so that a caller crossing a [`ListFilter`] writes one match arm whichever dialect answers — the
  /// same arrangement [`BytesCrossingError`](super::super::BytesCrossingError) has for the byte shape
  /// whose substring refusal cannot arise.
  ///
  /// [`ListCrossingError::Operand`]: super::ListCrossingError::Operand
  /// [`ListCrossingError::Element`]: super::ListCrossingError::Element
  ///
  /// `g` crosses the ELEMENT filter, and it is a second function rather than a use of `f` because
  /// the two convert different things: `f` maps one ELEMENT into its storage type, while the `any`
  /// slot holds a whole FILTER whose own operands are the element kind's to convert. A caller
  /// holding ONE converter for both is asking [`try_from_filter_with`](Self::try_from_filter_with),
  /// which composes them; the identity crossing below passes [`TryFromFilter::try_from_filter`] and
  /// needs no closure at all.
  pub fn try_from_filter_with_element<D, VF, E, F, X, G>(
    filter: ListFilter<D, VF>,
    f: F,
    g: G,
  ) -> Result<Self, ListCrossingError<E, X>>
  where
    F: FnMut(D) -> Result<V, E>,
    G: FnOnce(VF) -> Result<C, X>,
  {
    let mut stored = filter.try_map(f).map_err(ListCrossingError::Operand)?;
    let any = cross_element(stored.any.take(), g).map_err(ListCrossingError::Element)?;
    let count = cross_count(stored.count.take()).map_err(ListCrossingError::Cardinality)?;
    Ok(from_stored(stored, any, count))
  }
}

/// The identity crossing for a Postgres sequence column — a `Vec<String>` stored as a `text[]` is
/// the common one.
///
/// # Errors
///
/// As [`try_from_filter_with_element`](SqlListComparison::try_from_filter_with_element).
impl<D, VF, V: TryFrom<D>, C: TryFromFilter<VF>> TryFromFilter<ListFilter<D, VF>>
  for SqlListComparison<V, C, sqlx::Postgres>
{
  type Error = ListCrossingError<V::Error, C::Error>;

  fn try_from_filter(filter: ListFilter<D, VF>) -> Result<Self, Self::Error> {
    Self::try_from_filter_with_element(filter, V::try_from, C::try_from_filter)
  }
}

/// This dialect's own impl, because `V: PgHasArrayType` is a bound only this dialect can carry: an
/// impl that also had to serve SQLite could not ask for it, and would lower a native `ARRAY` column
/// through JSON.
impl<V: PgArrayElement, C: ComplexComparison<sqlx::Postgres>> ComplexComparison<sqlx::Postgres>
  for SqlListComparison<V, C, sqlx::Postgres>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <sqlx::Postgres as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Postgres as Backend>::Builder<'q>, <sqlx::Postgres as Backend>::Error> {
    push_list_slots(self, at, &mut builder);
    push_unnest_any(self.any.as_ref(), at, &mut builder)?;
    push_array_count(self.count.as_ref(), at, &mut builder);
    Ok(builder)
  }
}

/// The set kind's own impl over the same column and under the same bound: what differs between the
/// two is which operators reach the engine, not what the column is.
impl<V: PgArrayElement, C: ComplexComparison<sqlx::Postgres>> ComplexComparison<sqlx::Postgres>
  for SqlSetComparison<V, C, sqlx::Postgres>
{
  #[inline]
  fn conjuncts(&self) -> usize {
    Self::conjuncts(self)
  }

  fn apply<'q>(
    &'q self,
    at: At<'_>,
    mut builder: <sqlx::Postgres as Backend>::Builder<'q>,
  ) -> Result<<sqlx::Postgres as Backend>::Builder<'q>, <sqlx::Postgres as Backend>::Error> {
    push_set_slots(self, at, &mut builder);
    push_unnest_any(self.any.as_ref(), at, &mut builder)?;
    push_array_count(self.count.as_ref(), at, &mut builder);
    Ok(builder)
  }
}

/// The sequence kind's seven slots in the order the FILTER declares them — held beside the impl
/// rather than inside it so the order is one statement rather than an inlined habit.
///
/// It takes no `leaf`, where the JSON dialects' walks do: everything here is a native array
/// operator, so there is no per-dialect leaf to hand in.
fn push_list_slots<V: PgArrayElement, C>(
  comparison: &SqlListComparison<V, C, sqlx::Postgres>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
) {
  // A native array keeps its element order, so whole-collection equality is the engine's own `=`.
  for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
    if let Some(values) = slot {
      push_array_op(out.open(), at, " = ", values, negated);
    }
  }
  // Element-wise and lexicographic, which is what a Postgres array's own comparison operators do.
  for (slot, op) in [
    (&comparison.gt, " > "),
    (&comparison.gte, " >= "),
    (&comparison.lt, " < "),
    (&comparison.lte, " <= "),
  ] {
    if let Some(values) = slot {
      push_array_op(out.open(), at, op, values, false);
    }
  }
  push_membership(comparison.has_element.as_ref(), at, out);
}

/// The set kind's six slots, likewise.
fn push_set_slots<V: PgArrayElement, C>(
  comparison: &SqlSetComparison<V, C, sqlx::Postgres>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
) {
  for (slot, negated) in [(&comparison.eq, false), (&comparison.ne, true)] {
    if let Some(values) = slot {
      push_mutual_containment(out, at, values, negated);
    }
  }
  for (slot, op) in [
    (&comparison.encloses, " @> "),
    (&comparison.enclosed_by, " <@ "),
    (&comparison.overlaps, " && "),
  ] {
    if let Some(values) = slot {
      push_array_op(out.open(), at, op, values, false);
    }
  }
  push_membership(comparison.has_element.as_ref(), at, out);
}

/// The `has_element` slot both walks end with.
///
/// Membership IS containment of the singleton, so it needs no operator of its own — and the
/// singleton is an ARRAY, which is what keeps `@>` meaning containment rather than degrading into a
/// scalar comparison.
fn push_membership<V: PgArrayElement>(
  element: Option<&V>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
) {
  if let Some(element) = element {
    push_array_op(
      out.open(),
      at,
      " @> ",
      core::slice::from_ref(element),
      false,
    );
  }
}

/// `"col" <op> $1`, the operand bound as ONE array however many elements it holds.
fn push_array_op<V: PgArrayElement>(
  qb: &mut sqlx::QueryBuilder<sqlx::Postgres>,
  at: At<'_>,
  op: &str,
  values: &[V],
  negated: bool,
) {
  not_wrapped(qb, negated, |qb| {
    push_column(qb, at);
    qb.push(op);
    qb.push_bind(values);
  });
}

/// The `any` slot both walks end with: `unnest` is a real element scope on this dialect, so the
/// element comparison renders inside it at the one address every scope names its member with.
///
/// The alias list is what supplies that name — `unnest("tags") AS "__ig_element_0__"("value")` names
/// the derived table AND its single column, where a bare alias would leave the column called
/// `unnest`. The table half wears the framework's reserved prefix like every alias here; both halves
/// are bracketed like every other identifier this family emits.
///
/// # The two encodings agree here, and the strategy table is why
///
/// `unnest` hands back a member in the array's own element type, and the element comparison binds
/// through [`Carrier`](crate::comparison::sql::Carrier). [`PgCollectionStorage`]'s array rows are
/// exactly the element types *whose sqlx array type is the array OF the column their carrier row
/// binds into* — its own rule, written for the whole-collection operators — so an element scope over
/// one of them compares a member against a bind of the same column type. The elements where that
/// would not hold are the rows that name an edge table instead.
///
/// Measured on PostgreSQL 14.23: `EXISTS (SELECT 1 FROM unnest("tags") AS "__ig_element_0__"("value")
/// WHERE "value" LIKE 'h%' ESCAPE '\')` admits exactly the rows with a matching element, including
/// where the PARENT carries its own `value` column whose contents would have matched — an
/// unqualified name resolves to the innermost scope.
fn push_unnest_any<C>(
  element: Option<&C>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
) -> Result<(), <sqlx::Postgres as Backend>::Error>
where
  C: ComplexComparison<sqlx::Postgres>,
{
  let Some(element) = element else {
    return Ok(());
  };
  let column = render_column::<sqlx::Postgres>(at);
  push_element_scope(out.open(), element, at, |qb| {
    qb.push("unnest(");
    qb.push(&column);
    qb.push(") AS ");
    qb.push(quote_ident::<sqlx::Postgres>(ELEMENT_ALIAS));
    qb.push("(");
    qb.push(quote_ident::<sqlx::Postgres>(ELEMENT_VALUE));
    qb.push(")");
  })
}

/// The `count` slot both walks end with — `cardinality`, and NOT `array_length`.
///
/// # The empty array is what decides between the two, and it was measured
///
/// PostgreSQL 14.23, over a `text[]` column holding `{hdr,sdr}`, `{}`, `NULL` and `{hdr}`:
///
/// | row | `array_length(tags, 1)` | `cardinality(tags)` |
/// |---|---|---|
/// | `{hdr,sdr}` | 2 | 2 |
/// | `{}` | `NULL` | 0 |
/// | `NULL` | `NULL` | `NULL` |
/// | `{hdr}` | 1 | 1 |
///
/// An empty array has no DIMENSIONS, so `array_length` has no first dimension to report a length for
/// and answers `NULL`. That is not a rendering detail: `count: { eq: 0 }` then admits no row at all
/// where one holds the empty array, and `count: { lt: 2 }` admits the one-element row and skips the
/// empty one — both measured. `cardinality` counts elements rather than reading a dimension and
/// answers `0`, which is the number this operator was asked about.
///
/// Both answer `NULL` for a `NULL` column, and that agreement is the honest one: a column with no
/// collection in it has no cardinality, and every operator here gives a `NULL` column the same
/// three-valued answer.
///
/// The other two strategies need no such choice — SQLite's `json_array_length('[]')` and MySQL's
/// `JSON_LENGTH(CAST('[]' AS JSON))` are both `0`, measured — so this is the one dialect where a
/// cardinality had a wrong spelling available to it.
fn push_array_count(
  count: Option<&SqlCountComparison<i64, sqlx::Postgres>>,
  at: At<'_>,
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
) {
  let Some(count) = count else {
    return;
  };
  let column = render_column::<sqlx::Postgres>(at);
  push_count_slots(count, out, |qb| {
    qb.push("cardinality(");
    qb.push(&column);
    qb.push(")");
  });
}

/// Set equality: containment in both directions, the operand bound once per direction.
///
/// The underlying column is an ordered `ARRAY` and its `=` is available, so this is a choice the
/// engine does not make for us — a set's stored element order is an artefact of insertion, and `=`
/// would answer a question a reordering insert changes the answer to.
fn push_mutual_containment<V: PgArrayElement>(
  out: &mut SqlConjunction<'_, sqlx::Postgres>,
  at: At<'_>,
  values: &[V],
  negated: bool,
) {
  // Bracketed ONCE for the two directions.
  let column = render_column::<sqlx::Postgres>(at);
  not_wrapped(out.open(), negated, |qb| {
    qb.push("( ");
    qb.push(&column);
    qb.push(" @> ");
    qb.push_bind(values);
    qb.push(" AND ");
    qb.push(&column);
    qb.push(" <@ ");
    qb.push_bind(values);
    qb.push(" )");
  });
}