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
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
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
//! The frame, measured against BACKENDS WRITTEN HERE.
//!
//! # The rows under test are the fixture's, and that is the third-party proof as well as the harness
//!
//! [`OrderCapability`] is what a backend this crate does not ship implements, so a test that could
//! only be written against `sqlx::Postgres` or [`Mongo`](crate::Mongo) would be measuring the
//! shipped rows and not the seam. Every combination of the two answers is a unit struct below,
//! joined through nothing but the public trait — which is the same standard `query::mongo`'s own
//! fixture holds.
//!
//! The SHIPPED rows are measured too, at the end, where the two families disagree.

/// The COMPOSITE element's own corpus — the one collection shape that has no array anywhere, so
/// every backend's term is edge-stored and the four rows below answer alike. Its own file because
/// what it measures is a SUBJECT rather than a capability row.
mod composite;

use super::{
  CollectionBoundary, CollectionOrdering, NullPlacement, OrderCapability, OrderPartition,
  ShadowBoundary, ShadowOrdering, TermRepetition, Unpushable, compare_collections, partition,
};
use crate::{FieldName, OrderDirection, OrderTerm, TermName, TermSubject};

/// A backend that takes anything an order can hold, collections included — PostgreSQL's answers.
struct Everything;

impl OrderCapability for Everything {
  const NULLS: NullPlacement = NullPlacement::Reachable;
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Lexicographic;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Bindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// A backend whose ordering is KEYED by the subject and whose collection ordering is its own —
/// MongoDB's `$sort`, on both axes.
struct Keyed;

impl OrderCapability for Keyed {
  const NULLS: NullPlacement = NullPlacement::Reachable;
  const REPEATED_TERMS: TermRepetition = TermRepetition::Unrepresentable;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Divergent;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// A backend that cannot place a missing value — the dialect
/// [`NullOrdering::Inexpressible`](crate::comparison::sql::NullOrdering::Inexpressible) describes
/// and none of the three shipped ones is.
struct Placeless;

impl OrderCapability for Placeless {
  const NULLS: NullPlacement = NullPlacement::Unreachable;
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Lexicographic;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Bindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// A backend that keeps a collection in a column and orders it by SOME OTHER RULE — SQLite's and
/// MySQL's JSON answer, and MongoDB's extreme-element answer, on the one axis they share.
struct OtherRule;

impl OrderCapability for OtherRule {
  const NULLS: NullPlacement = NullPlacement::Reachable;
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  // The collection axis and the BYTES axis are independent, and this fixture is the one that says
  // so: a backend may keep the pin nowhere in a list column and everywhere in a blob.
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// A backend that ORDERS a collection the framework's way and cannot BIND one — the row no shipped
/// backend fills, and the whole reason [`Unpushable::CollectionCursor`] stays in the vocabulary.
///
/// It is the fixture's own answer rather than a shipped one on purpose: the two collection axes are
/// independent, and a frame that could not spell their fourth combination would be a frame reading
/// one row off another.
struct Boundaryless;

impl OrderCapability for Boundaryless {
  const NULLS: NullPlacement = NullPlacement::Reachable;
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Lexicographic;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// A term over a COLLECTION this backend keeps in a column of the row.
fn array(name: &'static str, direction: OrderDirection) -> OrderTerm {
  OrderTerm::array(TermName::new(name), FieldName::new(name), direction)
}

/// A term over a COLLECTION this backend keeps in a table of its own.
fn edge(name: &'static str, direction: OrderDirection) -> OrderTerm {
  OrderTerm::edge(TermName::new(name), FieldName::new(name), direction)
}

/// A term over a `NOT NULL` column of `name`, running `direction`.
fn term(name: &'static str, direction: OrderDirection) -> OrderTerm {
  OrderTerm::new(TermName::new(name), FieldName::new(name), direction)
}

/// The same, over a column that can hold nothing.
fn nullable(name: &'static str, direction: OrderDirection) -> OrderTerm {
  OrderTerm::nullable(TermName::new(name), FieldName::new(name), direction)
}

/// `a ASC, b DESC, id ASC` — a completed order with nothing unusual in it.
fn plain() -> [OrderTerm; 3] {
  [
    term("a", OrderDirection::Asc),
    term("b", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ]
}

/// A backend that takes every answer takes every order, whatever the terms hold.
#[test]
fn an_order_a_backend_can_express_is_whole() {
  let terms = [
    nullable("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];
  let partition = partition::<Everything>(&terms);

  assert_eq!(partition, OrderPartition::Whole(&terms));
  assert!(partition.is_whole());
  assert_eq!(partition.pushable(), &terms);
  assert!(partition.remainder().is_empty());
  assert_eq!(partition.cause(), None);
}

/// The `$sort` axis: a subject named twice is a second entry a LIST holds and a DOCUMENT replaces,
/// so the same order partitions two ways.
#[test]
fn a_repeated_subject_splits_only_where_the_statement_is_keyed() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];

  assert_eq!(
    partition::<Everything>(&terms),
    OrderPartition::Whole(&terms)
  );
  assert_eq!(
    partition::<Keyed>(&terms),
    OrderPartition::Split {
      pushable: &terms[..1],
      remainder: &terms[1..],
      cause: Unpushable::Repetition,
    }
  );
}

/// The null axis: a `NOT NULL` order is whole on a backend that can place nothing at all, and one
/// nullable term is where it stops.
#[test]
fn a_nullable_term_splits_where_the_position_is_unreachable() {
  let plain = plain();
  assert_eq!(
    partition::<Placeless>(&plain),
    OrderPartition::Whole(&plain)
  );

  let terms = [
    term("a", OrderDirection::Asc),
    nullable("b", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];
  assert_eq!(
    partition::<Placeless>(&terms),
    OrderPartition::Split {
      pushable: &terms[..1],
      remainder: &terms[1..],
      cause: Unpushable::NullPosition,
    }
  );
}

/// **The split takes the whole TAIL**, and that is the property a filter would not have: the third
/// term here is one this backend could take, and it is the caller's anyway, because term three only
/// decides where term two tied.
#[test]
fn the_split_takes_every_term_after_the_refused_one() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];
  let split = partition::<Keyed>(&terms);

  assert_eq!(split.remainder().len(), 2);
  assert_eq!(split.remainder()[1], terms[2]);
  assert_eq!(
    partition::<Keyed>(&terms[2..]),
    OrderPartition::Whole(&terms[2..]),
    "the tail is takeable on its own, and is still the caller's"
  );
}

/// A first term this backend refuses leaves an EMPTY prefix, which is a statement with no ordering
/// at all rather than a case anyone has to spot.
#[test]
fn a_refusal_at_the_first_term_leaves_nothing_for_the_statement() {
  let terms = [nullable("a", OrderDirection::Asc)];
  let partition = partition::<Placeless>(&terms);

  assert!(partition.pushable().is_empty());
  assert_eq!(partition.remainder(), &terms);
}

/// An order over NO terms is whole, which is the honest answer: there is nothing a backend failed
/// to take. What refuses an empty order is the party that RENDERS one — see `MongoSortError::Empty`
/// and `SqlOrderError::Empty` — because *an order over nothing has no spelling* is a fact about the
/// statement rather than about a capability.
#[test]
fn an_empty_order_is_whole() {
  assert_eq!(partition::<Keyed>(&[]), OrderPartition::Whole(&[]));
}

/// **The (i) law.** A cursor'd query with a nonempty remainder is refused BY NAME, and the refusal
/// carries the client's own term rather than a column of whichever database answered.
#[test]
fn a_cursord_query_with_a_remainder_is_refused() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("a", OrderDirection::Desc),
  ];
  let refusal = partition::<Keyed>(&terms)
    .paging::<Keyed>()
    .expect_err("this order is not one `$sort` document");

  assert_eq!(refusal.term(), TermName::new("a"));
  assert_eq!(refusal.cause(), Unpushable::Repetition);
  assert_eq!(
    refusal.to_string(),
    "a page's order lives entirely in the statement and `a` cannot be put in one: this backend's \
     ordering holds one entry per subject and this one is named twice"
  );
}

/// The other side of the law: a whole order pages, and what it hands back is the terms the
/// statement carries.
#[test]
fn a_whole_order_pages() {
  let terms = plain();

  assert_eq!(partition::<Keyed>(&terms).paging::<Keyed>(), Ok(&terms[..]));
}

/// One row of the corpus the degrade path is measured on: the value each term reads, and the
/// SEQUENCE the statement returned it in.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Row {
  a: i64,
  b: Option<i64>,
  id: i64,
}

/// The value a row holds at one term — the caller's half of
/// [`apply`](super::OrderPartition::apply), written the way a generated row would write it.
fn value(row: &Row, term: &OrderTerm) -> Option<i64> {
  match term.column().as_ref() {
    "a" => Some(row.a),
    "b" => row.b,
    _ => Some(row.id),
  }
}

/// The ids of `rows`, which is what every degrade assertion below compares.
fn ids(rows: &[Row]) -> Vec<i64> {
  rows.iter().map(|row| row.id).collect()
}

/// **The degrade path.** The statement ordered by `a` alone; the completion applied in memory
/// produces exactly the order that was written.
///
/// The corpus is the statement's own output: `a` ascending, with everything below it in whatever
/// sequence the engine answered in, which is what makes the completion the thing under test rather
/// than the sort.
#[test]
fn the_remainder_applied_in_memory_produces_the_written_order() {
  let terms = plain();
  let partition = OrderPartition::Split {
    pushable: &terms[..1],
    remainder: &terms[1..],
    cause: Unpushable::Repetition,
  };
  let mut rows = vec![
    Row {
      a: 1,
      b: Some(5),
      id: 3,
    },
    Row {
      a: 1,
      b: Some(9),
      id: 1,
    },
    Row {
      a: 1,
      b: Some(5),
      id: 2,
    },
    Row {
      a: 2,
      b: Some(1),
      id: 4,
    },
  ];

  partition.apply(&mut rows, value);

  // `a` ascending is the statement's; inside `a = 1`, `b` descending puts 9 first and the `b = 5`
  // pair is separated by `id` ascending.
  assert_eq!(ids(&rows), [1, 2, 3, 4]);
}

/// **The completion walks the WHOLE order, and a remainder-only sort is what this catches.**
///
/// The remainder here opens with a DESCENDING term over the same column the prefix ordered
/// ascending, which is exactly the shape a repeated subject produces on a keyed backend. Sorting by
/// the remainder alone makes that descending term the primary key — stability preserves the input
/// sequence only among rows the key ties, so every row the statement had already separated moves —
/// and the corpus comes back `[3, 2, 1]` instead of `[2, 1, 3]`.
///
/// It is a real defect and this is where it was caught: the first version of the completion sorted
/// by the remainder alone, and the corpus above passed it by accident.
#[test]
fn a_remainder_that_reopens_the_prefixs_column_does_not_take_over_the_order() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];
  let partition = OrderPartition::Split {
    pushable: &terms[..1],
    remainder: &terms[1..],
    cause: Unpushable::Repetition,
  };
  let mut rows = vec![
    Row {
      a: 1,
      b: None,
      id: 3,
    },
    Row {
      a: 0,
      b: None,
      id: 2,
    },
    Row {
      a: 0,
      b: None,
      id: 1,
    },
  ];

  partition.apply(&mut rows, value);

  assert_eq!(ids(&rows), [1, 2, 3]);
}

/// The completion is STABLE, which is what keeps it a completion: two rows the order cannot
/// separate at all stay in the sequence the statement put them in.
///
/// An unstable sort passes the tests above and fails this one, which is why it is separate.
#[test]
fn the_completion_keeps_the_statements_own_sequence_where_the_remainder_ties() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("b", OrderDirection::Asc),
  ];
  let partition = OrderPartition::Split {
    pushable: &terms[..1],
    remainder: &terms[1..],
    cause: Unpushable::Repetition,
  };
  let mut rows: Vec<Row> = (1..=8)
    .map(|id| Row {
      a: 1,
      b: Some(0),
      id,
    })
    .collect();

  partition.apply(&mut rows, value);

  assert_eq!(ids(&rows), [1, 2, 3, 4, 5, 6, 7, 8]);
}

/// The framework pins a missing value BELOW every value, and in memory that pin is
/// [`Option`]'s own ordering rather than a second rule this layer writes — so it inverts with a
/// descending term exactly as the rendered one does.
#[test]
fn a_missing_value_sorts_below_every_value_and_inverts_with_the_term() {
  let ascending = [nullable("b", OrderDirection::Asc)];
  let descending = [nullable("b", OrderDirection::Desc)];
  let corpus = || {
    vec![
      Row {
        a: 0,
        b: Some(7),
        id: 1,
      },
      Row {
        a: 0,
        b: None,
        id: 2,
      },
      Row {
        a: 0,
        b: Some(3),
        id: 3,
      },
    ]
  };

  let mut rows = corpus();
  OrderPartition::Split {
    pushable: &[],
    remainder: &ascending,
    cause: Unpushable::NullPosition,
  }
  .apply(&mut rows, value);
  assert_eq!(ids(&rows), [2, 3, 1]);

  let mut rows = corpus();
  OrderPartition::Split {
    pushable: &[],
    remainder: &descending,
    cause: Unpushable::NullPosition,
  }
  .apply(&mut rows, value);
  assert_eq!(ids(&rows), [1, 3, 2]);
}

/// A whole partition applies NOTHING, which is what keeps the ordinary path free of the degrade:
/// the statement already answered in the written order and a sort over it would be work for no
/// change.
#[test]
fn a_whole_partition_leaves_the_statements_own_answer_alone() {
  let terms = plain();
  let mut rows = vec![
    Row {
      a: 9,
      b: None,
      id: 1,
    },
    Row {
      a: 1,
      b: None,
      id: 2,
    },
  ];

  OrderPartition::Whole(&terms).apply(&mut rows, value);

  assert_eq!(ids(&rows), [1, 2]);
}

/// **The shipped rows, side by side.** One order, two backends, two verdicts — which is the whole
/// claim of a per-(term × backend) frame, and the assertion that goes red if either row lies.
#[cfg(all(feature = "postgres", feature = "mongo"))]
#[test]
fn a_repeated_subject_is_postgres_ordering_and_not_mongodb_sorting() {
  let terms = [
    term("a", OrderDirection::Asc),
    term("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];

  assert!(partition::<sqlx::Postgres>(&terms).is_whole());
  assert_eq!(
    partition::<crate::Mongo>(&terms).cause(),
    Some(Unpushable::Repetition)
  );
}

/// A nullable term is every shipped backend's to order by, and the three dialects reach that answer
/// through their own [`NullOrder`](crate::NullOrder) row rather than through a second constant.
///
/// It is the row that would go red if a dialect's `NULLS` moved without this frame noticing, which
/// is the whole reason the projection exists instead of a copy.
#[cfg(all(
  feature = "sqlite",
  feature = "postgres",
  feature = "mysql",
  feature = "mongo"
))]
#[test]
fn every_shipped_backend_can_place_a_missing_value() {
  use crate::comparison::sql::NullOrdering;

  let terms = [
    nullable("a", OrderDirection::Desc),
    term("id", OrderDirection::Asc),
  ];

  assert!(partition::<sqlx::Sqlite>(&terms).is_whole());
  assert!(partition::<sqlx::Postgres>(&terms).is_whole());
  assert!(partition::<sqlx::MySql>(&terms).is_whole());
  assert!(partition::<crate::Mongo>(&terms).is_whole());

  assert_eq!(
    NullPlacement::of(NullOrdering::Inexpressible),
    NullPlacement::Unreachable,
    "the projection is what would carry a fourth dialect's refusal into this frame"
  );
}

// ---------------------------------------------------------------------------------------------
// The COLLECTION axis: the pin, the three verdicts, and the two rows of the degrade law.
// ---------------------------------------------------------------------------------------------

/// The pin, over the corpus a LIVE PostgreSQL was asked the same question.
///
/// **This is the test that keeps the pin honest.** The two lists below are the ids
/// `PostgreSQL 14.23` returned for `ORDER BY <array column> ASC, id ASC` over exactly these rows,
/// copied from the server's own answer; the assertion is that
/// [`compare_collections`](super::compare_collections) puts them in the same sequence. A pin that
/// drifted from the engine it claims to match would redden here rather than serve a remainder in one
/// order and a Postgres statement in another.
///
/// The INTEGER corpus is the one that proves the comparison is the ELEMENT's rather than the stored
/// text's: `{10}` comes after `{2}`, where anything ranking a rendered JSON array by its characters
/// puts it before — which is the divergence SQLite's and MySQL's rows are about.
///
/// Mutation: flipping the pin to longer-is-less on a prefix moves `{a}` after `{a,a,a}` and `{1}`
/// after `{1,9}`, and both halves of this go red.
#[test]
fn the_pin_is_what_a_live_postgres_answered() {
  // `SELECT id, tags FROM pin ORDER BY tags COLLATE "C" ASC, id ASC` → 2,9,6,4,5,3,7,1,8
  let mut text: Vec<(i32, Vec<&str>)> = vec![
    (1, vec!["b"]),
    (2, vec![]),
    (3, vec!["a", "b"]),
    (4, vec!["a"]),
    (5, vec!["a", "a", "a"]),
    (6, vec!["B"]),
    (7, vec!["a", "b", "a"]),
    (8, vec!["b", "a"]),
    (9, vec![""]),
  ];
  text.sort_by(|left, right| compare_collections(&left.1, &right.1).then(left.0.cmp(&right.0)));
  assert_eq!(
    text.iter().map(|row| row.0).collect::<Vec<_>>(),
    [2, 9, 6, 4, 5, 3, 7, 1, 8],
    "the empty array least, a prefix below what extends it, and the first differing element deciding"
  );

  // The DESCENDING walk was the exact reverse of the ascending one, which is what lets a backward
  // page read the same order from the far end — the same property the pinned NULL position has.
  let mut backwards = text.clone();
  backwards
    .sort_by(|left, right| compare_collections(&right.1, &left.1).then(left.0.cmp(&right.0)));
  assert_eq!(
    backwards.iter().map(|row| row.0).collect::<Vec<_>>(),
    [8, 1, 7, 3, 5, 4, 6, 9, 2]
  );

  // `SELECT id, ns FROM pinn ORDER BY ns ASC, id ASC` → 4,5,3,6,1,7,2
  let mut numbers: Vec<(i32, Vec<i32>)> = vec![
    (1, vec![2]),
    (2, vec![10]),
    (3, vec![1, 9]),
    (4, vec![]),
    (5, vec![1]),
    (6, vec![1, 9, 0]),
    (7, vec![2, 0]),
  ];
  numbers.sort_by(|left, right| compare_collections(&left.1, &right.1).then(left.0.cmp(&right.0)));
  assert_eq!(
    numbers.iter().map(|row| row.0).collect::<Vec<_>>(),
    [4, 5, 3, 6, 1, 7, 2],
    "`{{10}}` after `{{2}}` is the element's own order and not the stored text's"
  );
}

/// The one PostgreSQL rule that is NOT the pin, recorded as the measurement rather than as silence.
///
/// A NULL ELEMENT sorts ABOVE every value there — `{1,NULL} > {1,2}`, measured on the same server —
/// where [`Ord`] for [`Option`] puts it below, that being the framework's own position for a missing
/// value. The two disagree and neither is wrong; what makes the pin honest anyway is that no
/// declaration can reach the disagreement, and the closure is the COMPILER's rather than a rule
/// written here:
///
/// - the framework's collection words carry no element nullability — an `Option` AROUND a
///   collection declares the collection, and there is no word for one INSIDE it, and
/// - the array strategy is chosen by an element type's `PgCollectionStorage` row, which no
///   `Option<T>` has, so an element that could be `NULL` reaches an edge table where there is no
///   native ordering to disagree with.
///
/// This asserts the disagreement itself, so that an element vocabulary that ever admitted a null
/// arrives as a question rather than as a wrong page.
#[test]
fn a_null_element_is_the_one_postgres_rule_the_pin_does_not_hold() {
  assert_eq!(
    compare_collections([Some(1), None], [Some(1), Some(2)]),
    core::cmp::Ordering::Less,
    "in memory a missing value is BELOW every value, which PostgreSQL reverses inside an array"
  );
}

/// A collection kept in a COLUMN is the backend's to order by exactly where the backend means what
/// the framework means.
///
/// Mutation: answering [`CollectionOrdering::Lexicographic`] for `OtherRule` makes the second half
/// whole, which is the same flip the MongoDB row would be.
#[test]
fn a_column_stored_collection_is_pushable_only_where_the_rule_agrees() {
  let terms = [
    array("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];

  assert_eq!(
    partition::<Everything>(&terms),
    OrderPartition::Whole(&terms)
  );
  assert_eq!(
    partition::<OtherRule>(&terms),
    OrderPartition::Split {
      pushable: &[],
      remainder: &terms,
      cause: Unpushable::CollectionSemantics,
    }
  );
}

/// A collection kept in a TABLE OF ITS OWN is nobody's to order by, and no capability row is asked.
///
/// It is the frame's one verdict that is a fact about the TERM alone: the row being ordered has no
/// such column, so a backend that answered otherwise would be answering about a column it is not
/// being handed. Both fixtures refuse it, and they disagree about everything else.
#[test]
fn an_edge_stored_collection_is_a_remainder_on_every_backend() {
  let terms = [
    term("a", OrderDirection::Asc),
    edge("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];
  let split = OrderPartition::Split {
    pushable: &terms[..1],
    remainder: &terms[1..],
    cause: Unpushable::CollectionTable,
  };

  assert_eq!(partition::<Everything>(&terms), split);
  assert_eq!(partition::<OtherRule>(&terms), split);
  assert_eq!(partition::<Keyed>(&terms), split);
}

/// The degrade law's FIRST row, walked: a cursorless query completes an edge-stored collection's
/// order IN MEMORY, in the pin's meaning.
///
/// The corpus is ordered by `a ASC` in the "statement" and the remainder is `tags ASC` — so the
/// memory sort has the whole answer to sort and the collection is what breaks the ties. What the
/// value type's [`Ord`] spends on the collection arm is
/// [`compare_collections`](super::compare_collections), which is the whole of how the pin reaches
/// this walk: a value that compared some other way would put the rows where no backend does.
///
/// Mutation: flipping the pin to longer-is-less moves `{a}` after `{a, a}` here as well as in the
/// parity test, so the two go red together.
#[test]
fn a_cursorless_query_completes_an_edge_stored_order_in_memory() {
  /// What a row holds at one term: a scalar, or the collection a collection term names.
  #[derive(PartialEq, Eq)]
  enum Value {
    Scalar(i32),
    Collection(Vec<&'static str>),
  }

  impl Ord for Value {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
      match (self, other) {
        (Self::Scalar(left), Self::Scalar(right)) => left.cmp(right),
        (Self::Collection(left), Self::Collection(right)) => compare_collections(left, right),
        // Two terms never share a slot, so the mixed pair is unreachable and ordered arbitrarily
        // rather than panicking: this is a test's value type, not a vocabulary.
        (Self::Scalar(_), Self::Collection(_)) => core::cmp::Ordering::Less,
        (Self::Collection(_), Self::Scalar(_)) => core::cmp::Ordering::Greater,
      }
    }
  }

  impl PartialOrd for Value {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
      Some(self.cmp(other))
    }
  }

  let terms = [
    term("a", OrderDirection::Asc),
    edge("tags", OrderDirection::Asc),
  ];
  let partition = partition::<Everything>(&terms);
  assert_eq!(partition.cause(), Some(Unpushable::CollectionTable));

  // As the statement returned them: ordered by `a` alone, which is the prefix it could carry.
  let mut rows: Vec<(u8, i32, Vec<&'static str>)> = vec![
    (1, 1, vec!["a", "a"]),
    (2, 1, vec![]),
    (3, 1, vec!["a"]),
    (4, 2, vec!["b"]),
    (5, 2, vec!["a"]),
  ];
  partition.apply(&mut rows, |row, term| {
    Some(match term.subject() {
      // A term over a column this deployment's database has not got never reaches a comparator: an
      // order carrying one is refused whole before a row is read.
      TermSubject::Value | TermSubject::Absent(_) => Value::Scalar(row.1),
      TermSubject::Array | TermSubject::Edge | TermSubject::Shadow => {
        Value::Collection(row.2.clone())
      }
    })
  });

  assert_eq!(
    rows.iter().map(|row| row.0).collect::<Vec<_>>(),
    [2, 3, 1, 5, 4],
    "the prefix decides first and the collection breaks its ties, in the pin's order"
  );
}

/// The degrade law's SECOND row: a page over a remainder is refused, naming the frame's own cause.
#[test]
fn a_page_over_an_edge_stored_collection_names_the_table() {
  let terms = [
    edge("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];
  let refusal = partition::<Everything>(&terms)
    .paging::<Everything>()
    .expect_err("a remainder is not pageable");

  assert_eq!(refusal.term(), TermName::new("tags"));
  assert_eq!(refusal.cause(), Unpushable::CollectionTable);
  assert!(refusal.to_string().contains("kept in a table of its own"));
}

/// …and a page over a collection the STATEMENT can carry PAGES, where the backend can bind a
/// boundary.
///
/// A page is two readings of one order, and the two are two capability rows. This term passes both:
/// the statement orders the array element by element, and the keyset binds the whole list as ONE
/// parameter — so the ordered scan and the page are served alike, which is the line the array cursor
/// opened.
///
/// Mutation: answering [`CollectionBoundary::Unbindable`] for `Everything` turns this into the
/// refusal below, and the same mutation on the shipped Postgres row is what production would take.
#[test]
fn a_page_over_a_pushable_collection_resumes_where_the_backend_binds_one() {
  let terms = [
    array("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];
  let partition = partition::<Everything>(&terms);
  assert!(
    partition.is_whole(),
    "the statement carries this order whole"
  );

  assert_eq!(partition.paging::<Everything>(), Ok(&terms[..]));
}

/// …and it is refused where the backend ORDERS one and cannot BIND one, which is the one refusal
/// [`partition`] does not raise and the one no shipped row fills.
///
/// The order is WHOLE — the statement carries it — so nothing about the split refuses this. What
/// does is the second reading, and the sentence names it.
///
/// Mutation: dropping the boundary scan from [`OrderPartition::paging`] makes this `Ok`, and such a
/// backend would page at a boundary its carrier never bound.
#[test]
fn a_page_over_a_pushable_collection_is_refused_where_no_boundary_binds() {
  let terms = [
    array("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];
  let partition = partition::<Boundaryless>(&terms);
  assert!(
    partition.is_whole(),
    "the statement carries this order whole"
  );

  let refusal = partition
    .paging::<Boundaryless>()
    .expect_err("this backend has no boundary to bind");
  assert_eq!(refusal.term(), TermName::new("tags"));
  assert_eq!(refusal.cause(), Unpushable::CollectionCursor);
  assert!(refusal.to_string().contains("cannot bind one"));
}

/// An order with no collection in it pages exactly as it did, which is what keeps the scan above
/// from being a cost the ordinary path pays.
#[test]
fn an_order_of_scalars_still_pages_whole() {
  let terms = plain();
  assert_eq!(
    partition::<Everything>(&terms).paging::<Everything>(),
    Ok(&terms[..])
  );
}

/// The SHIPPED rows, and the one that disagrees.
///
/// PostgreSQL is the only backend whose own ordering over a collection column IS the framework's,
/// which is what makes it the one pushable row. MongoDB is the interesting refusal: it really does
/// keep the collection in a field of the document and still cannot be asked, because `$sort` there
/// means the array's extreme element rather than the array.
///
/// Mutation: answering [`CollectionOrdering::Lexicographic`] for `Mongo` makes the second assertion
/// whole, and `MongoOrder::new` stops refusing the term.
#[cfg(all(
  feature = "sqlite",
  feature = "postgres",
  feature = "mysql",
  feature = "mongo"
))]
#[test]
fn only_postgres_orders_a_collection_the_framework_s_way() {
  let terms = [
    array("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];

  assert!(partition::<sqlx::Postgres>(&terms).is_whole());
  for cause in [
    partition::<sqlx::Sqlite>(&terms).cause(),
    partition::<sqlx::MySql>(&terms).cause(),
    partition::<crate::Mongo>(&terms).cause(),
  ] {
    assert_eq!(cause, Some(Unpushable::CollectionSemantics));
  }

  // …and every one of them refuses the edge-stored form, PostgreSQL included: that verdict is the
  // TERM's, so the one pushable row above is about the storage rather than about the dialect.
  let edged = [
    edge("tags", OrderDirection::Asc),
    term("id", OrderDirection::Asc),
  ];
  for cause in [
    partition::<sqlx::Postgres>(&edged).cause(),
    partition::<sqlx::Sqlite>(&edged).cause(),
    partition::<sqlx::MySql>(&edged).cause(),
    partition::<crate::Mongo>(&edged).cause(),
  ] {
    assert_eq!(cause, Some(Unpushable::CollectionTable));
  }
}