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
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
//! What a backend can express in its OWN ordering statement, and what becomes of a written order it
//! cannot express whole: [`OrderCapability`], [`partition`], and the [`OrderPartition`] it answers
//! with.
//!
//! # Pushability is a fact about a (term, backend) PAIR, and the order type stays neutral
//!
//! An [`OrderTerm`] names a column, a direction and whether that column can hold nothing. None of
//! those is a database fact, and a term that carried one would be a written order a client could
//! only ask of the deployment it was written for. What varies is what a BACKEND can put in its
//! ordering statement, so the verdict is per backend and the type is not — which is why this is a
//! trait with `const` rows rather than a member of the order vocabulary.
//!
//! The rows are `const` for [`BindCeiling`](crate::BindCeiling)'s reason: what the backends differ
//! in is an ANSWER, while what to do with it — take the term, or leave it for the caller — is one
//! rule everywhere. So a backend states the answer and [`partition`] does the work, which is also
//! what makes a backend this crate does not ship join by naming two constants.
//!
//! # The split is a PREFIX and a SUFFIX, never a filter
//!
//! An order is a SEQUENCE: term `n` decides only where term `n - 1` tied. So the moment a backend
//! cannot take term `k`, every term after it is the caller's too — the statement's own answer past
//! `k` is arbitrary, and picking the takeable terms out of the tail would order by a sequence
//! nobody wrote. [`partition`] therefore splits at the FIRST term the backend refuses and hands the
//! rest over whole.
//!
//! # What the remainder may be applied as — the DEGRADE law
//!
//! | the query | the remainder |
//! |---|---|
//! | mints NO cursor, and the whole answer is in hand | the WRITTEN order applied IN MEMORY, over the rows the statement returned — [`OrderPartition::apply`] |
//! | mints a cursor | REFUSED — [`OrderPartition::paging`] |
//!
//! The second row is the law rather than a limitation: **a page's order lives entirely in the
//! statement.** A cursor is a position in an order, and the rows a keyset admits are the rows the
//! statement's own `ORDER BY` — or `$sort` — put after the boundary. An order half in the statement
//! and half in the process would resume against a sequence the statement never produced, and the
//! page would skip or repeat exactly the rows at the boundary, with no error anywhere. That is the
//! failure this whole layer exists to prevent, so it is refused by name.
//!
//! The first row is legal because the memory sort has the WHOLE answer to sort. A statement with a
//! ceiling has already chosen which rows come back, under the prefix's order alone, so a completion
//! applied to those rows completes a set that was picked for a different sequence — which is why
//! the lane that may degrade is the one with no ceiling and no cursor at all.
//!
//! # A render-level refusal is still the backstop
//!
//! [`MongoOrder::new`](crate::query::mongo::MongoOrder::new) refuses an order it cannot render, and
//! goes on doing so. The frame here is what a lane consults BEFORE it renders, to decide between
//! degrading and refusing; the renderer is what catches an order that reached it anyway. It now
//! reads this frame rather than scanning for itself, which is what makes a capability row
//! load-bearing: a row that lied would redden the renderer's own tests.
//!
//! # How DEEP a nested order may reach is per backend and per declaration, not a framework wall
//!
//! A nested ordering term follows references, and how many it may follow is answered by the backend
//! that has to name each hop and by the depth the declaration itself minted — MongoDB spends a join
//! field per hop and refuses past the last one, where the SQL family spends none at all, a
//! correlated subselect being its own scope. The alias knob's `depth` is the pressure valve a
//! deployment turns, so the ceiling is a DECLARED fact about a record in a database rather than a
//! number this layer imposes.
//!
//! # Where the shipped backends put a MISSING value, in one table
//!
//! | backend | its own ordering | how the framework's pin is reached |
//! |---|---|---|
//! | SQLite 3.51.0 | `NULL` first ascending, last descending | already the pin; the term states nothing |
//! | MySQL 8.4.11 | the same | already the pin; there is no clause to state — `NULLS LAST` is `ERROR 1064` |
//! | PostgreSQL 16.14, 17.10 | `NULL` LAST ascending, first descending | the term states `NULLS FIRST` / `NULLS LAST` |
//! | MongoDB | `MinKey < Null < …`, a MISSING field where a `null` is | already the pin, and there is NO KNOB — `$sort` states nothing about nulls in either direction |
//!
//! The divergence is one dialect's default and one backend's missing knob, and neither reaches a
//! client: every row above puts a missing value BELOW every value in the end, which is what lets one
//! cursor page one order whichever deployment answers it. Where SQL states its knob is
//! [`NullOrdering`](crate::comparison::sql::NullOrdering) and
//! [`NullPosition`](crate::comparison::sql::NullPosition); MongoDB has none to state, and its row
//! here says so.
//!
//! The row that is NOT filled by any shipped backend is
//! [`Unreachable`](NullPlacement::Unreachable) — a dialect whose default disagrees AND which has no
//! clause. It would have to reach the pin through a derived leading term (`ORDER BY (a IS NULL), a`),
//! which is an extra column the cursor's tuple does not hold, so the ordering and the comparison
//! would run over two different tuples. That is refused rather than served, and this frame is where
//! the refusal becomes a REMAINDER a cursorless query can still complete.
//!
//! # Where the shipped backends put a COLLECTION, in one more table
//!
//! A collection is orderable, and the framework's meaning for one is PostgreSQL's own:
//! [`compare_collections`] — element by element, shorter-is-less on a prefix. What each backend can
//! do with that meaning is [`CollectionOrdering`], and it is the frame's FIRST row on which two
//! shipped backends genuinely disagree about SEMANTICS rather than about a data structure:
//!
//! | backend | a collection lives | its own ordering | verdict |
//! |---|---|---|---|
//! | PostgreSQL 14.23 | a native `ARRAY` column, or an edge table where `postgres(edge)` says so | element by element, shorter-is-less — MEASURED, below | the array is PUSHABLE; the edge table is a remainder |
//! | SQLite / MySQL | an edge table, always | there is no column to order | a remainder |
//! | MongoDB | a native array in the document | the array's MINIMUM element ascending and its MAXIMUM descending | UNPUSHABLE — the rule is not the pin |
//!
//! ## …and whether a PAGE can resume at one, which is a SECOND row
//!
//! Ordering a collection and BINDING one are two questions, and a frame that read the second off the
//! first would make PostgreSQL's happening to answer both ways into the rule. So
//! [`CollectionBoundary`] is its own capability row, asked by [`OrderPartition::paging`] alone:
//!
//! | backend | orders a collection | binds a boundary | a page over an array-stored term |
//! |---|---|---|---|
//! | PostgreSQL | the framework's way | ONE `E[]` parameter | SERVED |
//! | SQLite / MySQL / MongoDB | by some other rule | no array to bind | already a remainder, one layer out |
//!
//! No shipped row is the fourth combination — orders one, cannot bind one — and
//! [`Unpushable::CollectionCursor`] is what it would be refused by. The member stays for exactly
//! that backend, which is a downstream one.
//!
//! ## …and what the `sortable` word buys the REMAINDER rows, which is a THIRD row
//!
//! A declaration may ask for an ORDER-PRESERVING COMPANION COLUMN beside an edge-stored collection —
//! `#[ingraph(list(scalar), sortable)]` — and the row then carries one binary column holding
//! [`collection_sort_key`](crate::collection_sort_key)'s bytes, whose BYTEWISE order IS
//! [`compare_collections`]. The term's subject becomes
//! [`TermSubject::Shadow`](crate::TermSubject::Shadow) and what the frame asks is
//! [`ShadowOrdering`] — a question about BYTES, where [`CollectionOrdering`] is a question about
//! LISTS:
//!
//! | backend | its ordering over a binary column | verdict |
//! |---|---|---|
//! | SQLite | `memcmp`, shorter-is-less on a prefix — `BLOB` | PUSHABLE |
//! | PostgreSQL | bytewise, shorter-is-less on a prefix — `bytea` | PUSHABLE |
//! | MySQL | bytewise under the binary collation, shorter-is-less — `BLOB` | PUSHABLE |
//! | MongoDB | BSON's own: `BinData` ranks by LENGTH first, then subtype, then bytes | UNPUSHABLE — the rule is not the pin |
//!
//! So the two dialects that had nothing but a remainder now put a collection order in the statement,
//! and PostgreSQL's edge-choosing element types join them. MongoDB's row is honest rather than moot:
//! it keeps every collection in a native array and so mints no shadow term at all, and the row is
//! what a downstream family reads before assuming a blob column would carry the pin.
//!
//! ## …and whether a PAGE can resume at one, which is a FOURTH row
//!
//! The array pair's question again, one storage form over: ordering a companion column and BINDING
//! one are two facts, and [`ShadowBoundary`] is the second. It is asked by
//! [`OrderPartition::paging`] alone:
//!
//! | backend | orders the companion | binds a boundary | a page over a `sortable` term |
//! |---|---|---|---|
//! | SQLite / PostgreSQL / MySQL | bytewise, which IS the pin | one `BLOB`/`bytea` parameter | SERVED |
//! | MongoDB | by `BinData`'s own rule | — | already a remainder, one layer out |
//!
//! No shipped row is the fourth combination — orders one, cannot bind one — and
//! [`Unpushable::ShadowCursor`] is what it would be refused by. The member stays for exactly that
//! backend, which is a downstream one.
//!
//! **What the page needed was not a capability but a COLUMN.** The refusal used to be the
//! FRAMEWORK's: an emitted row projected the collection and not its companion, so there was no
//! boundary value to write into a cursor slot whatever a backend could bind. The page statement now
//! carries the companion under the engine's own sort alias — the same seam an expression term's
//! value rides, [`SqlOrdering::value`](crate::query::sql::SqlOrdering::value) being where it is read
//! back — so the boundary a cursor freezes is the bytes that statement's own `ORDER BY` sorted the
//! row by. The ordered SCAN projects none of it, having no cursor to mint.
//!
//! ## …and TEXT is where a companion and a NATIVE ARRAY order ONE declared column two ways
//!
//! The companion is BYTES: [`collection_sort_key`](crate::collection_sort_key)'s frame is byte
//! order and nothing else, which is why the column holding it is the dialect's BINARY type and not
//! its text one — see [`SORT_KEY`](crate::query::sql::AsyncSchemaDialect::SORT_KEY). A NATIVE ARRAY
//! orders by the ELEMENT's own meaning instead, and for text that meaning is the DATABASE
//! COLLATION, inherited whole rather than pinned here (the section below states the inheritance).
//! Under a non-`C` collation those are two different orders over the same values: measured on
//! `PostgreSQL 14.23` over `text[]`, `{B}` ranks before `{a}` in byte order — the `C` row of the
//! page table below, which is the companion's order — and LAST under `en_US.UTF-8`, which is that
//! same table's second row.
//!
//! **WHICH of the two an emitted `ORDER BY` renders is decided by the STORAGE FORM alone**, and by
//! no knob a deployment turns. A companion exists where the collection is kept in a table of its
//! own AND the declaration wrote `sortable`; a dialect holding the collection in a column of the
//! row orders that column and mints no companion at all. So ONE database renders exactly one of the
//! two for one column, and it takes two STORAGE CHOICES over one declaration to hold both:
//! `postgres(edge)` against PostgreSQL's default, or a record deployed to PostgreSQL and
//! to SQLite.
//!
//! DELIBERATE, and what makes it so is that neither order is available at the other's site. Bytes
//! are the frame the whole SQL family orders the framework's way — the table above IS that fact —
//! while a native array carries the element's own meaning, which is not this pin's to state. So the
//! divergence is NAMED here rather than closed, and what it costs is that ONE CLIENT WORD covers
//! both: a term's identity is the FIELD's whichever storage form answered it, so a written
//! `orderBy` fingerprints alike across the two and no client can tell which of them it received.
//! What the divergence does NOT reach is a PAGE — a cursor at a shadow term is refused outright
//! ([`Unpushable::ShadowCursor`]), so no keyset boundary is ever compared under one of the two
//! orders against a scan the other produced.
//!
//! ## MySQL's JSON-ARRAY comparison was measured as a shortcut, and the uniform mechanism won
//!
//! MySQL is the one shipped dialect with a native ordering over an array-shaped value — its `JSON`
//! type compares two arrays element by element and takes the shorter to be less where it is a prefix
//! — so it was the candidate for a per-dialect road that needed no companion column at all. It is
//! NOT taken, and the reasons are three:
//!
//! - **the ordering is by TYPE before value.** MySQL's JSON comparison ranks
//!   `BLOB < … < BOOLEAN < ARRAY < OBJECT < STRING < INTEGER/DOUBLE < NULL` before it compares two
//!   values at all. A homogeneous array never reaches that rule, but the rule is what the engine
//!   states, and a collection order resting on the elements happening to be one type is a pin
//!   nothing enforces;
//! - **it is a second storage form.** A `JSON` column is not the edge table this dialect already
//!   keeps its collections in, so taking it would mean a collection stored twice, or stored one way
//!   for order and another for containment — which is the arrangement the whole edge/array split
//!   exists to keep down to two;
//! - **it would be one dialect's answer to a question the frame asks of every backend.** The
//!   companion column is bytes, and bytes are what every dialect here already orders the framework's
//!   way. A road for MySQL alone would be a second mechanism to keep in step with the first.
//!
//! Read from the server's documented semantics rather than from a live walk — this repository
//! provisions no MySQL — and recorded here rather than left as a decision nobody wrote down. What
//! IS measured live is the mechanism that was taken: `query::sql::ddl`'s own shadow suite runs the
//! ordering against an in-memory SQLite and holds it against [`compare_collections`].
//!
//! MongoDB's is the disagreement worth naming: `$sort` over an array field does not compare arrays
//! at all, it compares each document's extreme element, so `[9]` sorts after `[1, 99]` ascending
//! where the pin puts it before. Two orders, one client sentence — which is why the row is a refusal
//! that names the rule rather than one that says *unsupported*.
//!
//! ## The PostgreSQL row is a MEASUREMENT, and this is the walk
//!
//! `PostgreSQL 14.23 (Homebrew) on aarch64-apple-darwin25.4.0`, one table of `int[]` and one of
//! `text[]`, `ORDER BY a` ascending:
//!
//! ```text
//! {} < {1} < {1,2} < {1,2,3} < {2}                      -- int[]
//! {} < {B} < {a} < {a,a,a} < {a,b} < {b}                -- text[] COLLATE "C"
//! ```
//!
//! — the empty array least, a prefix below what extends it, and the first differing element
//! deciding: [`Iterator::cmp`]'s own rule, which is what [`compare_collections`] is written as. The
//! descending walk returned the exact reverse, so the pin survives a backward [`Walk`](crate::Walk)
//! the way the `NULL` position does.
//!
//! One PostgreSQL rule is NOT the pin, and it is unreachable rather than reconciled: a NULL ELEMENT
//! sorts ABOVE every value there (`{1,NULL} > {1,2}`, measured), where [`Ord`] for [`Option`] — the
//! framework's own position for a missing value — puts it below. 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 an `Option` inside one), and the array strategy is chosen by
//! an element type's `PgCollectionStorage` row, which no `Option<T>` has. An element that cannot be
//! `NULL` cannot be ordered wrongly.
//!
//! The ELEMENT's own order meaning is inherited whole and is not this pin's to state. Text under a
//! non-`C` collation compares as that collation says, exactly as a scalar text column already does.
//!
//! ## …and the PAGE was measured on both collations, because that inheritance is what a page rides
//!
//! The element's collation is the one thing about a text collection that could have made the two
//! readings of an order disagree: an `ORDER BY` under one rule and a boundary comparison under
//! another skips or repeats exactly the rows at the page boundary, with no error anywhere. It
//! cannot, and the reason is that BOTH readings are the engine's — the keyset binds a `text[]`
//! parameter and PostgreSQL compares it against the column under the column's own collation, which
//! is the collation the ordering resolved too. Rust's [`Ord`] never enters the paging path.
//!
//! Measured rather than argued, on `PostgreSQL 14.23 (Homebrew) on aarch64-apple-darwin25.4.0`, over
//! `text[]` with a corpus where COLLATION AND BYTE ORDER DISAGREE (`{B}` against `{a}`), paged two
//! at a time against the full ordered scan, in both directions and on both walks:
//!
//! | database collation | the ordered scan | the page |
//! |---|---|---|
//! | `C` | `{} {} {B} {a} {a} {a,a,a} {a,b} {b}` — byte order, which IS [`Iterator::cmp`] over [`Ord`] | EXACT, all four |
//! | `en_US.UTF-8` | `{} {} {a} {a} {a,a,a} {a,b} {b} {B}` — `{B}` moves to the END | EXACT, all four |
//!
//! The SEQUENCE rule is identical on both: the empty array least, a prefix below what extends it,
//! the first differing element deciding, and the descending walk the exact reverse. What moved is
//! the ELEMENT comparison, which is the inheritance above and not this pin.
//!
//! Two more probes on the same corpus: a boundary at the EMPTY array serves every row with any
//! element, and two rows holding an equal list are separated by the key tail alone.
//!
//! What this does NOT make safe is the IN-MEMORY completion. [`OrderPartition::apply`] compares with
//! the caller's own [`Ord`], so a remainder over a text collection completes in byte order whatever
//! the server's collation is — the scalar text situation exactly, and unreachable from a page, which
//! refuses a remainder outright.

use core::cmp::Ordering;

use crate::{OrderTerm, TermName, TermSubject};

/// Whether the framework's pinned position for a MISSING value is reachable in a backend's ordering
/// statement.
///
/// The framework puts nothing BELOW every value — see
/// [`pinned_nulls`](crate::comparison::sql::pinned_nulls), which is where the pin is stated and why
/// it is a total order on the domain rather than a per-direction convention.
///
/// Two members where the SQL family's [`NullOrdering`](crate::comparison::sql::NullOrdering) has
/// three, and the missing one is a RENDERING distinction: whether a dialect reaches the pin by its
/// own default or by stating a clause decides what the term looks like and not whether the term can
/// be taken. What a partition asks is only the second question.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum NullPlacement {
  /// The backend's ordering statement puts a missing value where the framework pins it — by its own
  /// default, or by a position stated on the term.
  Reachable,
  /// It can do neither, so a term whose column can hold nothing is not this backend's to order by.
  Unreachable,
}

impl NullPlacement {
  /// The placement a SQL dialect's [`NullOrdering`](crate::comparison::sql::NullOrdering) answer
  /// amounts to.
  ///
  /// The projection exists so that a dialect states the fact ONCE, at
  /// [`NullOrder::NULLS`](crate::comparison::sql::NullOrder::NULLS), where the rendering already
  /// reads it. A second constant beside it would be one fact with two homes and exactly one place
  /// to be stated wrongly.
  #[cfg(feature = "sqlx")]
  #[inline]
  #[must_use]
  pub const fn of(ordering: crate::comparison::sql::NullOrdering) -> Self {
    use crate::comparison::sql::NullOrdering;

    match ordering {
      NullOrdering::Implicit | NullOrdering::Explicit => Self::Reachable,
      NullOrdering::Inexpressible => Self::Unreachable,
    }
  }
}

/// Whether a backend's ordering statement can carry TWO terms over one subject.
///
/// It is the first axis on which the two shipped families genuinely disagree, and the disagreement
/// is the DATA STRUCTURE rather than the engine: an `ORDER BY` is a LIST, so `"a" ASC, "a" DESC` is
/// a second entry SQL simply never reaches, while a `$sort` is a DOCUMENT whose keys are unique, so
/// `{a: 1, a: -1}` holds one of the two and the other is gone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TermRepetition {
  /// A repeated subject is another entry in the list, and the later one changes nothing.
  Admitted,
  /// The statement is KEYED by the subject, so a second term over one subject would replace the
  /// first — which is an order nobody wrote, arriving with no error.
  Unrepresentable,
}

/// What a backend's own ordering over a COLLECTION column MEANS, against the one meaning this
/// framework has.
///
/// The framework's meaning is [`compare_collections`], which is PostgreSQL's native array ordering:
/// element by element, shorter-is-less on a prefix. A backend either orders a collection column that
/// way or it does not, and the second answer is a REFUSAL rather than an approximation — a statement
/// that sorted by some other rule would answer a different question under the client's own term.
///
/// # Two members, and the one that is missing is *no collection column at all*
///
/// A backend with no array type keeps a collection in a table of its own, and a term over one is
/// refused for a reason that has nothing to do with this row: there is no column of the row to
/// order by, whatever this backend would have meant by one. That is
/// [`TermSubject::Edge`](crate::TermSubject::Edge), a fact about the TERM, and a backend answers
/// here only about the column form it may actually be handed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CollectionOrdering {
  /// The backend's ordering over a collection column IS the framework's — see
  /// [`compare_collections`].
  Lexicographic,
  /// It orders one by some other rule, so a collection is not this backend's to put in an ordering
  /// statement at all.
  Divergent,
}

/// What a backend's own ordering over a BINARY column means — the question a `sortable`
/// collection's COMPANION COLUMN asks, and the one that decides whether the companion carries the
/// pin anywhere at all.
///
/// The companion holds [`collection_sort_key`](crate::collection_sort_key)'s bytes, whose BYTEWISE
/// order is [`compare_collections`](compare_collections). So a backend that compares a binary column
/// byte by byte, shorter-is-less on a prefix, orders the collection the framework's way by ordering
/// the blob; a backend that compares one some other way carries the pin nowhere, and its `sortable`
/// collections stay the remainder they were.
///
/// # It is a SECOND row beside [`CollectionOrdering`] rather than a reading of it
///
/// The two answer about two different columns. [`CollectionOrdering`] is about a NATIVE ARRAY, whose
/// ordering is the backend's own opinion about lists; this is about a BLOB, whose ordering is the
/// backend's own opinion about bytes. PostgreSQL happens to answer both the framework's way and
/// MongoDB neither, and folding them would make those coincidences the rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShadowOrdering {
  /// The backend orders a binary column BYTEWISE, shorter-is-less on a prefix — so the companion
  /// column's order IS [`compare_collections`].
  Bytewise,
  /// It orders one by some other rule, so a companion column would sort the rows somewhere the
  /// framework does not mean.
  Divergent,
}

/// Whether a backend can BIND a whole collection as ONE boundary value — the second reading of a
/// collection order, which the first does not imply.
///
/// [`CollectionOrdering`] answers what the backend's `ORDER BY` over a collection column MEANS. This
/// answers what its keyset predicate can compare against, and the two are independent facts about
/// one column: a page is two readings of one order — the sequence the rows come back in, and the
/// boundary it resumes at — so a backend that orders a collection the framework's way and cannot
/// bind one still has no page to serve.
///
/// # Why it is not read off the ORDERING row
///
/// A capability row is a promise, and a promise that folded two answers into one would be a backend
/// unable to say the true thing about itself. PostgreSQL happens to answer both ways — a native
/// array orders lexicographically AND binds as one `E[]` parameter — and reading the second off the
/// first would make that coincidence the rule, so a backend whose statement orders collections but
/// whose carrier cannot bind one would silently page at a boundary it never bound.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CollectionBoundary {
  /// A whole collection crosses as ONE bound value, so a page can resume at a collection term.
  ///
  /// PostgreSQL's row: the boundary list is one array parameter, never an element expansion — see
  /// [`Carrier`](crate::Carrier)'s own table, where the array rows are.
  Bindable,
  /// It cannot, so a collection term is refused at [`OrderPartition::paging`] however well the
  /// statement orders one.
  Unbindable,
}

/// Whether a backend can BIND a COMPANION COLUMN's bytes as a boundary value — the second reading of
/// a `sortable` collection's order, which the first does not imply.
///
/// [`ShadowOrdering`] answers what the backend's `ORDER BY` over the companion MEANS. This answers
/// what its keyset predicate can compare against, and they are two facts about one column for
/// [`CollectionBoundary`]'s reason: a page is two readings of one order — the sequence the rows come
/// back in, and the boundary it resumes at — so a backend that orders a blob bytewise and cannot bind
/// one still has no page to serve.
///
/// # It is a FOURTH row rather than the array row read twice
///
/// The two boundaries are two VALUES. An array boundary is a whole list, which a dialect binds as one
/// array parameter or not at all; a companion boundary is one opaque blob, which every dialect in
/// this crate binds and which needs no array type anywhere. Reading either off the other would make
/// PostgreSQL's happening to do both — and SQLite's and MySQL's happening to do exactly one — the
/// rule.
///
/// # What CLOSED to make this row reachable
///
/// It used to be that no backend could resume at a companion, and the cause was the FRAMEWORK's: an
/// emitted row projected the collection and not its companion, so there was no boundary value to
/// write into a slot whatever the backend could bind. The page statement now projects the companion
/// under the engine's own sort alias and the row reads it back off the driver's row — see
/// [`SqlOrdering::value`](crate::query::sql::SqlOrdering::value) — so what is left is a question
/// about a BACKEND, and this is the row that asks it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShadowBoundary {
  /// A companion column's bytes cross as one bound value, so a page can resume at a `sortable`
  /// collection's term.
  ///
  /// Every SQL dialect this crate ships: a sort key is a `BLOB`/`bytea` and
  /// [`Carrier`](crate::Carrier) has a byte-string row for all three.
  Bindable,
  /// It cannot, so a companion term is refused at [`OrderPartition::paging`] however well the
  /// statement orders one.
  Unbindable,
}

/// Why one term of a written order is not this backend's to put in its ordering statement — or, for
/// the last member, not this backend's to RESUME a page at.
///
/// One member per capability row plus one per fact about the term itself, so a partition can say
/// WHICH answer refused rather than only that one did — which is what makes a row that lies a red
/// test rather than a page that quietly sorts in the wrong place.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Unpushable {
  /// THIS DEPLOYMENT's database has no column for the term at all — the declaration narrowed it out
  /// of this dialect — [`TermSubject::Absent`](crate::TermSubject::Absent).
  ///
  /// It is the one member no capability row decides and the one member no lane may DEGRADE. Every
  /// other cause says the value is somewhere the ordering statement cannot reach, which a scan may
  /// complete in memory; this one says the value is not here at all — a raise supplies the fill the
  /// declaration named, one constant for every row — so completing the order in memory would answer
  /// a question nobody asked. Both order constructors turn it into a named error naming the column
  /// and the dialect: see [`ColumnNotStored`](super::ColumnNotStored).
  NotStored,
  /// The term's column can hold nothing and this backend can put that nothing neither where the
  /// framework pins it nor anywhere it could state — [`NullPlacement::Unreachable`].
  NullPosition,
  /// An earlier term already names this term's subject, and this backend's ordering statement holds
  /// one entry per subject — [`TermRepetition::Unrepresentable`].
  Repetition,
  /// The term names a COLLECTION this database keeps in a table of its own, so the row being
  /// ordered has no column for it — [`TermSubject::Edge`](crate::TermSubject::Edge).
  ///
  /// It is the one member no capability row decides: an edge-stored collection is refused by every
  /// backend, this one included, and a backend that grew an opinion about it would be answering
  /// about a column it is not being handed.
  CollectionTable,
  /// The term names a COLLECTION in a column of the row, and this backend does not order one the
  /// way the framework means — [`CollectionOrdering::Divergent`].
  CollectionSemantics,
  /// The term names a COLLECTION this backend's statement orders and its keyset cannot bind —
  /// [`CollectionBoundary::Unbindable`].
  ///
  /// # NO SHIPPED ROW RAISES THIS TODAY
  ///
  /// It used to be every collection's refusal, on a sentence that read *a cursor's slot is one
  /// stored value and a collection is not*. The half of that which was true is about the BACKEND
  /// rather than about collections: PostgreSQL binds a whole list as one array parameter and writes
  /// it into one slot whose bytes carry their own inner framing, so a page over an array-stored
  /// collection resumes exactly like any other term. The three backends that cannot bind one keep a
  /// collection in an edge table anyway, so their terms are refused one layer out, under
  /// [`CollectionTable`](Self::CollectionTable), for a reason that needs no capability row.
  ///
  /// What is left is the honest gap between the two readings, and the member stays for it: a backend
  /// whose statement orders collections the framework's way but whose carrier cannot bind one
  /// refuses HERE. Deleting it would leave that backend with no sentence to be refused by, and a
  /// page resuming at a boundary nothing bound.
  ///
  /// # It is raised by [`OrderPartition::paging`] alone, and that is the whole of the asymmetry
  ///
  /// Every other member says the STATEMENT could not carry the term, so an order carrying one is
  /// split and a cursorless query completes it in memory. This one says the statement could and the
  /// RESUME could not — the degrade law's two rows meeting a term that passes the first and fails
  /// the second.
  CollectionCursor,
  /// The term names a COLLECTION mirrored into an order-preserving companion column, and this
  /// backend does not order a binary column bytewise — [`ShadowOrdering::Divergent`].
  ///
  /// NO SHIPPED SQL DIALECT RAISES IT: all three compare a `BLOB`/`bytea` byte by byte, which is the
  /// whole reason a companion column is the mechanism at all. What the member is for is the backend
  /// that does not — MongoDB's own row says so — and a downstream family whose binary ordering ranks
  /// by length or by encoding is refused here rather than sorting rows somewhere nobody meant.
  CollectionShadow,
  /// The term names a COLLECTION mirrored into a companion column this backend's statement CAN
  /// order by and whose bytes its keyset cannot bind — [`ShadowBoundary::Unbindable`].
  ///
  /// # NO SHIPPED ROW RAISES THIS TODAY
  ///
  /// It used to be every companion term's refusal, and the cause was the FRAMEWORK's rather than a
  /// backend's: an emitted row projected the COLLECTION and not its companion, so there was no
  /// boundary value to write into a slot whatever the backend could bind. What was true in that is
  /// still true — a boundary nothing projected is a page resuming where the ordering never stopped —
  /// and what closed it is one column on the page statement. The companion rides the SELECT list
  /// under the engine's own sort alias, exactly as an expression term's value does, and the row
  /// reads it back off the driver's row; see
  /// [`SqlOrdering::value`](crate::query::sql::SqlOrdering::value), where the boundary is frozen.
  ///
  /// What is left is the honest gap between the two readings, and the member stays for it: a backend
  /// whose statement orders a binary column bytewise but whose carrier cannot bind one refuses HERE.
  /// All three shipped SQL dialects bind a byte string, and MongoDB mints no companion at all — its
  /// collections are native arrays with no edge table to mirror — so the row that would raise it is
  /// a downstream one, and deleting the member would leave that backend with no sentence to be
  /// refused by.
  ///
  /// # It is raised by [`OrderPartition::paging`] alone, which is the asymmetry
  /// [`CollectionCursor`](Self::CollectionCursor) already carries
  ///
  /// The statement could take the term and the RESUME could not. The ORDERED SCAN is unaffected on
  /// every dialect, and that is the `sortable` word's own deliverable — the order lives in the
  /// statement, where before it was a remainder.
  ShadowCursor,
}

impl core::fmt::Display for Unpushable {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::NotStored => f.write_str(
        "this deployment's database has no column for the term: the declaration narrowed it out of \
         this dialect and stores it in the record's others",
      ),
      Self::NullPosition => {
        f.write_str("this backend cannot put NULL below every value in an ordering")
      }
      Self::Repetition => f.write_str(
        "this backend's ordering holds one entry per subject and this one is named twice",
      ),
      Self::CollectionTable => f.write_str(
        "this collection is kept in a table of its own, so the row being ordered has no column for \
         it",
      ),
      Self::CollectionSemantics => f.write_str(
        "this backend does not order a collection element by element, so ordering by one would \
         answer a different question",
      ),
      Self::CollectionCursor => f.write_str(
        "this backend orders a collection but cannot bind one, so a page cannot resume at this term",
      ),
      Self::CollectionShadow => f.write_str(
        "this backend does not order a binary column bytewise, so an order-preserving companion \
         column would not carry this collection's order",
      ),
      Self::ShadowCursor => f.write_str(
        "this backend orders a collection's companion column but cannot bind its bytes, so a page \
         cannot resume at this term",
      ),
    }
  }
}

/// Two collections in the framework's ONE order: element by element, and shorter-is-less where one
/// is a prefix of the other.
///
/// **This is the pin.** It is PostgreSQL's native array ordering — `ORDER BY <array column>` is
/// legal there and means exactly this — which is what makes it the one meaning a remainder can be
/// completed with in memory and a PostgreSQL statement can be pushed with, without the two
/// disagreeing. The measurement is in this module's own note, taken against a live server.
///
/// The ELEMENT's order is its own [`Ord`] and is not restated here: a collection of a type orders
/// however a column of that type already orders, which is what *element-wise* means and what keeps
/// this from being a second opinion about text, about numbers, or about anything else.
///
/// # It takes iterators, because a caller's two collections need not be one container
///
/// A row holds a `Vec`, a filter operand arrives as a `Box<[T]>`, and a comparator written for
/// [`OrderPartition::apply`] may be handed either — so the pin is stated over what both are, rather
/// than over one of them with conversions at every call site.
///
/// # Examples
///
/// The three rules, in the order the PostgreSQL walk showed them:
///
/// ```
/// use core::cmp::Ordering;
///
/// use ingraph::query::compare_collections;
///
/// // the empty collection is least
/// assert_eq!(compare_collections::<[i32; 0], _>([], [1]), Ordering::Less);
/// // a prefix is below what extends it
/// assert_eq!(compare_collections([1, 2], [1, 2, 3]), Ordering::Less);
/// // and the first differing element decides, whatever the lengths are
/// assert_eq!(compare_collections([2], [1, 9]), Ordering::Greater);
/// ```
pub fn compare_collections<L, R>(left: L, right: R) -> Ordering
where
  L: IntoIterator,
  R: IntoIterator<Item = L::Item>,
  L::Item: Ord,
{
  left.into_iter().cmp(right)
}

/// What a backend can express in its own ORDERING statement.
///
/// # It is implemented by BACKENDS, and this crate ships four rows
///
/// The three SQL dialects and [`Mongo`](crate::Mongo). A backend this crate does not ship joins by
/// naming two constants, which is the whole of what the frame asks of one — the same standing
/// [`QuoteIdent`](crate::QuoteIdent), [`BindCeiling`](crate::BindCeiling) and
/// [`NullOrder`](crate::NullOrder) have, one layer out from any of them.
///
/// # There is no default, and there must not be
///
/// A row that could be left out would be a backend whose ordering was assumed to take anything, and
/// what an assumption buys here is a page that sorts by a sequence the statement did not produce.
/// The full-set law this crate follows says the same thing from the other side: a backend that says
/// nothing about its ordering is a backend nobody can ask.
pub trait OrderCapability {
  /// Where this backend can put a missing value in an ordering.
  const NULLS: NullPlacement;

  /// Whether this backend's ordering can carry two terms over one subject.
  const REPEATED_TERMS: TermRepetition;

  /// What this backend's ordering over a COLLECTION column means, against the framework's one
  /// meaning.
  ///
  /// A backend that keeps every collection in a table of its own still answers, and answers about
  /// the column form it does not have — [`Divergent`](CollectionOrdering::Divergent) being the
  /// honest word for *if you handed me one I would not order it your way*. What refuses ITS
  /// collections is the term's own subject, one layer out from this row.
  const COLLECTIONS: CollectionOrdering;

  /// Whether this backend can BIND a whole collection as one boundary value.
  ///
  /// The second reading of a collection order, and a row of its own because the first does not imply
  /// it — see [`CollectionBoundary`]. A backend answers here even where
  /// [`COLLECTIONS`](Self::COLLECTIONS) is [`Divergent`](CollectionOrdering::Divergent) and the
  /// question is therefore moot, for the reason that row answers about a column form it has not got:
  /// a full set of answers is what makes a capability frame readable, and a row left out would be an
  /// assumption with a page behind it.
  const COLLECTION_BOUNDARY: CollectionBoundary;

  /// What this backend's ordering over a BINARY column means — the question a `sortable`
  /// collection's companion column asks.
  ///
  /// A backend that keeps no collection in an edge table answers anyway, for the reason
  /// [`COLLECTIONS`](Self::COLLECTIONS) answers about a column form it has not got: a full set is
  /// what makes the frame readable, and the row that is never asked today is the row a downstream
  /// storage choice makes reachable tomorrow.
  const SHADOWS: ShadowOrdering;

  /// Whether this backend can BIND a companion column's bytes as one boundary value.
  ///
  /// The second reading of a `sortable` collection's order, and a row of its own because the first
  /// does not imply it — see [`ShadowBoundary`], and [`COLLECTION_BOUNDARY`](Self::COLLECTION_BOUNDARY)
  /// one storage form over. A backend answers here even where [`SHADOWS`](Self::SHADOWS) is
  /// [`Divergent`](ShadowOrdering::Divergent) and the question is therefore moot, for the reason
  /// every row in this frame is answered: a full set is what makes a capability frame readable, and
  /// a row left out would be an assumption with a page behind it.
  const SHADOW_BOUNDARY: ShadowBoundary;
}

/// A written order as one backend takes it: the prefix its statement carries, and whatever is left.
///
/// # ONE enum rather than two slices and a reason beside them
///
/// The cause exists exactly when the remainder does, so two fields would be two states for one
/// fact and one of them could be set without the other. Here the split IS the thing that has a
/// cause, and a whole order has no room to carry one.
///
/// It borrows the terms it was given and copies nothing: a partition is two windows onto one slice,
/// so the value is the width of what it points at.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[must_use = "a partition decides where the order is applied, and deciding nothing applies none of it"]
pub enum OrderPartition<'a> {
  /// Every term is the statement's.
  Whole(&'a [OrderTerm]),
  /// The statement carries `pushable` and the caller is left `remainder`, because its first term is
  /// one this backend cannot take.
  Split {
    /// The prefix the statement orders by, which may be empty where the very first term is refused.
    pushable: &'a [OrderTerm],
    /// The terms from the refused one onward, in the sequence they run.
    remainder: &'a [OrderTerm],
    /// Why the first of them was refused.
    cause: Unpushable,
  },
}

impl<'a> OrderPartition<'a> {
  /// The terms the statement orders by.
  #[inline]
  #[must_use]
  pub const fn pushable(&self) -> &'a [OrderTerm] {
    match self {
      Self::Whole(terms) => terms,
      Self::Split { pushable, .. } => pushable,
    }
  }

  /// The terms it does not, in the sequence they run.
  #[inline]
  #[must_use]
  pub const fn remainder(&self) -> &'a [OrderTerm] {
    match self {
      Self::Whole(_) => &[],
      Self::Split { remainder, .. } => remainder,
    }
  }

  /// Why the remainder is a remainder, or [`None`] where there is none.
  #[inline]
  #[must_use]
  pub const fn cause(&self) -> Option<Unpushable> {
    match self {
      Self::Whole(_) => None,
      Self::Split { cause, .. } => Some(*cause),
    }
  }

  /// Whether the statement carries the whole order.
  #[inline]
  #[must_use]
  pub const fn is_whole(&self) -> bool {
    matches!(self, Self::Whole(_))
  }

  /// The terms a CURSOR'D query's statement must carry — the whole order — or why this backend
  /// cannot page it.
  ///
  /// This is the degrade law's second row, and it is a refusal rather than a fallback for the
  /// reason the module note gives: an order half in the statement and half in the process resumes
  /// against a sequence the statement never produced.
  ///
  /// # A COLLECTION is asked a SECOND question here, and `B` is why this names a backend
  ///
  /// A page is TWO readings of one order — the ordering the rows come back in, and the boundary it
  /// resumes at — and the two are separate capability rows. [`OrderCapability::COLLECTIONS`] and
  /// [`OrderCapability::SHADOWS`] answer the first, per storage form; [`OrderCapability::COLLECTION_BOUNDARY`]
  /// and [`OrderCapability::SHADOW_BOUNDARY`] answer the second. A term the partition left in the
  /// pushable prefix has passed its ordering row and is refused here only where the backend cannot
  /// bind what it would resume at — under [`Unpushable::CollectionCursor`] for a whole list and
  /// [`Unpushable::ShadowCursor`] for a companion's bytes, the only two members this method raises
  /// and [`partition`] does not.
  ///
  /// **No shipped backend raises either.** PostgreSQL binds a boundary list as one array parameter;
  /// all three SQL dialects bind a byte string, which is what a companion boundary is; and MongoDB
  /// keeps every collection in a native array, so it mints no companion at all and its list terms
  /// are already the partition's remainder under [`Unpushable::CollectionSemantics`].
  ///
  /// # ONE walk over the prefix, not one per row
  ///
  /// The two rows refuse two different terms, so a scan per row would name whichever of them was
  /// asked first rather than whichever term came first — and what [`PagingOrderError`] promises is
  /// *the first term that did not fit*. One walk asking both questions of each term keeps that
  /// promise, which is also [`partition`]'s own shape one question over.
  ///
  /// `B` is repeated from [`partition`] rather than carried in the value, and that is the honest
  /// shape: a partition is two windows onto one slice with a cause beside them, and a capability
  /// folded into it would be a backend's answer travelling as data — free to be read against another
  /// backend, which is exactly the mistake this frame exists to make unspellable.
  ///
  /// The prefix is what is scanned rather than the whole order, because a term in the REMAINDER has
  /// already refused the page for a reason the statement itself gave, and that is the narrower
  /// sentence.
  ///
  /// # Errors
  ///
  /// [`PagingOrderError`], naming the first term the page could not take and what refused it.
  pub fn paging<B: OrderCapability + ?Sized>(&self) -> Result<&'a [OrderTerm], PagingOrderError> {
    if let Self::Split {
      remainder, cause, ..
    } = self
    {
      return Err(PagingOrderError {
        // Non-empty by construction: `partition` splits AT the refused term, so it is this slice's
        // first element.
        term: remainder
          .first()
          .expect("a split names the term that caused it")
          .identity(),
        cause: *cause,
      });
    }
    match self
      .pushable()
      .iter()
      .find_map(|term| Some((term, unresumable::<B>(term)?)))
    {
      Some((term, cause)) => Err(PagingOrderError {
        term: term.identity(),
        cause,
      }),
      None => Ok(self.pushable()),
    }
  }

  /// Put the rows the statement returned in the WRITTEN order, IN MEMORY — the degrade law's first
  /// row.
  ///
  /// `value` is what the row holds at one term, and it is the caller's because a value is the ROW's
  /// vocabulary: this layer holds terms and no way to read one off anything.
  ///
  /// A WHOLE partition does nothing at all, which is what keeps the ordinary path free of this: the
  /// statement already answered in the written order and a sort over it would be work for no change.
  ///
  /// # It walks the WHOLE order and not only the remainder, and that is measured rather than tidy
  ///
  /// A stable sort by the remainder alone makes the remainder's FIRST TERM the primary key.
  /// Stability preserves the input sequence only among rows the sort key TIES, so every row the
  /// statement had already separated is free to move — which is not a completion, it is a different
  /// order. The comparator therefore starts at the pushable prefix, which the statement has already
  /// ordered by and which therefore decides nothing new, and reaches the remainder exactly where
  /// that prefix ties.
  ///
  /// Measured, on the corpus beside this module and again on the MongoDB package's own: a
  /// `title ASC` prefix with a `title DESC, id ASC` remainder returns `[beta, alpha, alpha]` under
  /// the remainder alone and `[alpha, alpha, beta]` under the whole order. The first is what a page
  /// of this shape would have served, without an error anywhere.
  ///
  /// # A COLLECTION term's value compares by [`compare_collections`], and nothing here can enforce it
  ///
  /// `V` is the caller's, so the pin reaches this walk through the caller's own [`Ord`]: a value
  /// type whose collection arm compares by [`compare_collections`] completes a remainder in the one
  /// meaning a PostgreSQL statement would have pushed, and one that compares some other way puts the
  /// rows somewhere no backend does. The function is public for that reason — it is what such an arm
  /// is written as, stated once so a lane and a dialect cannot each have their own idea.
  ///
  /// [`Ord`] for [`Vec`] and for a slice already IS this rule, so a value type that simply holds the
  /// collection is right by construction; what the function buys is the two collections not having
  /// to be one container, and a name for the rule that a test can be pinned to.
  ///
  /// # The framework's pinned NULL position is [`Option`]'s own ordering
  ///
  /// `None` sorts below every `Some` in [`core`]'s [`Ord`] for [`Option`], which is exactly where
  /// this framework pins a missing value. So the pin needs no code here and cannot drift from the
  /// one the statement renders — and a value type that ordered the two the other way could not
  /// implement [`Ord`] at all.
  ///
  /// # There is no [`Walk`](crate::Walk), because a degraded order is never walked backwards
  ///
  /// A backward walk exists to page, and a page with a remainder is refused at
  /// [`paging`](Self::paging). So the terms are applied AS WRITTEN, and the one lane that may reach
  /// here is the ordered scan.
  pub fn apply<T, V, F>(&self, rows: &mut [T], mut value: F)
  where
    V: Ord,
    F: FnMut(&T, &OrderTerm) -> Option<V>,
  {
    let Self::Split {
      pushable,
      remainder,
      ..
    } = self
    else {
      return;
    };
    rows.sort_by(|left, right| {
      for term in pushable.iter().chain(*remainder) {
        let ordering = value(left, term).cmp(&value(right, term));
        let ordering = if term.direction().is_descending() {
          ordering.reverse()
        } else {
          ordering
        };
        if ordering != Ordering::Equal {
          return ordering;
        }
      }
      Ordering::Equal
    });
  }
}

/// `terms` split into what `B`'s ordering statement carries and what it does not.
///
/// # The checks run in the order they are written, and the order is the cause's
///
/// The SUBJECT and nullability are facts about the TERM alone, while a repetition is a fact about
/// the term and everything before it — so the first two are asked first and a term refused for
/// several is reported under the one that needs no context. Which cause is named changes no verdict;
/// it changes what a reader is told, and the narrower sentence is the useful one.
///
/// The subject leads the two, and nothing has to be decided about the pair: a collection has no
/// NULL state, so no term can be refused on both.
///
/// # The repetition scan is quadratic, over the columns a client wrote
///
/// [`MongoOrder::new`](crate::query::mongo::MongoOrder::new)'s own reason, and the same bound: an
/// order is as long as the columns a record declares, so a scan is what this is rather than a set
/// built per query on a path that renders one statement.
pub fn partition<B: OrderCapability + ?Sized>(terms: &[OrderTerm]) -> OrderPartition<'_> {
  for (level, term) in terms.iter().enumerate() {
    let Some(cause) = refused::<B>(&terms[..level], term) else {
      continue;
    };
    let (pushable, remainder) = terms.split_at(level);
    return OrderPartition::Split {
      pushable,
      remainder,
      cause,
    };
  }
  OrderPartition::Whole(terms)
}

/// Why `B` cannot RESUME a page at `term`, or [`None`] where it can.
///
/// [`refused`]'s twin one question over: that one asks what an ordering STATEMENT can carry and this
/// one what a KEYSET can bind, and the two are separate rows for the reason [`CollectionBoundary`]
/// gives. Both questions are asked of every term, so [`OrderPartition::paging`]'s one walk names the
/// first term the page could not take whichever of them refused it.
///
/// The subject is asked before the capability, exactly as [`refused`] asks it: which boundary a term
/// resumes at is a fact about the TERM, and a backend answers only about the value form it may
/// actually be handed. Both questions go through the vocabulary's own
/// [`binds_the_collection`](TermSubject::binds_the_collection) and
/// [`binds_the_companion`](TermSubject::binds_the_companion), whose exhaustive matches are what make
/// a fifth subject decide rather than inherit.
fn unresumable<B: OrderCapability + ?Sized>(term: &OrderTerm) -> Option<Unpushable> {
  if term.subject().binds_the_collection()
    && matches!(B::COLLECTION_BOUNDARY, CollectionBoundary::Unbindable)
  {
    return Some(Unpushable::CollectionCursor);
  }
  if term.subject().binds_the_companion()
    && matches!(B::SHADOW_BOUNDARY, ShadowBoundary::Unbindable)
  {
    return Some(Unpushable::ShadowCursor);
  }
  None
}

/// Why `B` cannot take `term` after `earlier`, or [`None`] where it can.
fn refused<B: OrderCapability + ?Sized>(
  earlier: &[OrderTerm],
  term: &OrderTerm,
) -> Option<Unpushable> {
  match term.subject() {
    // No column of THIS row at all, so no capability row is consulted and none could help: a
    // backend answers about the value form it is handed, and this deployment's database has none to
    // hand it. Asked first, before every other question, because it is the one that needs no
    // context and the one whose sentence is narrowest.
    TermSubject::Absent(_) => return Some(Unpushable::NotStored),
    // Not a column of the row on any backend, so no capability row is consulted: the term itself is
    // the whole answer.
    TermSubject::Edge => return Some(Unpushable::CollectionTable),
    TermSubject::Array if matches!(B::COLLECTIONS, CollectionOrdering::Divergent) => {
      return Some(Unpushable::CollectionSemantics);
    }
    // The companion column is a column of the row, so what refuses it is the BYTES row and not the
    // array one: this backend is being handed a blob, not a list.
    TermSubject::Shadow if matches!(B::SHADOWS, ShadowOrdering::Divergent) => {
      return Some(Unpushable::CollectionShadow);
    }
    TermSubject::Array | TermSubject::Shadow | TermSubject::Value => {}
  }
  if term.is_nullable() && matches!(B::NULLS, NullPlacement::Unreachable) {
    return Some(Unpushable::NullPosition);
  }
  if matches!(B::REPEATED_TERMS, TermRepetition::Unrepresentable)
    // The subject is the pair (column, LEAF) rather than the column alone: an expanded citizen
    // contributes several terms under one field name, and they name different columns of the row —
    // `at_nanos` beside `at_pts` is no more a repetition than two fields would be. Reading the field
    // alone would refuse every semantic citizen's order on a dialect whose ordering holds one entry
    // per subject, which is a client's term blamed for an expansion it cannot see.
    && earlier
      .iter()
      .any(|before| before.column() == term.column() && before.leaf() == term.leaf())
  {
    return Some(Unpushable::Repetition);
  }
  None
}

/// A PAGE whose order this backend cannot put in one statement.
///
/// It carries the first term that did not fit, by the identity a rename does not move, and the
/// capability row that refused it — so the sentence a caller is given names the client's own term
/// rather than a column of whichever database answered.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PagingOrderError {
  term: &'static TermName,
  cause: Unpushable,
}

impl PagingOrderError {
  /// The first term the statement could not take.
  #[inline]
  #[must_use]
  pub const fn term(&self) -> &'static TermName {
    self.term
  }

  /// What refused it.
  #[inline]
  #[must_use]
  pub const fn cause(&self) -> Unpushable {
    self.cause
  }
}

impl core::fmt::Display for PagingOrderError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    let Self { term, cause } = self;
    let term: &str = term;
    write!(
      f,
      "a page's order lives entirely in the statement and `{term}` cannot be put in one: {cause}"
    )
  }
}

impl core::error::Error for PagingOrderError {}

/// Measured at [`NullOrder`](crate::comparison::sql::NullOrder): SQLite's own default already puts
/// `NULL` where the framework pins it. An `ORDER BY` is a list, so a repeated column is a second
/// entry the engine never reaches rather than one that replaces the first.
///
/// **Collections.** SQLite has no array type, so a declared collection is kept in an edge table and
/// a term over one carries [`TermSubject::Edge`](crate::TermSubject::Edge) whatever this row says.
/// What this row is about is the JSON array a collection would sit in if one were kept in a column:
/// that ordering compares the STORED TEXT, so `["10"]` sorts below `["9"]`, which is not the
/// framework's rule — the same fact
/// [`ListCrossingError::JsonOrdering`](crate::comparison::sql::ListCrossingError::JsonOrdering)
/// already refuses the four ordering OPERATORS for.
#[cfg(feature = "sqlite")]
impl OrderCapability for sqlx::Sqlite {
  const NULLS: NullPlacement = NullPlacement::of(<Self as crate::NullOrder>::NULLS);
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// PostgreSQL's default is the opposite of the framework's pin and it has the clause, so the
/// position is STATED on the term — which is a modifier and not an extra term, and therefore a
/// placement this backend reaches. The list reading is SQLite's.
///
/// **Collections.** The one PUSHABLE row in the frame, and it is a measurement: `ORDER BY <array
/// column>` is legal here and compares element by element with shorter-is-less on a prefix, which is
/// where [`compare_collections`] got its rule. The module note carries the walk. An element type
/// whose `PgCollectionStorage` row names the edge table instead — and a collection whose
/// `postgres(edge)` block says so — reaches this backend as
/// [`TermSubject::Edge`](crate::TermSubject::Edge) and is a remainder like the other two dialects',
/// which is what makes the storage form and not the dialect the thing the frame reads.
#[cfg(feature = "postgres")]
impl OrderCapability for sqlx::Postgres {
  const NULLS: NullPlacement = NullPlacement::of(<Self as crate::NullOrder>::NULLS);
  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;
}

/// MySQL has no `NULLS FIRST` clause at all — `ERROR 1064` — and does not need one: its default is
/// the framework's own position. The list reading is SQLite's.
///
/// **Collections.** SQLite's row, one engine over: no array type, so a declared collection is
/// edge-stored, and MySQL's own `JSON` ordering ranks by element TYPE before value — which is not
/// the framework's rule either.
#[cfg(feature = "mysql")]
impl OrderCapability for sqlx::MySql {
  const NULLS: NullPlacement = NullPlacement::of(<Self as crate::NullOrder>::NULLS);
  const REPEATED_TERMS: TermRepetition = TermRepetition::Admitted;
  const COLLECTIONS: CollectionOrdering = CollectionOrdering::Divergent;
  const COLLECTION_BOUNDARY: CollectionBoundary = CollectionBoundary::Unbindable;
  const SHADOWS: ShadowOrdering = ShadowOrdering::Bytewise;
  const SHADOW_BOUNDARY: ShadowBoundary = ShadowBoundary::Bindable;
}

/// The row with NO KNOB, and the first one whose two answers disagree.
///
/// **Nulls.** MongoDB has one null position and it is already the framework's: BSON's total order
/// runs `MinKey < Null < Numbers < String < …`, with a MISSING field ordered exactly where a `null`
/// is, so nothing sorts below a missing value on an ascending term. There is no clause to state a
/// different one and none is wanted — the fixed position IS the pin, which is why this row is
/// [`Reachable`](NullPlacement::Reachable) without a
/// [`NullOrder`](crate::comparison::sql::NullOrder) answer behind it.
///
/// **Repeats.** A `$sort` is a DOCUMENT and its keys are unique, so a second term over one field
/// REPLACES the first: a page would sort by the last direction written and resume against the
/// first. That is the crate's first genuinely unpushable order variant — an order SQLite, Postgres
/// and MySQL all render without complaint.
///
/// **Collections.** The frame's first SEMANTICS disagreement, and the only row where a backend that
/// really does keep a collection in a column of the row still refuses to order by one. MongoDB's
/// `$sort` over an array field does not compare arrays at all: it takes each document's MINIMUM
/// element on an ascending term and its MAXIMUM on a descending one, so `[9]` sorts after `[1, 99]`
/// ascending and the two directions are not even reverses of one another. The framework's rule is
/// element by element, so this is a different question under the client's own term rather than a
/// missing feature — which is what
/// [`MongoSortError::Collection`](crate::query::mongo::MongoSortError::Collection) says when it
/// refuses one.
#[cfg(feature = "mongo")]
impl OrderCapability for crate::Mongo {
  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::Unbindable;
}

/// The `sortable` word's PAGE half — which terms a page can resume at, and the row that refuses one.
/// Beside [`shadow_tests`], which is the word's ordered-scan half, for the reason that suite is
/// beside [`tests`]: one word, two guarantees, and a change to either stays visible.
#[cfg(test)]
mod shadow_cursor_tests;
#[cfg(all(test, feature = "sqlx"))]
mod shadow_tests;
#[cfg(test)]
mod tests;