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
//! A written order bound to a dialect: [`SqlOrder`], the `ORDER BY` it renders, and what it refuses
//! before rendering anything.
//!
//! # One order drives both halves of a page, which is the whole reason this type exists
//!
//! A keyset page is two renderings of one order — the `ORDER BY` the rows come back in, and the
//! `WHERE` that resumes at the cursor's row — and they have to agree about every term's direction
//! and about where `NULL` sits, or the page skips or repeats exactly the rows at a boundary. Two
//! call sites reading one list is a convention; ONE value that renders both is a guarantee, and
//! [`SqlKeyset`](super::SqlKeyset) is built from this type rather than from a slice for that reason.
//!
//! # Everything that can be refused is refused HERE, at construction
//!
//! So both renderings are infallible. [`new`](SqlOrder::new) is where an order over nothing and a
//! dialect that cannot place `NULL` are turned away, which is before a `QueryBuilder` has been
//! touched — the standard [`SqlKeyIn`](super::SqlKeyIn) holds for its own ceiling, where *a refusal
//! leaves the accumulator exactly as it was found*.

use core::{borrow::BorrowMut, marker::PhantomData};

use super::{
  ClauseTransition, NullOrder, NullOrdering, NullPosition, OrderByClause, OrderSubjects,
  QueryBuilder, QuoteIdent, SubjectSlot, pinned_nulls,
};
use crate::{
  OrderSignature, OrderTerm, TermName, Walk,
  comparison::At,
  query::{ColumnNotStored, OrderCapability, Unpushable, partition},
};

/// A written order, checked against one dialect: non-empty, and every nullable term placeable where
/// the framework pins `NULL`.
///
/// # It is `Copy`, and a page renders it twice
///
/// Two borrowed pointers, so the value is the width of what it points at — the argument
/// [`At`](crate::At) makes for the same receiver. A page hands it to the `ORDER BY` and then to the
/// keyset, and neither takes it away from the other.
///
/// # The dialect is a type parameter, and it is not decoration
///
/// What was checked at construction is `Db`'s [`NullOrder`] answer, so the checked-ness travels in
/// the type: a `SqlOrder<'_, Postgres>` cannot be rendered into a MySQL statement, which is where
/// the check would have been made against the wrong dialect.
pub struct SqlOrder<'a, Db> {
  // NON-EMPTY, established by `new` and relied on by `push_order_by`.
  terms: &'a [OrderTerm],
  // `fn() -> Db` rather than a bare parameter, so the dialect marker contributes no auto-trait or
  // variance obligation — the convention every `Db`-parameterised type in this family follows.
  db: PhantomData<fn() -> Db>,
}

impl<'a, Db: NullOrder + OrderCapability> SqlOrder<'a, Db> {
  /// `terms` as an order this dialect can render, or why it cannot.
  ///
  /// # It reads the capability frame rather than scanning for itself
  ///
  /// What a dialect's `ORDER BY` can carry is its own
  /// [`OrderCapability`](crate::query::OrderCapability) row, and
  /// [`partition`](crate::query::partition) is the one party that reads a row — so this refuses
  /// exactly the orders that frame leaves a remainder for, and a row that lied would redden here
  /// rather than render a statement ordered by something else. It is the BACKSTOP the frame's own
  /// note describes, the SQL family's twin of
  /// [`MongoOrder::new`](crate::query::mongo::MongoOrder::new): a lane that means to degrade
  /// partitions first and hands over [`pushable`](crate::query::OrderPartition::pushable), which
  /// this then takes whole.
  ///
  /// The nullability check the frame now makes was written here once, against
  /// [`NullOrdering::Inexpressible`] directly. It is the same verdict —
  /// [`NullPlacement::of`](crate::query::NullPlacement::of) is the projection of exactly that answer
  /// — and one authority rather than two that agree.
  ///
  /// # Errors
  ///
  /// [`SqlOrderError::Empty`] for an order over no terms;
  /// [`NotStored`](SqlOrderError::NotStored) for a term naming a column this deployment's database
  /// has not got, which is the declaration-truth schema's runtime half; and one variant per
  /// capability the frame names: [`NullPosition`](SqlOrderError::NullPosition),
  /// [`Repetition`](SqlOrderError::Repetition),
  /// [`CollectionTable`](SqlOrderError::CollectionTable),
  /// [`CollectionSemantics`](SqlOrderError::CollectionSemantics) and
  /// [`CollectionShadow`](SqlOrderError::CollectionShadow).
  pub fn new(terms: &'a [OrderTerm]) -> Result<Self, SqlOrderError> {
    if terms.is_empty() {
      return Err(SqlOrderError::Empty);
    }
    let partition = partition::<Db>(terms);
    if let Some(refused) = partition.remainder().first() {
      let term = refused.identity();
      return Err(match partition.cause() {
        // The DEPLOYMENT's own refusal, and the one cause that is not about this dialect's ordering
        // statement at all: the column is not here to be ordered. The dialect comes off the term's
        // own subject, which is where the emission put it, so the sentence names both halves of the
        // combination its author owns.
        Some(Unpushable::NotStored) => SqlOrderError::NotStored(ColumnNotStored::new(
          term,
          refused
            .subject()
            .absent_from()
            // Total by construction: `NotStored` is the verdict `TermSubject::Absent` alone
            // produces, and the dialect is that subject's own payload.
            .expect("a term refused as unstored names the dialect that has not got it"),
        )),
        Some(Unpushable::Repetition) => SqlOrderError::Repetition(term),
        Some(Unpushable::CollectionTable) => SqlOrderError::CollectionTable(term),
        Some(Unpushable::CollectionSemantics) => SqlOrderError::CollectionSemantics(term),
        Some(Unpushable::CollectionShadow) => SqlOrderError::CollectionShadow(term),
        // `NullPosition` and the `None` that cannot arrive beside a remainder. The default is the
        // one this family was written for and the one a shipped dialect can never reach.
        _ => SqlOrderError::NullPosition(term),
      });
    }
    Ok(Self {
      terms,
      db: PhantomData,
    })
  }
}

/// The two READINGS of a checked order, which ask the dialect nothing.
///
/// A block of their own rather than [`new`](SqlOrder::new)'s, and the split is what a bound COSTS at
/// the use rather than at the impl: `new` proves what this dialect's ordering can carry, and a
/// caller that already holds the value it returned has nothing left to prove — a keyset reading the
/// terms back would otherwise have to restate the capability rows to ask for a slice.
impl<'a, Db> SqlOrder<'a, Db> {
  /// The terms, in the sequence they run.
  #[inline]
  #[must_use]
  pub const fn terms(&self) -> &'a [OrderTerm] {
    self.terms
  }

  /// This order's fingerprint — what a cursor minted under it carries, and what one replayed
  /// against it is checked on.
  #[inline]
  #[must_use]
  pub fn signature(&self) -> OrderSignature {
    OrderSignature::of(self.terms)
  }
}

impl<'a, Db> SqlOrder<'a, Db>
where
  Db: sqlx::Database + QuoteIdent + NullOrder,
{
  /// Push this order's `ORDER BY`, running `walk`'s way.
  ///
  /// A backward walk renders every term INVERTED, which — with the rows re-reversed after they come
  /// back, which is the engine's — is the same order read from the far end. The framework's `NULL`
  /// position inverts with it, because it is a total order on the domain rather than a per-direction
  /// convention: see [`pinned_nulls`].
  ///
  /// # What each dialect states
  ///
  /// Only the one whose default disagrees. SQLite and MySQL render the bare term, so an index over
  /// the column still serves the order; Postgres renders the clause. That split is
  /// [`NullOrdering`]'s and is read here rather than restated.
  ///
  /// A `NOT NULL` term states nothing on any dialect, which is not an omission: the column holds no
  /// `NULL`, so every position is the same position, and the clause would cost an index match on
  /// the dialect that reads it for a row that cannot exist.
  ///
  /// # It renders one entry per TERM, which is the whole answer for a term over ONE column
  ///
  /// A term whose type spans SEVERAL — the framework's own [`Timestamp`](crate::Timestamp) is the
  /// first — needs its segments JOINED beneath the field's name, and that join is
  /// [`Backend::write_column`](crate::Backend::write_column)'s, which reads an ADDRESS this
  /// signature has not got. There is deliberately no second joining rule here: `at_secs` is not
  /// spelled anywhere in this crate, which is what keeps a `SELECT`, a `WHERE` and an `ORDER BY`
  /// from being three concatenations that could differ.
  ///
  /// So a composite term's ordering is [`push_order_by_with`](Self::push_order_by_with)'s, which
  /// takes the address and is the path the engine's own page renders through — see
  /// [`find`](crate::query::sql::find) and the interface's union.
  ///
  /// **A LEVEL is the same sentence one grain finer.** A term carrying [`OrderTerm::leaf`] names one
  /// leaf of a tree, and that leaf's column name is the same join — so it belongs to the same
  /// position, for the same reason, and this one renders the FIELD's name as it does for a wide
  /// composite. Nothing in the framework reaches here with either: the engine's page and its ordered
  /// scan both render through the address.
  pub fn push_order_by<S, QB>(
    self,
    builder: QueryBuilder<S, Db, QB>,
    walk: Walk,
  ) -> QueryBuilder<OrderByClause, Db, QB>
  where
    S: ClauseTransition<OrderByClause>,
    QB: BorrowMut<sqlx::QueryBuilder<Db>>,
  {
    let (first, rest) = self
      .terms
      .split_first()
      .expect("`SqlOrder::new` refuses an order over no terms");
    let mut builder = push_term::<Db, _, _>(builder, first, walk);
    for term in rest {
      builder = push_term::<Db, _, _>(builder, term, walk);
    }
    builder
  }
}

impl<Db: sqlx::Database + NullOrder> SqlOrder<'_, Db> {
  /// [`push_order_by`](Self::push_order_by) with what each term COMPARES written by `subjects` —
  /// the `ORDER BY` half of [`OrderSubjects`], whose other half is
  /// [`SqlKeyset`](super::SqlKeyset)'s.
  ///
  /// The two halves take ONE value, and that is the whole reason this exists rather than a caller
  /// pushing its own terms: a page is two renderings of one order, and an expression written one way
  /// in the ordering and another in the keyset skips or repeats exactly the rows at a boundary. The
  /// borrow impl beside [`TermColumns`](super::TermColumns) is what lets one subjects value reach
  /// both.
  ///
  /// # This position writes no wrapping, and neither do the other two
  ///
  /// Every term renders through [`order_by_with`](QueryBuilder::order_by_with), which states no pair
  /// of its own. What a subject is wrapped in is decided by the shape the subjects declare at
  /// [`shape`](OrderSubjects::shape) and written by the [`SubjectSlot`](super::SubjectSlot) opened
  /// for it — the same type at the SELECT list and in every arm of the resume predicate, so one
  /// value renders three times and cannot be bracketed differently in any of them.
  ///
  /// # The bounds are [`push_order_by`](Self::push_order_by)'s less [`QuoteIdent`]
  ///
  /// Nothing here pushes an identifier: what a rendered column costs is
  /// [`TermColumns`](super::TermColumns)'s, and a subject rendered some other way is not made to pay
  /// it. That is the dividend the seam was built for, one clause up from where the keyset takes it.
  ///
  /// # A COMPOSITE TERM'S ENTRIES RUN IN SEGMENT ORDER, and a SEMANTIC citizen arrives EXPANDED
  ///
  /// The walk is `0..OrderTerm::width()` and [`OrderTerm::segments`] is declaration order, so a term
  /// over a composite that states no sequence renders its leaves as declared — unchanged, and byte
  /// for byte what it always was.
  ///
  /// A citizen that DOES state one never reaches this position wide. [`OrderTerm::levels`] has
  /// already expanded it into one ordinary term per level, each one column, so `at: MediaTimestamp`
  /// arrives as four terms and renders `at_nanos`, `at_pts`, then the timebase pair — the 2026-08-29
  /// law's semantic half, spent where the columns are written. Nothing in this walk knows that
  /// happened, which is the point: a level is an ordinary term and this clause renders ordinary
  /// terms.
  ///
  /// The sequence moves TOGETHER with the rest of the page because it is the same expansion that
  /// moves them — [`SqlKeyset`](super::SqlKeyset) resumes the same level list, each level's operand
  /// binds one placeholder, and the `NULL` position is stated per level rather than per subject. See
  /// [`OrderTerm::levels`] for what a level carries and ingraph #467 for the design.
  pub fn push_order_by_with<S, QB, Sub>(
    self,
    builder: QueryBuilder<S, Db, QB>,
    walk: Walk,
    at: At<'_>,
    subjects: &Sub,
  ) -> QueryBuilder<OrderByClause, Db, QB>
  where
    S: ClauseTransition<OrderByClause>,
    QB: BorrowMut<sqlx::QueryBuilder<Db>>,
    Sub: OrderSubjects<Db> + ?Sized,
  {
    // The first entry is written apart from the rest because it is the one that TRANSITIONS the
    // clause: `S` becomes `OrderByClause` there and every entry after it is that state to itself.
    let mut builder =
      push_subject_entry::<Db, _, _, Sub>(builder, self.terms, 0, 0, walk, at, subjects);
    for leaf in 1..self.terms[0].width() {
      builder =
        push_subject_entry::<Db, _, _, Sub>(builder, self.terms, 0, leaf, walk, at, subjects);
    }
    for level in 1..self.terms.len() {
      for leaf in 0..self.terms[level].width() {
        builder =
          push_subject_entry::<Db, _, _, Sub>(builder, self.terms, level, leaf, walk, at, subjects);
      }
    }
    builder
  }
}

/// One ENTRY of the term at `level` — its `leaf`-th column — whose left-hand side is `subjects`',
/// with the position of `NULL` stated where this dialect needs it stated.
///
/// The whole order and the LEVEL travel together, which is [`OrderSubjects`]'s own shape: a party
/// that answers for some terms and defers the rest to [`TermColumns`](super::TermColumns) has both
/// halves in hand, and that mixed order is exactly what a nested ordering term produces.
///
/// A term contributes [`OrderTerm::width`] entries — one for an ordinary column and one per column
/// for a composite — and each states the SAME direction and the same `NULL` position, because they
/// are one subject read left to right rather than terms a client wrote separately. That is what
/// keeps a backward walk inverting the whole subject: a pair inverted in one half and not the other
/// is not the reverse of any order.
///
/// The shape is asked before the entry is opened and spent as the slot the subject is written into —
/// see the method above for why this position states no wrapping of its own.
fn push_subject_entry<Db, S, QB, Sub>(
  builder: QueryBuilder<S, Db, QB>,
  terms: &[OrderTerm],
  level: usize,
  leaf: usize,
  walk: Walk,
  at: At<'_>,
  subjects: &Sub,
) -> QueryBuilder<OrderByClause, Db, QB>
where
  Db: sqlx::Database + NullOrder,
  S: ClauseTransition<OrderByClause>,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
  Sub: OrderSubjects<Db> + ?Sized,
{
  let term = &terms[level];
  let direction = walk.direction(term.direction());
  let shape = subjects.shape(terms, level);
  builder.order_by_with(
    |qb| subjects.push_entry(SubjectSlot::new(qb, shape), at, terms, level, leaf),
    direction.is_descending(),
    nulls::<Db>(term, walk),
  )
}

/// One term, with the position of `NULL` stated where this dialect needs it stated.
fn push_term<Db, S, QB>(
  builder: QueryBuilder<S, Db, QB>,
  term: &OrderTerm,
  walk: Walk,
) -> QueryBuilder<OrderByClause, Db, QB>
where
  Db: sqlx::Database + QuoteIdent + NullOrder,
  S: ClauseTransition<OrderByClause>,
  QB: BorrowMut<sqlx::QueryBuilder<Db>>,
{
  let direction = walk.direction(term.direction());
  builder.order_by_nulls(
    term.column(),
    direction.is_descending(),
    nulls::<Db>(term, walk),
  )
}

/// The position an ordering term over `term` states on this dialect, or [`None`] where it states
/// nothing.
///
/// The three answers are the three [`NullOrdering`] members, and the last one cannot arrive here for
/// a nullable term: [`SqlOrder::new`] refused the order. It answers [`None`] all the same rather
/// than panicking, because what it would be asked about is a `NOT NULL` term — which states nothing
/// on every dialect anyway.
fn nulls<Db: NullOrder>(term: &OrderTerm, walk: Walk) -> Option<NullPosition> {
  if !term.is_nullable() || !matches!(Db::NULLS, NullOrdering::Explicit) {
    return None;
  }
  Some(pinned_nulls(walk.direction(term.direction())))
}

/// Why a written order cannot be rendered for this dialect.
///
/// # No refusal here is about a cursor
///
/// An order is refused before any cursor is looked at, which is what keeps
/// [`CursorError`](crate::CursorError) about the string a client handed back and this type about
/// the query being asked. A page over an order this refuses has no cursor to be wrong.
///
/// # One variant per [`Unpushable`] member the frame can raise at construction, and one for the
/// empty order
///
/// The two are different questions and the split is the frame's: what a STATEMENT cannot carry is a
/// capability row's answer and lands here, where what a PAGE cannot resume at is
/// [`PagingOrderError`](crate::query::PagingOrderError)'s and reaches a caller from the lane. So
/// [`Unpushable::CollectionCursor`] has no twin below — it is a fact about a dialect's CARRIER
/// rather than about its ordering statement, and no shipped dialect raises it: PostgreSQL binds a
/// boundary list as one array parameter, and the other two keep every collection in a table of its
/// own, so their terms are the partition's remainder under `Unpushable::CollectionTable`.
/// [`Unpushable::ShadowCursor`] has none for the same reason one step further out: it is a fact
/// about what an emitted ROW projects, which no dialect has an opinion about.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SqlOrderError {
  /// A term names a column THIS DEPLOYMENT's database does not store — the declaration narrowed it
  /// out of this dialect and keeps it in the record's others.
  ///
  /// The schema states the DECLARATION's truth, so the word is offered wherever the service runs;
  /// this is the deployment's own answer, given before a statement is rendered rather than as a
  /// bare *no such column* out of the driver. See [`ColumnNotStored`], which carries both halves of
  /// the sentence: which column, and which dialect has not got it.
  ///
  /// It is the one variant here that is not about what this dialect's ordering can EXPRESS. Every
  /// other one refuses a value the row really holds; this one refuses a term with no value behind
  /// it at all.
  NotStored(ColumnNotStored),
  /// An order over NO terms.
  ///
  /// There is no default order in this framework, and *an order over nothing has no spelling*: a
  /// query that wrote no term gets no `ORDER BY` at all and never reaches this type. The generated
  /// lowering makes the same case unspellable by taking its first term as a parameter of its own;
  /// here the terms arrive as one runtime slice, and this is where that slice can be empty.
  Empty,
  /// A term's column is nullable and this dialect can place `NULL` neither by default nor on the
  /// term.
  ///
  /// Refusing is what makes the framework's pinned position mean anything — see
  /// [`NullOrdering::Inexpressible`]. None of the three shipped dialects can raise it: SQLite and
  /// MySQL already order `NULL` where the framework does, and Postgres states the clause.
  ///
  /// Carries the nullable term, by the identity a rename does not move.
  NullPosition(&'static TermName),
  /// An earlier term already names this term's subject, and this dialect's ordering holds one entry
  /// per subject.
  ///
  /// None of the three shipped dialects can raise it — an `ORDER BY` is a LIST, so a repeated
  /// column is a second entry the engine never reaches — and it is here because the frame can say
  /// it: a dialect joining by naming its own capability rows may answer
  /// [`TermRepetition::Unrepresentable`](crate::query::TermRepetition::Unrepresentable), and a
  /// refusal it could not be told about would be a page sorted by the last direction written and
  /// resumed against the first.
  Repetition(&'static TermName),
  /// The term names a COLLECTION this database keeps in a table of its own, so the row being
  /// ordered has no column for it.
  ///
  /// It is every dialect's refusal and not one dialect's: SQLite and MySQL have no array type and
  /// keep every collection that way, and PostgreSQL joins them for a collection whose element type
  /// — or whose `postgres(edge)` block — chose the edge table.
  CollectionTable(&'static TermName),
  /// The term names a COLLECTION in a column of the row, and this dialect does not order one
  /// element by element.
  ///
  /// PostgreSQL does, so it is the one dialect this cannot be raised for. The other two keep a
  /// column-stored collection as JSON, whose ordering compares the stored text or ranks by element
  /// type before value — a different question under the client's own term, which is the same fact
  /// [`ListCrossingError::JsonOrdering`](super::ListCrossingError::JsonOrdering) refuses the four
  /// ordering OPERATORS for.
  CollectionSemantics(&'static TermName),
  /// The term names a COLLECTION mirrored into an ORDER-PRESERVING COMPANION COLUMN, and this
  /// dialect does not order a binary column bytewise.
  ///
  /// **No shipped dialect can raise it**, and that is the mechanism rather than luck: SQLite's
  /// `BLOB` compares by `memcmp`, PostgreSQL's `bytea` compares bytewise, and MySQL's `BLOB` carries
  /// the binary collation — all three shorter-is-less on a prefix, which is exactly the frame
  /// [`collection_sort_key`](crate::collection_sort_key) writes. It is here because the frame can
  /// say it: a dialect joining by naming its own rows may answer
  /// [`ShadowOrdering::Divergent`](crate::query::ShadowOrdering::Divergent), and a refusal it could
  /// not be told about would be rows sorted by a rule nobody wrote.
  CollectionShadow(&'static TermName),
}

impl core::fmt::Display for SqlOrderError {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Empty => f.write_str("an order over no terms has no spelling"),
      Self::NotStored(why) => write!(f, "{why}"),
      Self::NullPosition(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is nullable and this dialect cannot put NULL below every value"
        )
      }
      Self::Repetition(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is named twice and this dialect's ordering holds one entry per subject"
        )
      }
      Self::CollectionTable(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is a collection kept in a table of its own, so this row's ORDER BY has no \
           column for it"
        )
      }
      Self::CollectionSemantics(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is a collection, and this dialect does not order one element by element"
        )
      }
      Self::CollectionShadow(term) => {
        let term: &str = term;
        write!(
          f,
          "`{term}` is a collection ordered through a companion column, and this dialect does not \
           order a binary column bytewise"
        )
      }
    }
  }
}

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

impl<Db> core::fmt::Debug for SqlOrder<'_, Db> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlOrder")
      .field("terms", &self.terms)
      .finish()
  }
}

/// Written out rather than derived, for the reason every `Db`-parameterised type in this family
/// writes its own: a derive would bound `Db`, which is a marker held as `PhantomData<fn() -> Db>`
/// and which implements none of these.
impl<Db> Clone for SqlOrder<'_, Db> {
  #[inline]
  fn clone(&self) -> Self {
    *self
  }
}

impl<Db> Copy for SqlOrder<'_, Db> {}

impl<Db> PartialEq for SqlOrder<'_, Db> {
  #[inline]
  fn eq(&self, other: &Self) -> bool {
    self.terms == other.terms
  }
}

#[cfg(test)]
mod tests;