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
//! What this family's rows BIND, and nothing about the storage forms themselves — those are the
//! crate's and are tested with them, in `storage`.

/// The crossing every temporal field takes, and it names no converter anywhere: the filter carries
/// jiff values, the comparison carries the storage form, and the only thing that chose it is the
/// field's type.
#[cfg(all(feature = "jiff", feature = "time"))]
#[test]
fn a_temporal_filter_crosses_without_naming_a_converter() {
  use jiff::civil;

  use crate::{
    ScalarFilter, Temporal,
    comparison::{TryFromFilter, sql::SqlScalarComparison},
  };

  let instant: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
  let crossed = SqlScalarComparison::<Temporal<time::OffsetDateTime>, ()>::try_from_filter(
    ScalarFilter::<jiff::Timestamp>::new().with_gte(instant),
  )
  .unwrap();
  assert_eq!(
    crossed.gte().unwrap().get().unix_timestamp_nanos(),
    instant.as_nanosecond()
  );

  // The other three rows travel the same seam, and the storage type is the only thing that varies.
  let zoned = SqlScalarComparison::<Temporal<time::OffsetDateTime>, ()>::try_from_filter(
    ScalarFilter::<jiff::Zoned>::new().with_lt(instant.to_zoned(jiff::tz::TimeZone::UTC)),
  )
  .unwrap();
  assert_eq!(zoned.lt().unwrap().get().nanosecond(), 123_456_789);

  let date = SqlScalarComparison::<Temporal<time::Date>, ()>::try_from_filter(
    ScalarFilter::<jiff::civil::Date>::new().with_eq(civil::date(2024, 5, 6)),
  )
  .unwrap();
  assert_eq!(date.eq().unwrap().get().year(), 2024);

  let at = SqlScalarComparison::<Temporal<time::Time>, ()>::try_from_filter(
    ScalarFilter::<jiff::civil::Time>::new()
      .with_in_([civil::Time::new(7, 8, 9, 123_456_789).unwrap()]),
  )
  .unwrap();
  assert_eq!(at.in_().unwrap()[0].get().nanosecond(), 123_456_789);
}

/// The projection the codegen writes, resolved for a temporal field — the seam that has to work if
/// a declaration is ever to reach one of these rows without an emitter branch.
///
/// `ToDatabaseComparison` needed no row of its own for this: it is already generic in both the
/// filter's domain type and the storage type, so the temporal path travels the same projection as
/// every other kind. That is the property being pinned, and a hard-coded kind → comparison table in
/// the emitter is what it exists to keep unnecessary.
///
/// A dialect is in the gate because the projection itself asks for one — `ToDatabaseComparison`'s
/// row for a scalar filter is bounded on `Db: sqlx::Database`, so `()` stands in for a dialect
/// everywhere else in these tests and cannot here.
#[cfg(all(feature = "jiff", feature = "time", feature = "sqlite"))]
#[test]
fn the_codegen_projection_resolves_for_a_temporal_field() {
  use crate::{
    DefaultMarker, Temporal, ToGraphqlFilter,
    comparison::{ToDatabaseComparison, TryFromFilter, sql::SqlScalarComparison},
  };

  type Comparison<F, S> = <F as ToDatabaseComparison<S, sqlx::Sqlite>>::Comparison;
  type Filter<T> = <<T as DefaultMarker>::Marker as ToGraphqlFilter>::Filter;
  type Projected<T, S> = Comparison<Filter<T>, S>;

  let crossed: Projected<jiff::Timestamp, Temporal<time::OffsetDateTime>> =
    TryFromFilter::try_from_filter(
      Filter::<jiff::Timestamp>::new().with_eq(jiff::Timestamp::UNIX_EPOCH),
    )
    .unwrap();

  let _: SqlScalarComparison<Temporal<time::OffsetDateTime>, sqlx::Sqlite> = crossed;
}

/// The crossing cannot be `Err`, and the assignment is the assertion: an error type that is not
/// [`Infallible`](core::convert::Infallible) does not compile here.
///
/// This is what [`From`] buys over a `TryFrom` written by hand. Every built-in row is total, so the
/// blanket is the infallible half and std's own lifts it — "cannot fail" rather than "has not
/// failed yet".
#[cfg(all(feature = "jiff", feature = "time"))]
#[test]
fn the_temporal_crossing_cannot_fail() {
  use crate::{
    ScalarFilter, Temporal,
    comparison::{TryFromFilter, sql::SqlScalarComparison},
  };

  let crossed: Result<
    SqlScalarComparison<Temporal<time::OffsetDateTime>, ()>,
    core::convert::Infallible,
  > = SqlScalarComparison::try_from_filter(
    ScalarFilter::<jiff::Timestamp>::new().with_eq(jiff::Timestamp::UNIX_EPOCH),
  );

  assert_eq!(
    crossed.unwrap().eq().unwrap().get(),
    &time::OffsetDateTime::UNIX_EPOCH
  );
}

#[cfg(feature = "sqlite")]
mod sqlite {
  use crate::{BeU64, Carrier, Score, TypedId};

  /// One bind per carried value, and the SQL text never names the encoding — the placeholder is the
  /// same whichever row was selected.
  #[test]
  fn a_row_pushes_exactly_one_placeholder() {
    struct Scene;

    fn placeholder<V: Carrier<sqlx::Sqlite>>(value: &V) -> String {
      let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
      value.push_bind(&mut qb);
      qb.sql().as_str().to_owned()
    }

    assert_eq!(placeholder(&1i64), "?");
    assert_eq!(placeholder(&BeU64(1)), "?");
    assert_eq!(placeholder(&Score::ONE), "?");
    // The borrowed row goes through the same seam as the owned one.
    assert_eq!(placeholder(&&1i64), "?");
    // And a typed id is its stored id: one placeholder, with the entity nowhere in the text.
    assert_eq!(placeholder(&TypedId::<i64, Scene>::new(1)), "?");
  }
}

#[cfg(feature = "postgres")]
mod postgres {
  use crate::Carrier;

  /// What `value`'s row pushed: the SQL text, and how many parameters are behind it.
  fn bound<V: Carrier<sqlx::Postgres>>(value: &V) -> (String, usize) {
    use sqlx::Execute;

    let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
    value.push_bind(&mut qb);
    let mut built = qb.build();
    let binds = match built.take_arguments() {
      Ok(Some(args)) => sqlx::Arguments::len(&args),
      Ok(None) | Err(_) => 0,
    };
    (built.sql().as_str().to_owned(), binds)
  }

  /// **A COLLECTION BOUNDARY IS ONE BIND, WHATEVER THE LIST HOLDS.**
  ///
  /// This is the row's whole claim, and the one that has to be pinned rather than read: an element
  /// expansion renders `$1, $2, $3` and answers the same question, so the failure is a page that
  /// stops rendering at a boundary list longer than the dialect's
  /// [`BindCeiling`](crate::BindCeiling) — a refusal about a number the client never chose.
  ///
  /// Zero, one and many all push exactly one `$1`. The empty list is the interesting one: it is the
  /// legal LEAST boundary and an expansion would push nothing at all for it, which is not a
  /// comparison.
  ///
  /// Mutating `pg_array_carriers!` to push per element — a loop of `push_bind` over the slice —
  /// leaves the count at the list's length and reddens every row of this.
  #[test]
  fn a_collection_binds_as_one_array_parameter() {
    assert_eq!(bound(&Vec::<i64>::new()), ("$1".to_owned(), 1));
    assert_eq!(bound(&vec![1i64]), ("$1".to_owned(), 1));
    assert_eq!(bound(&vec![1i64, 2, 3, 4, 5]), ("$1".to_owned(), 1));

    assert_eq!(
      bound(&vec!["hdr".to_owned(), "sdr".to_owned()]),
      ("$1".to_owned(), 1)
    );
    assert_eq!(bound(&vec![true, false]), ("$1".to_owned(), 1));
    assert_eq!(bound(&vec![1.5f64, 2.5]), ("$1".to_owned(), 1));
    assert_eq!(bound(&vec![vec![1u8, 2], vec![3]]), ("$1".to_owned(), 1));
  }

  /// A `Vec<u8>` is ONE `BYTEA` and a `Vec<Vec<u8>>` is a `BYTEA[]`, and the two rows are two types
  /// — the same split the cursor codec makes, made here in the bind.
  ///
  /// Both push one parameter, so the count cannot tell them apart; what does is the byte the scalar
  /// row binds and the array header the collection row does.
  #[test]
  fn a_byte_column_and_a_list_of_byte_strings_are_two_rows() {
    let column = bound(&vec![1u8, 2]);
    let list = bound(&vec![vec![1u8, 2]]);

    assert_eq!(column, ("$1".to_owned(), 1));
    assert_eq!(list, ("$1".to_owned(), 1));

    let mut scalar = sqlx::postgres::PgArgumentBuffer::default();
    let _ =
      sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&[1u8, 2].as_slice(), &mut scalar).unwrap();
    let mut array = sqlx::postgres::PgArgumentBuffer::default();
    let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&[vec![1u8, 2]].as_slice(), &mut array)
      .unwrap();

    assert_eq!(scalar.to_vec(), [1, 2]);
    assert_ne!(array.to_vec(), [1, 2]);
  }
}

/// One column, one operator, three dialects — and the temporal rows change nothing about the text.
/// The comparison kind is generic over `Db` for exactly this reason, so what is being pinned is
/// that the new rows did not acquire a dialect-shaped difference on the way in.
#[cfg(all(
  feature = "jiff",
  feature = "time",
  feature = "sqlite",
  feature = "postgres",
  feature = "mysql"
))]
#[test]
fn a_temporal_comparison_lowers_the_same_in_every_dialect() {
  use crate::{
    ScalarFilter, Temporal,
    comparison::{
      TryFromFilter,
      sql::{SqlScalarComparison, tests::render},
    },
  };

  fn gte<Db>() -> SqlScalarComparison<Temporal<time::OffsetDateTime>, Db> {
    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    SqlScalarComparison::try_from_filter(ScalarFilter::<jiff::Timestamp>::new().with_gte(at))
      .unwrap()
  }

  assert_eq!(
    render::<sqlx::Sqlite, _>("at", &gte()),
    ("\"at\" >= ?".to_owned(), 1)
  );
  assert_eq!(
    render::<sqlx::Postgres, _>("at", &gte()),
    ("\"at\" >= $1".to_owned(), 1)
  );
  assert_eq!(
    render::<sqlx::MySql, _>("at", &gte()),
    ("`at` >= ?".to_owned(), 1)
  );
}

/// The bound value is NOT observable from the rendered SQL — a wrong carrier row renders identical
/// text and binds the same number of times — so this module reads the argument buffer instead.
///
/// Postgres is where that is possible without a connection: its `ArgumentBuffer` dereferences to a
/// `Vec<u8>`, so a probe binding nothing can record where it stood. Two probes around one carrier
/// leave the exact bytes that carrier pushed, length prefix included. The other two dialects hold
/// their arguments as opaque values with no byte view, and the property under test — that the row
/// binds its own storage type and its own value — is not dialect-shaped.
#[cfg(all(feature = "jiff", feature = "time", feature = "postgres"))]
mod bound_bytes {
  use core::cell::RefCell;
  use std::rc::Rc;

  use crate::{Carrier, Temporal, TemporalStorage, TypedId};

  /// Binds nothing and records the whole buffer as it stood when its turn came.
  #[derive(Clone, Default)]
  struct Probe(Rc<RefCell<Vec<u8>>>);

  impl sqlx::Type<sqlx::Postgres> for Probe {
    fn type_info() -> <sqlx::Postgres as sqlx::Database>::TypeInfo {
      <i32 as sqlx::Type<sqlx::Postgres>>::type_info()
    }
  }

  impl sqlx::Encode<'_, sqlx::Postgres> for Probe {
    fn encode_by_ref(
      &self,
      buf: &mut <sqlx::Postgres as sqlx::Database>::ArgumentBuffer,
    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
      *self.0.borrow_mut() = buf.to_vec();
      // Writing nothing is what makes the reading honest, and sqlx asserts it: a `Yes` that wrote
      // bytes trips its own `debug_assert` one frame up.
      Ok(sqlx::encode::IsNull::Yes)
    }
  }

  /// The bytes `value`'s carrier row pushed, and nothing else.
  fn pushed<V: Carrier<sqlx::Postgres>>(value: &V) -> Vec<u8> {
    let before = Probe::default();
    let after = Probe::default();

    let mut qb = sqlx::QueryBuilder::<sqlx::Postgres>::default();
    qb.push_bind(before.clone());
    value.push_bind(&mut qb);
    qb.push_bind(after.clone());

    let start = before.0.borrow().len();
    let buffer = after.0.borrow();
    // The trailing four bytes are the second probe's own length slot, reserved before its turn.
    buffer[start..buffer.len() - 4].to_vec()
  }

  /// The wrapper binds its inner value and adds nothing of its own — the delegation is a delegation
  /// and not a re-encoding.
  #[test]
  fn the_wrapper_binds_exactly_what_it_wraps() {
    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let stored = at.to_storage();

    assert_eq!(pushed(&Temporal::from(at)), pushed(&stored));
    assert!(!pushed(&Temporal::from(at)).is_empty());
  }

  /// A typed id binds its STORED id and nothing else, in bytes: two entities addressed by one id
  /// type push the same parameter, which is what "storage sees only `I`" means where it is spent.
  #[test]
  fn a_typed_id_binds_exactly_the_id_it_holds() {
    struct Scene;
    struct Keyframe;

    assert_eq!(pushed(&TypedId::<i64, Scene>::new(7)), pushed(&7i64));
    assert_eq!(
      pushed(&TypedId::<i64, Scene>::new(7)),
      pushed(&TypedId::<i64, Keyframe>::new(7))
    );
    assert!(!pushed(&TypedId::<i64, Scene>::new(7)).is_empty());
  }

  /// Three storage types, three different pushes — and the SQL text cannot tell them apart, which
  /// is the whole reason this test reads bytes. A row rewired to bind a neighbour's type is caught
  /// here and nowhere else.
  #[test]
  fn each_temporal_row_pushes_its_own_type() {
    use jiff::civil;

    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let instant = pushed(&Temporal::from(at));
    let date = pushed(&Temporal::from(civil::date(2024, 5, 6)));
    let time = pushed(&Temporal::from(
      civil::Time::new(7, 8, 9, 123_456_789).unwrap(),
    ));

    assert_ne!(instant, date);
    assert_ne!(instant, time);
    assert_ne!(date, time);

    // A `DATE` is four bytes and the other two are eight, all behind the same four-byte length
    // prefix — so the widths alone separate the date row, and the values separate the rest.
    assert_eq!(date.len(), 4 + 4);
    assert_eq!(instant.len(), 4 + 8);
    assert_eq!(time.len(), 4 + 8);
  }

  /// A value change is visible in the pushed bytes, which is what makes the two assertions above
  /// mean something: identical bytes for different values would have made every `assert_ne!` above
  /// pass for the wrong reason.
  #[test]
  fn a_different_operand_pushes_different_bytes() {
    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let later: jiff::Timestamp = "2024-05-06T07:08:09.123457789Z".parse().unwrap();

    assert_ne!(pushed(&Temporal::from(at)), pushed(&Temporal::from(later)));
  }

  /// The wrapper's TWO bind paths agree, in bytes.
  ///
  /// [`Carrier::push_bind`](crate::Carrier::push_bind) is how this crate binds a scalar operand;
  /// sqlx's [`Encode`](sqlx::Encode) is how sqlx binds one — and how it binds each ELEMENT of the
  /// array a collection column lowers into, which is why `Temporal<T>` now has both. A type whose
  /// two paths disagree writes one column as a scalar and another as an array member, and renders
  /// identical SQL either way.
  ///
  /// They cannot disagree here because both end at `T` and `time`'s three carry through
  /// `native_carriers!`, whose body IS `push_bind`. This is the measurement of that rather than the
  /// argument for it. It is not a property every carrier has: `i8` widens to `smallint` here while
  /// sqlx types it `"char"`, which is why `i8` declares the edge table.
  #[test]
  fn the_carrier_row_and_sqlxs_encoder_bind_the_same_bytes() {
    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let wrapped = Temporal::from(at);

    let mut buf = sqlx::postgres::PgArgumentBuffer::default();
    let _ = sqlx::Encode::<sqlx::Postgres>::encode_by_ref(&wrapped, &mut buf).unwrap();
    let encoded = buf.to_vec();

    // A Postgres parameter is its network-order length and then its bytes, and `pushed` returns
    // both — so the encoder's output is the carrier's push with the prefix put back.
    let mut expected = i32::try_from(encoded.len()).unwrap().to_be_bytes().to_vec();
    expected.extend_from_slice(&encoded);

    assert!(!encoded.is_empty());
    assert_eq!(pushed(&wrapped), expected);
  }

  /// Postgres stores microseconds, so the last three digits of a nanosecond operand are gone by the
  /// time the bytes exist — the encoder takes `whole_microseconds()` and says nothing. The crossing
  /// kept them (see `TemporalStorage`'s own tests); this is where they stop, and it is sqlx's
  /// behaviour rather than this crate's.
  #[test]
  fn the_bind_is_where_postgres_loses_the_last_three_digits() {
    let at: jiff::Timestamp = "2024-05-06T07:08:09.123456789Z".parse().unwrap();
    let rounded: jiff::Timestamp = "2024-05-06T07:08:09.123456000Z".parse().unwrap();

    assert_ne!(at.to_storage(), rounded.to_storage());
    assert_eq!(
      pushed(&Temporal::from(at)),
      pushed(&Temporal::from(rounded))
    );
  }
}

/// **TWO placeholders out of ONE field, in every dialect the build compiles.**
///
/// The framework's own instant is the one row in this family's table that is not one column, so what
/// is pinned here is the pair a `VALUES` list gets: the two placeholders and the comma between them
/// are this row's, and the count is never told to the engine writing the list.
///
/// The bind COUNT beside the text is the half a placeholder cannot show — a row pushing one value
/// twice renders the same string — and the dialect spellings differ, which is what makes the
/// generic header a real claim rather than a coincidence of SQLite's `?`.
#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
mod instant {
  use crate::{Carrier, Timestamp};

  /// One value through one dialect's builder: the text it renders, and the number of arguments that
  /// really bound.
  fn pushed<Db, V>(value: &V) -> (String, usize)
  where
    Db: sqlx::Database,
    V: Carrier<Db>,
    <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
  {
    use sqlx::Execute as _;

    let mut qb = sqlx::QueryBuilder::<Db>::default();
    value.push_bind(&mut qb);
    let mut built = qb.build();
    let binds = match built.take_arguments() {
      Ok(Some(arguments)) => sqlx::Arguments::len(&arguments),
      Ok(None) | Err(_) => 0,
    };
    (built.sql().as_str().to_owned(), binds)
  }

  fn at() -> Timestamp {
    "2026-08-09T21:14:03.123456789Z"
      .parse()
      .expect("the fixture parses")
  }

  #[cfg(feature = "sqlite")]
  #[test]
  fn sqlite_takes_two_placeholders() {
    assert_eq!(pushed::<sqlx::Sqlite, _>(&at()), (String::from("?, ?"), 2));
    // A scalar beside it is one, so the two are the composite's own and not the builder's.
    assert_eq!(pushed::<sqlx::Sqlite, _>(&1i64), (String::from("?"), 1));
  }

  #[cfg(feature = "postgres")]
  #[test]
  fn postgres_numbers_them_both() {
    assert_eq!(
      pushed::<sqlx::Postgres, _>(&at()),
      (String::from("$1, $2"), 2)
    );
  }

  #[cfg(feature = "mysql")]
  #[test]
  fn mysql_takes_two_placeholders() {
    assert_eq!(pushed::<sqlx::MySql, _>(&at()), (String::from("?, ?"), 2));
  }

  /// **WHICH two values bound**, which the placeholder text cannot show: a row pushing the seconds
  /// twice renders exactly the same string.
  ///
  /// Read out of a LIVE table as two raw integers, so the assertion is what the engine actually
  /// received. The ORDER is the second half of it — a row that pushed its halves the other way round
  /// binds the same two numbers and stores an instant nobody wrote.
  #[cfg(feature = "sqlite")]
  #[tokio::test]
  async fn the_two_binds_are_the_seconds_and_then_the_nanoseconds() {
    use sqlx::{Connection as _, Row as _};

    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    sqlx::query(r#"CREATE TABLE "stamps" ("at_secs" BIGINT, "at_nanos" INT)"#)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");

    let instant = at();
    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::new(r#"INSERT INTO "stamps" VALUES ("#);
    instant.push_bind(&mut qb);
    qb.push(")");
    qb.build().execute(&mut db).await.expect("one row");

    let stored = sqlx::query(r#"SELECT "at_secs", "at_nanos" FROM "stamps""#)
      .fetch_one(&mut db)
      .await
      .expect("one row");
    assert_eq!(
      (
        stored.get::<i64, _>("at_secs"),
        stored.get::<i32, _>("at_nanos")
      ),
      (instant.as_second(), instant.subsec_nanosecond())
    );
    assert_eq!(
      stored.get::<i32, _>("at_nanos"),
      123_456_789,
      "all nine digits, which is what the second column exists for"
    );
  }
}

/// **THE CARDINALITY'S THREE CARRIERS**, read where the difference between them lives: what the bind
/// actually sends, and what the read refuses.
///
/// [`Count`](crate::Count) is the one type in this table whose crossing SPENDS an invariant — a
/// cardinality counts rows that exist, so it is bounded by the physical store and may narrow into an
/// `i64` where a bare `u64` may not. These lanes are that claim put to a real engine rather than
/// left in the doc that makes it.
#[cfg(feature = "sqlite")]
mod cardinality {
  use crate::{Carrier, Count};

  /// One `Count` written into a real column and read straight back out AS AN `i64` — so the
  /// assertion is the bytes the engine received rather than the value the type held.
  async fn stored(count: Count) -> i64 {
    use sqlx::{Connection as _, Row as _};

    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    sqlx::query(r#"CREATE TABLE "tallies" ("n" INTEGER)"#)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");

    let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::new(r#"INSERT INTO "tallies" VALUES ("#);
    count.push_bind(&mut qb);
    qb.push(")");
    qb.build().execute(&mut db).await.expect("one row");

    sqlx::query(r#"SELECT "n" FROM "tallies""#)
      .fetch_one(&mut db)
      .await
      .expect("one row")
      .get::<i64, _>("n")
  }

  /// **THE BIND IS THE NARROWED FORM, AND IT SATURATES.**
  ///
  /// An ordinary count arrives whole. The two magnitudes past `i64::MAX` arrive as `i64::MAX`, which
  /// is the arm [`Count::to_signed`](crate::Count::to_signed) documents as unreachable — measured
  /// here so that *unreachable* stays a claim about callers rather than about the function.
  #[tokio::test]
  async fn a_count_binds_as_the_signed_form_its_own_codec_produces() {
    assert_eq!(stored(Count::new(0)).await, 0);
    assert_eq!(stored(Count::new(7)).await, 7);
    assert_eq!(stored(Count::new(i64::MAX.unsigned_abs())).await, i64::MAX);
    assert_eq!(stored(Count::new(u64::MAX)).await, i64::MAX);
  }

  /// **AND A NEGATIVE COLUMN IS REFUSED BY NAME**, which is the half no write of this framework's
  /// can reach.
  ///
  /// The row is put there by hand — the only way it CAN be, the bind above having no negative arm —
  /// which is exactly the corrupt-row case the refusal exists for: a hand-edited database, a column
  /// shared with something else, a bit flip. What comes back is sqlx's own
  /// [`ColumnDecode`](sqlx::Error::ColumnDecode) naming the column, carrying
  /// [`NegativeCount`](crate::NegativeCount) with the value it refused, rather than a clamp to zero
  /// that would answer a question nobody asked.
  #[tokio::test]
  async fn a_negative_column_refuses_the_read_rather_than_clamping_it() {
    use sqlx::{Connection as _, Row as _};

    let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
      .await
      .expect("an in-memory database");
    sqlx::query(r#"CREATE TABLE "tallies" ("n" INTEGER)"#)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
    sqlx::query(r#"INSERT INTO "tallies" VALUES (5), (-3)"#)
      .execute(&mut db)
      .await
      .expect("one honest row and one nobody wrote");

    let rows = sqlx::query(r#"SELECT "n" FROM "tallies" ORDER BY "n" DESC"#)
      .fetch_all(&mut db)
      .await
      .expect("both rows");

    assert_eq!(
      rows[0].try_get::<Count, _>("n").expect("an ordinary count"),
      Count::new(5)
    );

    let refused = rows[1]
      .try_get::<Count, _>("n")
      .expect_err("a negative column is not a cardinality");
    let sqlx::Error::ColumnDecode { index, source } = &refused else {
      panic!("the refusal names the column it read: {refused:?}");
    };
    // The quotes are SQLite's own: a result column named by a quoted expression is reported
    // verbatim, so what is being read here is WHICH column and not how the driver spells it.
    assert_eq!(index.trim_matches('"'), "n");
    assert!(
      source.to_string().contains("-3"),
      "and the sentence carries the value it refused: {source}"
    );
  }
}

/// **THE CARDINALITY ON MYSQL IS THE IDENTITY** — the one dialect whose column holds a `u64` whole,
/// so the row spends nothing and the type it declares is `u64`'s own.
///
/// It is the counterpart of the narrowing lanes above, and reading the TYPE is what tells the two
/// apart: a `Count` that had quietly borrowed the `i64` row here would bind the same placeholder and
/// store the same number for every value a test can hold, and would differ only past `i64::MAX`.
#[cfg(feature = "mysql")]
#[test]
fn a_count_declares_the_unsigned_column_on_mysql() {
  assert_eq!(
    <crate::Count as sqlx::Type<sqlx::MySql>>::type_info(),
    <u64 as sqlx::Type<sqlx::MySql>>::type_info(),
    "MySQL holds a cardinality natively, so the row declares the width itself"
  );
}

/// **A PATTERN BINDS AS ITS PATTERN AND THE PREDICATE IS AN ORDINARY TEXT PREDICATE** — the eight
/// operators the `scalar` family publishes, lowered on the one dialect this file can render without
/// a server.
///
/// `eq` is the operator the citizen exists for: it asks *which row holds THIS pattern*, and what it
/// binds is the pattern text — so the placeholder carries `^a+$` and the automaton reaches no
/// statement. `gte` is beside it because the ordering the family publishes is the column's text
/// collation and nothing more; see `graphql::filter`'s row, where what an order over patterns means
/// is written down.
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[test]
fn a_pattern_filter_lowers_to_a_text_predicate_over_the_pattern() {
  use crate::{
    At, ComplexComparison, FieldName, RecordAddress, ScalarFilter,
    comparison::{
      TryFromFilter,
      sql::{SqlConjunction, SqlScalarComparison},
    },
  };

  const ROW: RecordAddress = RecordAddress::new(FieldName::new("watches"), &[FieldName::new("id")]);

  let filter = ScalarFilter::<regex::Regex>::new()
    .with_eq(regex::Regex::new("^a+$").expect("a pattern"))
    .with_gte(regex::Regex::new("^b").expect("a pattern"));
  let crossed =
    SqlScalarComparison::<regex::Regex, sqlx::Sqlite>::try_from_filter(filter).expect("it crosses");

  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  let out = SqlConjunction::with_lead(&mut qb, "");
  let frame = At::new(&ROW).frame(FieldName::new("include"));
  crossed.apply(frame.at(), out).expect("it lowers");
  assert_eq!(qb.sql(), r#""include" = ? AND "include" >= ?"#);
}

/// **WHAT THE PLACEHOLDER ACTUALLY HOLDS IS THE PATTERN**, asked of a live database rather than of a
/// rendered string — the one thing the SQL above cannot show.
///
/// `Carrier` pushes `as_str`, so the value that reaches the driver is the expression text and never
/// a rendering of the automaton. Selected straight back out as a `String`, which is the shortest
/// proof that the bind and the `TEXT` column agree about what a pattern IS.
#[cfg(all(feature = "sqlite", feature = "regex"))]
#[tokio::test]
async fn a_bound_pattern_reaches_the_driver_as_its_text() {
  use sqlx::Connection as _;

  use crate::Carrier as _;

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");

  let mut qb = sqlx::QueryBuilder::<sqlx::Sqlite>::default();
  qb.push("SELECT ");
  regex::Regex::new("^[a-z]+(?:-[0-9]+)?$")
    .expect("a pattern")
    .push_bind(&mut qb);
  assert_eq!(qb.sql(), "SELECT ?", "one placeholder, one value");

  let bound: String = qb
    .build_query_scalar()
    .fetch_one(&mut db)
    .await
    .expect("the driver takes the bind");
  assert_eq!(bound, "^[a-z]+(?:-[0-9]+)?$");
}