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
//! **A field whose TYPE spans two columns, through every lane that names a column.**
//!
//! ```text
//! struct Take { id: i64, tb: Timebase }        ONE field on the row
//! CREATE TABLE "take" ("id" …, "tb_num" …, "tb_den" …)
//! INSERT INTO "take" ("id", "tb_num", "tb_den") VALUES (?, ?, ?)
//! SELECT "id", "tb_num", "tb_den" FROM "take"
//! ```
//!
//! The row keeps ONE field and the statements name THREE columns, and nothing between them holds a
//! joined name: `COLUMNS` is a tree of [`ColumnShape`]s whose second entry is what `Timebase`
//! answered, and `tb_num` is assembled while a statement is being written.
//!
//! # What each half is measured against
//!
//! | half | measured how |
//! |---|---|
//! | the descriptor's agreement with the row | a `const` — [`describes`](crate::describes) walks the flat table against the nested list |
//! | `CREATE`, `INSERT`, `SELECT` on SQLite | live, in-memory, through the schema lane's own DDL |
//! | the value's crossing | live: two `i64`s out through ONE `push_bind`, two columns back into ONE field |
//! | Postgres and MySQL | the rendered TEXT, which is all this repository provisions |
//! | `flatten` | a second row, one word apart, rendering `num`/`den` |
//!
//! # The flattened twin is the same declaration one word apart
//!
//! [`FlattenedRow`] differs from [`TakeRow`] in nothing but the entry its `COLUMNS` holds — `flattened`
//! where the other says `shape` — so the difference in what three lanes render is attributable to
//! that word and to nothing else. It is the ROW-side half of the twin the derive corpus already
//! carries for the predicate.

use sqlx::QueryBuilder;

use super::insert_statement;
#[cfg(any(feature = "postgres", feature = "mysql"))]
use super::upsert_statement;
use crate::{
  Assemble, Carrier, ColumnKind, ColumnName, ColumnShape, ComplexComparison, FieldName,
  Identifiable, Record, RecordAddress, Transformer, assembled, assembled_flattened,
  comparison::{Backend, sql::SqlKeyIn},
  query::sql::{CrossingError, SqlQuery, SqlWrite},
};

/// A rate, stored as TWO columns — the composite this whole module is about.
///
/// Declared here rather than reached for, because a composite is a thing a DOWNSTREAM writes: no
/// comparison kind this crate ships occupies more than one column, so the shape a holder has to be
/// able to describe exists only outside the framework. What it states is the pair every composite
/// states — a width, and a bind that fills it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Timebase {
  num: i64,
  den: i64,
}

/// The WIDTH, and the one authority the rest of this module reads.
///
/// It names no dialect. `num` and `den` are `num` and `den` in every database that has columns at
/// all, which is what makes the parameter the trait deliberately does not carry.
impl ColumnKind for Timebase {
  const SEGMENTS: &'static [ColumnShape] = &[
    ColumnShape::Plain(ColumnName::new("num")),
    ColumnShape::Plain(ColumnName::new("den")),
  ];
}

/// **N BINDS OUT.** The engine writes the comma between FIELDS because a field is what it counts;
/// the comma between a field's own columns is here, because the count is this type's.
///
/// One dialect named rather than `Db: sqlx::Database`, for the reason a downstream composite's
/// crossing names one: with the header generic this impl would overlap the framework's own rows for
/// a backend that is not an `sqlx::Database`, and rustc cannot see from outside that none will
/// arrive.
#[cfg(feature = "sqlite")]
impl Carrier<sqlx::Sqlite> for Timebase {
  fn push_bind(&self, qb: &mut QueryBuilder<sqlx::Sqlite>) {
    qb.push_bind(self.num);
    qb.push(", ");
    qb.push_bind(self.den);
  }
}

#[cfg(feature = "postgres")]
impl Carrier<sqlx::Postgres> for Timebase {
  fn push_bind(&self, qb: &mut QueryBuilder<sqlx::Postgres>) {
    qb.push_bind(self.num);
    qb.push(", ");
    qb.push_bind(self.den);
  }
}

#[cfg(feature = "mysql")]
impl Carrier<sqlx::MySql> for Timebase {
  fn push_bind(&self, qb: &mut QueryBuilder<sqlx::MySql>) {
    qb.push_bind(self.num);
    qb.push(", ");
    qb.push_bind(self.den);
  }
}

/// The record: an id, and one field that is two columns.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Take {
  id: i64,
  tb: Timebase,
}

impl Identifiable for Take {
  type Id = i64;

  fn id_ref(&self) -> &i64 {
    &self.id
  }
}

impl Transformer for Take {
  type Graphql = ();
  type Key = i64;
  type Lineage = i64;
  type Record = Self;

  fn key(&self) -> i64 {
    self.id
  }
}

impl<Db: Backend> Record<Db> for Take {
  type Row = TakeRow;
  type Comparison = SqlKeyIn<i64, Db, 1>;
  type OrderBy = ();
}

/// The stored row. **ONE field for the composite**, which is the claim the whole module rests on: a
/// value spanning two columns is not two fields that happen to be adjacent, so nothing here can put
/// them in the wrong order or fill one and forget the other.
#[derive(Debug, Clone, PartialEq, Eq)]
struct TakeRow {
  id: i64,
  tb: Timebase,
}

/// The twin, DIFFERENT IN ONE ENTRY — see the module note.
#[derive(Debug, Clone, PartialEq, Eq)]
struct FlattenedRow {
  id: i64,
  tb: Timebase,
}

/// Every name this fixture's tables and columns are spelled by, once.
const TAKE: RecordAddress = RecordAddress::new(FieldName::new("take"), &[FieldName::new("id")]);
const FLATTEN: RecordAddress =
  RecordAddress::new(FieldName::new("flattened"), &[FieldName::new("id")]);
const ALIASES: &[&str] = &["__ig_take_0__", "__ig_take_1__"];

/// The bodies both rows share: everything but the one `COLUMNS` entry that is the experiment.
macro_rules! row {
  ($row:ty, $address:expr, $columns:expr) => {
    impl<Db> SqlQuery<Db> for $row
    where
      Db: Backend + sqlx::Database,
      SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
      i64: Carrier<Db>,
      Timebase: ColumnKind,
      for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
      for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
    {
      type Record = Take;
      type Address = SqlKeyIn<i64, Db, 1>;

      const ADDRESS: RecordAddress = $address;
      const ALIASES: &'static [&'static str] = ALIASES;
      const COLUMNS: &'static [ColumnShape] = $columns;

      fn addresses(ids: &[i64]) -> Result<Self::Address, CrossingError> {
        Ok(SqlKeyIn::new(
          ["id"],
          ids.iter().map(|id| [*id]).collect::<Vec<_>>(),
        ))
      }

      fn id(&self) -> Result<i64, CrossingError> {
        Ok(self.id)
      }

      fn record(self) -> Result<Take, CrossingError> {
        Ok(Take {
          id: self.id,
          tb: self.tb,
        })
      }
    }

    impl<Db> SqlWrite<Db> for $row
    where
      Db: Backend + sqlx::Database,
      SqlKeyIn<i64, Db, 1>: ComplexComparison<Db>,
      i64: Carrier<Db>,
      Timebase: Carrier<Db> + ColumnKind,
      for<'r> i64: sqlx::Decode<'r, Db> + sqlx::Type<Db>,
      for<'a> &'a str: sqlx::ColumnIndex<Db::Row>,
    {
      fn row(record: Take) -> Result<Self, CrossingError> {
        Ok(Self {
          id: record.id,
          tb: record.tb,
        })
      }

      /// Indexed by FIELD: position 1 is the whole composite, and its own `push_bind` is what fills
      /// two placeholders. A row that returned to counting COLUMNS here would need this `match` to
      /// know the width, which is the number the type is the only party holding.
      fn bind(&self, at: usize, qb: &mut QueryBuilder<Db>) {
        match at {
          0 => self.id.push_bind(qb),
          _ => self.tb.push_bind(qb),
        }
      }

      fn bind_address(&self, _at: usize, qb: &mut QueryBuilder<Db>) {
        self.id.push_bind(qb);
      }
    }
  };
}

row!(
  TakeRow,
  TAKE,
  &[
    ColumnShape::Plain(ColumnName::new("id")),
    crate::shape::<Timebase>(ColumnName::new("tb")),
  ]
);
row!(
  FlattenedRow,
  FLATTEN,
  &[
    ColumnShape::Plain(ColumnName::new("id")),
    crate::flattened::<Timebase>(),
  ]
);

/// **The DESCRIPTOR's agreement with the row, in a `const`.**
///
/// The descriptor is the PHYSICAL table, so its columns are flat and each carries a stored type; the
/// row's list is by field. What the audit therefore checks is the JOIN between them — `tb` met by a
/// `tb_num` and a `tb_den`, in that order — which is the only compile-time statement anybody makes
/// about the names a `SELECT` will render.
#[cfg(feature = "sqlite")]
impl crate::Describe<sqlx::Sqlite> for Take {
  const BLUEPRINT: crate::Table = crate::Table::new(
    TAKE,
    &[
      crate::Column::new(FieldName::new("id"), "INTEGER", false),
      crate::Column::new(FieldName::new("tb_num"), "INTEGER", false),
      crate::Column::new(FieldName::new("tb_den"), "INTEGER", false),
    ],
  );
}

#[cfg(feature = "sqlite")]
const _: () = assert!(crate::describes(
  &<Take as crate::Describe<sqlx::Sqlite>>::BLUEPRINT,
  <TakeRow as SqlQuery<sqlx::Sqlite>>::COLUMNS
));

/// A field is ONE entry and its type decides how many columns it is — so the two questions a
/// statement asks of this list have two different answers, and neither is the other's default.
#[cfg(feature = "sqlite")]
#[test]
fn the_list_counts_fields_and_the_width_counts_columns() {
  let columns = <TakeRow as SqlQuery<sqlx::Sqlite>>::COLUMNS;
  assert_eq!(columns.len(), 2, "an id and a composite");
  assert_eq!(crate::width(columns), 3, "which is three columns");
  assert_eq!(
    columns[1].segments().len(),
    2,
    "and the second entry carries what its type answered"
  );
}

/// The statement text one dialect renders, with each statement's bind count beside it — the pairing
/// the write lane's own harness uses, and for its reason: a placeholder says nothing about what went
/// into it, so a lane binding one value twice renders the right string.
fn insert_text<Row, Db>(row: &Row) -> (String, usize)
where
  Row: SqlWrite<Db>,
  Db: crate::query::sql::SqlDialect,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  use sqlx::Execute as _;

  let mut statement = insert_statement::<Row, Db>(row);
  let mut built = statement.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)
}

/// The `SELECT` one dialect renders for a row — the read lane's opening, which is the other list the
/// shapes drive.
fn select_text<Row, Db>() -> String
where
  Row: SqlQuery<Db>,
  Db: crate::query::sql::SqlDialect,
  i64: sqlx::Type<Db>,
  for<'t> i64: sqlx::Encode<'t, Db>,
  <Db as sqlx::Database>::Arguments: sqlx::IntoArguments<Db>,
{
  use sqlx::Execute as _;

  let mut statement =
    crate::query::sql::find::scan::<Row, Db>(None, None, None).expect("no predicate to lower");
  statement.build().sql().as_str().to_owned()
}

fn take() -> Take {
  Take {
    id: 7,
    tb: Timebase {
      num: 24_000,
      den: 1_001,
    },
  }
}

/// **SQLite: three columns from two fields, and the binds match.**
#[cfg(feature = "sqlite")]
#[test]
fn the_prefixed_columns_are_what_sqlite_is_sent() {
  let row = <TakeRow as SqlWrite<sqlx::Sqlite>>::row(take()).expect("nothing converts");
  assert_eq!(
    insert_text::<TakeRow, sqlx::Sqlite>(&row),
    (
      r#"INSERT INTO "take" ("id", "tb_num", "tb_den") VALUES (?, ?, ?)"#.to_owned(),
      3
    )
  );
  assert_eq!(
    select_text::<TakeRow, sqlx::Sqlite>(),
    r#"SELECT "id", "tb_num", "tb_den" FROM "take""#
  );
}

/// **And `flatten` is the SAME declaration one word apart**: the prefix goes and nothing else moves —
/// the field is still one, the width is still two, and the binds are still two.
#[cfg(feature = "sqlite")]
#[test]
fn the_flatten_word_drops_the_prefix_and_nothing_else() {
  let row = <FlattenedRow as SqlWrite<sqlx::Sqlite>>::row(take()).expect("nothing converts");
  assert_eq!(
    insert_text::<FlattenedRow, sqlx::Sqlite>(&row),
    (
      r#"INSERT INTO "flattened" ("id", "num", "den") VALUES (?, ?, ?)"#.to_owned(),
      3
    )
  );
  assert_eq!(
    select_text::<FlattenedRow, sqlx::Sqlite>(),
    r#"SELECT "id", "num", "den" FROM "flattened""#
  );
  assert_eq!(
    crate::width(<FlattenedRow as SqlQuery<sqlx::Sqlite>>::COLUMNS),
    3,
    "dropping a name drops no column"
  );
}

/// **Postgres: the same three columns under its own placeholders**, and the keyed replace naming
/// every one of them.
#[cfg(feature = "postgres")]
#[test]
fn postgres_renders_the_flattened_columns() {
  let row = <TakeRow as SqlWrite<sqlx::Postgres>>::row(take()).expect("nothing converts");
  assert_eq!(
    insert_text::<TakeRow, sqlx::Postgres>(&row),
    (
      r#"INSERT INTO "take" ("id", "tb_num", "tb_den") VALUES ($1, $2, $3)"#.to_owned(),
      3
    )
  );
  assert_eq!(
    select_text::<TakeRow, sqlx::Postgres>(),
    r#"SELECT "id", "tb_num", "tb_den" FROM "take""#
  );

  use sqlx::Execute as _;
  let mut statement = upsert_statement::<TakeRow, sqlx::Postgres>(&row);
  let replace = statement.build().sql().as_str().to_owned();
  assert_eq!(
    replace,
    concat!(
      r#"INSERT INTO "take" ("id", "tb_num", "tb_den") VALUES ($1, $2, $3)"#,
      r#" ON CONFLICT ("id") DO UPDATE SET "id" = "excluded"."id","#,
      r#" "tb_num" = "excluded"."tb_num", "tb_den" = "excluded"."tb_den""#
    ),
    "the assignment list is every COLUMN, so a composite contributes its segments here too"
  );
}

/// **MySQL: the same three columns in its own brackets**, and its target-less replace naming each.
#[cfg(feature = "mysql")]
#[test]
fn mysql_renders_the_flattened_columns() {
  let row = <TakeRow as SqlWrite<sqlx::MySql>>::row(take()).expect("nothing converts");
  assert_eq!(
    insert_text::<TakeRow, sqlx::MySql>(&row),
    (
      "INSERT INTO `take` (`id`, `tb_num`, `tb_den`) VALUES (?, ?, ?)".to_owned(),
      3
    )
  );
  assert_eq!(
    select_text::<TakeRow, sqlx::MySql>(),
    "SELECT `id`, `tb_num`, `tb_den` FROM `take`"
  );

  use sqlx::Execute as _;
  let mut statement = upsert_statement::<TakeRow, sqlx::MySql>(&row);
  let replace = statement.build().sql().as_str().to_owned();
  assert_eq!(
    replace,
    concat!(
      "INSERT INTO `take` (`id`, `tb_num`, `tb_den`) VALUES (?, ?, ?)",
      " ON DUPLICATE KEY UPDATE `id` = VALUES(`id`),",
      " `tb_num` = VALUES(`tb_num`), `tb_den` = VALUES(`tb_den`)"
    )
  );
}

/// **N COLUMNS IN.** The mirror of the `Carrier` rows above, and the third thing a composite states:
/// the segments it spans are the ones it reads back, joined under whatever the holder passed down.
///
/// Generic over the ROW where the carrier rows name a dialect each, and the difference is where the
/// overlap would be: a bind's own trait is parameterised by the dialect, so a generic header there
/// would reach the framework's rows for a backend that is not an `sqlx::Database`. Nothing is
/// generic over `Timebase` here, so there is no row for this one to meet.
impl<'a, R: sqlx::Row> Assemble<'a, R> for Timebase
where
  i64: Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    Ok(Self {
      num: assembled(row, FieldName::new("num"), under)?,
      den: assembled(row, FieldName::new("den"), under)?,
    })
  }
}

/// The decodes, in the SHAPE THE EMITTER WRITES: one uniform spelling per field, judging nothing
/// about width, with `flatten` selecting the entry point that lends no name.
///
/// They are what an `#[ingraph::record(…)]` expansion produces for the same two declarations —
/// proved on that side by `ingraph-codegen`'s golden and by `ingraph-derive`'s live fixture. Written
/// out here because this crate cannot run its own derive, and the point of the pair is the SAME one
/// the `COLUMNS` twins above make: the two rows differ in one entry and in nothing else.
macro_rules! decode {
  ($row:ty, $tb:expr) => {
    impl<'a, R: sqlx::Row> sqlx::FromRow<'a, R> for $row
    where
      i64: Assemble<'a, R>,
      Timebase: Assemble<'a, R>,
    {
      fn from_row(__row: &'a R) -> sqlx::Result<Self> {
        let id: i64 = assembled(__row, FieldName::new("id"), None)?;
        let tb: Timebase = $tb(__row)?;
        Ok(Self { id, tb })
      }
    }
  };
}

decode!(TakeRow, |row| assembled(row, FieldName::new("tb"), None));
decode!(FlattenedRow, |row| assembled_flattened(row, None));

/// **THE ROUND TRIP, LIVE.** The table is CREATED from the descriptor, the record is written through
/// the write lane, and it is read back through the read lane — so `tb_num` is spelled by the DDL, by
/// the `INSERT`, by the `SELECT` and by the decode, and no two of those may disagree.
///
/// What this catches and a rendered golden cannot: a `CREATE TABLE` and an `INSERT` that flatten
/// under different rules, an engine that will not take three values for what the row calls two
/// fields, and a decode reading a column the statement never asked for.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_flattened_composite_makes_the_whole_round_trip() {
  use sqlx::Connection as _;

  use crate::{
    TypeVisitor as _,
    query::sql::{Create, get, insert},
  };

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  let mut create = Create::<sqlx::Sqlite>::new();
  create
    .next_type::<Take>()
    .expect("this descriptor renders for SQLite");
  create.run(&mut db).await.expect("and the engine takes it");

  insert::<TakeRow, sqlx::Sqlite, _>(&mut db, take())
    .await
    .expect("three values for two fields");

  assert_eq!(
    get::<TakeRow, sqlx::Sqlite, _>(&mut db, &7, false)
      .await
      .expect("the record is there"),
    Some(take()),
    "two columns back into one field"
  );

  // The columns really are two, under the names the shapes joined — read outside the engine's own
  // vocabulary so that the claim is about the TABLE and not about this crate's rendering.
  let (num, den): (i64, i64) =
    sqlx::query_as(r#"SELECT "tb_num", "tb_den" FROM "take" WHERE "id" = 7"#)
      .fetch_one(&mut db)
      .await
      .expect("the flattened columns are what the schema holds");
  assert_eq!((num, den), (24_000, 1_001));
}

/// **The seam reads what a hand-written decode reads.** The decodes above are the emitter's spelling
/// — one uniform entry per field, the segments joined by the walk — and this is what they replaced:
/// the two columns named as literals, filled into the composite by hand.
///
/// Both are run against ONE row, so a drift between them is a disagreement about a value and not
/// about two fixtures. That is what makes the replacement a measurement rather than a claim: an
/// `assembled` that joined `tbnum`, or descended in the wrong order, comes back different or comes
/// back an error, and either way this fails.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_emitted_spelling_reads_what_a_hand_written_decode_reads() {
  use sqlx::{Connection as _, FromRow as _, Row as _};

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  for statement in [
    r#"CREATE TABLE "take" ("id" INTEGER, "tb_num" INTEGER, "tb_den" INTEGER)"#,
    r#"INSERT INTO "take" VALUES (7, 24000, 1001)"#,
  ] {
    sqlx::query(statement)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
  }
  // The columns come back in an order the row does not declare, which a POSITIONAL decode would pass
  // while transposing: all three are integers.
  let row = sqlx::query(r#"SELECT "tb_den", "id", "tb_num" FROM "take""#)
    .fetch_one(&mut db)
    .await
    .expect("one row");

  let by_hand = TakeRow {
    id: row.try_get("id").expect("the id column"),
    tb: Timebase {
      num: row.try_get("tb_num").expect("the first flattened column"),
      den: row.try_get("tb_den").expect("the second"),
    },
  };
  assert_eq!(
    TakeRow::from_row(&row).expect("the seam decodes"),
    by_hand,
    "the walk joined `tb_num` and `tb_den`, in that order"
  );
}

/// **And `flatten` is the same declaration one word apart on the READ side too**: the row is
/// identical, the entry point is the one that lends no name, and the columns it asks for are bare.
///
/// The table carries `num`/`den` and NOT `tb_num`/`tb_den`, so a decode that kept the prefix is
/// `ColumnNotFound` rather than a subtly different value — which is what makes the word's effect
/// attributable here as it is in the rendered statements above.
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_flattened_decode_asks_for_the_bare_columns() {
  use sqlx::{Connection as _, FromRow as _};

  let mut db = sqlx::sqlite::SqliteConnection::connect("sqlite::memory:")
    .await
    .expect("an in-memory database");
  for statement in [
    r#"CREATE TABLE "flattened" ("id" INTEGER, "num" INTEGER, "den" INTEGER)"#,
    r#"INSERT INTO "flattened" VALUES (7, 24000, 1001)"#,
  ] {
    sqlx::query(statement)
      .execute(&mut db)
      .await
      .expect("the fixture's own DDL");
  }
  let row = sqlx::query(r#"SELECT * FROM "flattened""#)
    .fetch_one(&mut db)
    .await
    .expect("one row");

  let flattened = FlattenedRow::from_row(&row).expect("the flattened seam decodes");
  assert_eq!(
    (flattened.id, flattened.tb),
    (
      7,
      Timebase {
        num: 24_000,
        den: 1_001
      }
    )
  );
  assert!(
    TakeRow::from_row(&row).is_err(),
    "and the prefixed spelling finds nothing in this table"
  );
}