@fabrika/db 0.9.0-dev.17 → 0.9.0-dev.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -39,7 +39,7 @@ export interface WorldRow {
39
39
  * share link's chain is this list.
40
40
  */
41
41
  readonly chain: readonly { readonly type: string; readonly value: string }[]
42
- /** The row's values of the policy's update columns, as seeded. */
42
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
43
43
  readonly updates: Readonly<Record<string, SampleValue>>
44
44
  /**
45
45
  * The distinct value written into every text column the fixture filled itself, in this row and in its containers.
@@ -56,7 +56,7 @@ export interface WorldRow {
56
56
  /** One seeded row of an application table, which lies in no dimension. */
57
57
  export interface ApplicationRow {
58
58
  readonly key: string
59
- /** The row's values of the policy's update columns, as seeded. */
59
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
60
60
  readonly updates: Readonly<Record<string, SampleValue>>
61
61
  /** The distinct value written into every text column the fixture filled itself. */
62
62
  readonly markers: readonly string[]
@@ -83,14 +83,33 @@ export interface SeededRow {
83
83
  }
84
84
 
85
85
  /**
86
- * What the isolation fixture cannot seed for a schema: a CHECK its values fail, a required foreign key to a scoped table
87
- * outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
88
- * failure of the handler or the policy a case is about.
86
+ * What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
87
+ * foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
88
+ * column, never a failure of the handler or the policy a case is about.
89
89
  */
90
90
  export class SeedLimitError extends Error {
91
91
  override readonly name = 'SeedLimitError'
92
92
  }
93
93
 
94
+ /** The constraint a seeded row failed, as a backend reads it off the database's error. */
95
+ export interface Violation {
96
+ readonly kind: 'check' | 'unique' | 'foreign'
97
+ /** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
98
+ readonly name: string
99
+ /** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
100
+ readonly columns?: readonly string[]
101
+ }
102
+
103
+ /** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
104
+ export class ConstraintLimitError extends SeedLimitError {
105
+ readonly violation: Violation
106
+
107
+ constructor(message: string, violation: Violation) {
108
+ super(message)
109
+ this.violation = violation
110
+ }
111
+ }
112
+
94
113
  /** One row of a table in each of two containment chains that share no value. */
95
114
  export interface IsolationWorlds {
96
115
  /**
@@ -197,8 +216,12 @@ export interface SeedColumn {
197
216
  readonly number: boolean
198
217
  /** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
199
218
  readonly json: boolean
200
- /** A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it cannot fill. */
201
- readonly sample: () => Primitive
219
+ /**
220
+ * A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
221
+ * cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
222
+ * day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
223
+ */
224
+ readonly sample: (variant: number) => Primitive
202
225
  }
203
226
 
204
227
  /** A CHECK constraint of the schema, by the columns it names. */
@@ -207,9 +230,14 @@ export interface CheckConstraint {
207
230
  readonly table: string
208
231
  readonly columns: readonly string[]
209
232
  /** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
210
- readonly values: readonly string[]
233
+ readonly values: readonly CheckLiteral[]
234
+ /** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
235
+ readonly literals: readonly CheckLiteral[]
211
236
  }
212
237
 
238
+ /** A literal of a CHECK expression. */
239
+ export type CheckLiteral = string | number
240
+
213
241
  /**
214
242
  * A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
215
243
  * plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
@@ -279,34 +307,39 @@ export interface SeedingBackend {
279
307
  }
280
308
 
281
309
  /** The seed limit of a CHECK a seeded row fails. */
282
- export function checkLimit(constraint: string, table: string): SeedLimitError {
283
- return new SeedLimitError(
284
- `the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}: it writes a text marker or a sample of the type there; give the column an IN list, a default, or make it nullable`,
310
+ export function checkLimit(constraint: string, table: string): ConstraintLimitError {
311
+ return new ConstraintLimitError(
312
+ `the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}: no row it tried passes it (the values the CHECK names, null where a column admits it, samples of each type, fresh referenced rows)`,
313
+ { kind: 'check', name: constraint },
285
314
  )
286
315
  }
287
316
 
288
317
  /** The seed limit of a foreign key a seeded row breaks. */
289
- export function foreignKeyLimit(constraint: string, table: string): SeedLimitError {
290
- return new SeedLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`)
318
+ export function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError {
319
+ return new ConstraintLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`, {
320
+ kind: 'foreign',
321
+ name: constraint,
322
+ })
291
323
  }
292
324
 
293
325
  /** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
294
326
  export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
295
327
  return new SeedLimitError(
296
- `the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value; give the column a default or make it nullable`,
328
+ `the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value`,
297
329
  )
298
330
  }
299
331
 
300
332
  /** The seed limit of a row whose values another row of the table already holds under a unique index. */
301
- export function uniqueValueLimit(index: string, table: string): SeedLimitError {
302
- return new SeedLimitError(
303
- `the isolation fixture cannot satisfy the unique index ${index} of ${table}: it writes a sample of each column's type there, which another row holds; give a column of it a default, or make it nullable`,
333
+ export function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError {
334
+ return new ConstraintLimitError(
335
+ `the isolation fixture cannot satisfy the unique index ${index} of ${table}: every row it tried holds values another row holds there (samples of each type, the values a CHECK names, fresh referenced rows)`,
336
+ columns === undefined ? { kind: 'unique', name: index } : { kind: 'unique', name: index, columns },
304
337
  )
305
338
  }
306
339
 
307
340
  /** The seed limit of a required column whose type the fixture has no sample of. */
308
341
  export function typeLimit(table: string, column: string, type: string): SeedLimitError {
309
- return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}); give the column a default or make it nullable`)
342
+ return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}): it has no sample of that type`)
310
343
  }
311
344
 
312
345
  /**
@@ -341,6 +374,14 @@ function applicationRowError(refusal: ApplicationRowRefusal): Error {
341
374
  }
342
375
 
343
376
  /** A key value as the database returned it, for the foreign key that references it. */
377
+ /** `value` as the fixture can write it back, or `undefined` when it is none it writes (a JSON object, bytes). */
378
+ function plainValue(value: unknown): SampleValue | undefined {
379
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
380
+ return value
381
+ }
382
+ return value instanceof Date ? value : undefined
383
+ }
384
+
344
385
  function keyValue(value: unknown, where: string): SampleValue {
345
386
  if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
346
387
  return value
@@ -395,7 +436,124 @@ function ownerOf(models: TableModels, dimension: string): TableModel | undefined
395
436
  }
396
437
 
397
438
  /** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
398
- const MAX_REFERENCE_DEPTH = 4
439
+ const MAX_REFERENCE_DEPTH = 16
440
+ /** How many rows the fixture tries for one insert before it reports the last constraint they failed. */
441
+ const MAX_ROW_ATTEMPTS = 64
442
+ /** How many samples of its type the fixture tries in a column whose values a constraint may refuse. */
443
+ const SAMPLE_VARIANTS = 4
444
+
445
+ /** One way to fill a slot of a row: its values, given the row so far; a `SeedLimitError` when it has none. */
446
+ interface SlotOption {
447
+ /** It reads the row's other values (a number a unique index numbers within its group), so it is taken last and never kept. */
448
+ readonly grouped: boolean
449
+ readonly values: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>
450
+ }
451
+
452
+ /**
453
+ * Columns the fixture fills together (one column, or a foreign key's open columns) and the ways it may fill them, first
454
+ * first. `reads` are the columns of the row its options read, which other slots fill first.
455
+ */
456
+ interface Slot {
457
+ readonly columns: readonly string[]
458
+ readonly options: readonly SlotOption[]
459
+ readonly reads?: readonly string[]
460
+ }
461
+
462
+ /**
463
+ * An option computed once for each value of `reads` in the row: a fresh referenced row is inserted once for the values
464
+ * it shares with the row, and again only when they change.
465
+ */
466
+ function keptOption(
467
+ compute: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>,
468
+ reads: readonly string[] = [],
469
+ ): SlotOption {
470
+ const computed = new Map<string, Promise<ReadonlyMap<string, SampleValue>>>()
471
+ return {
472
+ grouped: false,
473
+ values: (row) => {
474
+ const key = reads.map((name) => valueKey(row.get(name) ?? null)).join('\u0000')
475
+ const values = computed.get(key) ?? compute(row)
476
+ computed.set(key, values)
477
+ return values
478
+ },
479
+ }
480
+ }
481
+
482
+ function valueKey(value: SampleValue): string {
483
+ if (value === null) return 'null'
484
+ return `${typeof value}:${value instanceof Date ? value.toISOString() : String(value)}`
485
+ }
486
+
487
+ /**
488
+ * The order the fixture fills `slots` in: a slot after the slots that fill the columns it reads, and a slot that numbers
489
+ * within the row's group last, once every other slot placed the row. A cycle keeps the declared order.
490
+ */
491
+ function slotOrder(slots: readonly Slot[]): number[] {
492
+ const filledBy = new Map<string, number>()
493
+ slots.forEach((slot, index) => {
494
+ for (const name of slot.columns) filledBy.set(name, index)
495
+ })
496
+ const grouped = (index: number): boolean => slots[index]?.options.some((option) => option.grouped) ?? false
497
+ const pending = [...slots.keys()].sort((left, right) => Number(grouped(left)) - Number(grouped(right)))
498
+ const order: number[] = []
499
+ while (pending.length > 0) {
500
+ const ready = pending.findIndex((index) =>
501
+ (slots[index]?.reads ?? []).every((name) => {
502
+ const filler = filledBy.get(name)
503
+ return filler === undefined || filler === index || order.includes(filler)
504
+ })
505
+ )
506
+ const [next] = pending.splice(Math.max(ready, 0), 1)
507
+ if (next !== undefined) order.push(next)
508
+ }
509
+ return order
510
+ }
511
+
512
+ function valueOption(name: string, value: SampleValue): SlotOption {
513
+ return { grouped: false, values: async () => new Map([[name, value]]) }
514
+ }
515
+
516
+ /** The values a literal of a CHECK suggests for `column`: a number and its neighbours in a number column, a text in a text column. */
517
+ function literalValues(column: SeedColumn, literal: CheckLiteral): SampleValue[] {
518
+ if (column.number) return typeof literal === 'number' && Number.isSafeInteger(literal) ? [literal, literal + 1, literal - 1] : []
519
+ return column.text && typeof literal === 'string' ? [literal] : []
520
+ }
521
+
522
+ /** The first usable option of `slot` from `choice[index]` on, which `choice` then records; `undefined` when none is. */
523
+ async function pickOption(
524
+ slot: Slot,
525
+ choice: number[],
526
+ index: number,
527
+ row: ReadonlyMap<string, SampleValue>,
528
+ ): Promise<{ readonly values: ReadonlyMap<string, SampleValue> } | { readonly error: SeedLimitError }> {
529
+ let refused: SeedLimitError | undefined
530
+ for (let at = choice[index] ?? 0; at < slot.options.length; at++) {
531
+ const option = slot.options[at]
532
+ if (option === undefined) continue
533
+ try {
534
+ const values = await option.values(row)
535
+ choice[index] = at
536
+ return { values }
537
+ } catch (error) {
538
+ if (!(error instanceof SeedLimitError)) throw error
539
+ refused = error
540
+ }
541
+ }
542
+ return { error: refused ?? new SeedLimitError('the isolation fixture has no value to try') }
543
+ }
544
+
545
+ /** The next combination of the `involved` slots' options, the first involved changing first; `false` once all were tried. */
546
+ function advanceChoice(slots: readonly Slot[], choice: number[], involved: readonly number[]): boolean {
547
+ for (const index of involved) {
548
+ const at = choice[index] ?? 0
549
+ if (at + 1 < (slots[index]?.options.length ?? 0)) {
550
+ choice[index] = at + 1
551
+ return true
552
+ }
553
+ choice[index] = 0
554
+ }
555
+ return false
556
+ }
399
557
  /** The digest of the empty object a seeded file stands for. */
400
558
  const EMPTY_SHA256 = createHash('sha256').digest('hex')
401
559
 
@@ -446,17 +604,22 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
446
604
  * and the number 1, which a bounded CHECK passes as before. A key column `row` holds no value for yet is left out of
447
605
  * the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
448
606
  */
449
- async function nextNumberOf(table: string, column: SeedColumn, row: ReadonlyMap<string, SampleValue>): Promise<SampleValue> {
607
+ async function nextNumberOf(
608
+ table: string,
609
+ column: SeedColumn,
610
+ row: ReadonlyMap<string, SampleValue>,
611
+ ungrouped: ReadonlySet<string> = new Set(),
612
+ ): Promise<SampleValue> {
450
613
  const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
451
614
  const groups: Map<string, SampleValue>[] = []
452
615
  for (const index of covering) {
453
616
  const group = new Map<string, SampleValue>()
454
617
  for (const other of index.columns) {
455
- if (other !== column.name && row.has(other)) group.set(other, row.get(other) ?? null)
618
+ if (other !== column.name && row.has(other) && !ungrouped.has(other)) group.set(other, row.get(other) ?? null)
456
619
  }
457
620
  if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
458
621
  }
459
- if (groups.length === 0) return column.sample()
622
+ if (groups.length === 0) return column.sample(0)
460
623
  const next = await backend.nextNumber(table, column.name, groups)
461
624
  if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
462
625
  return next
@@ -466,28 +629,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
466
629
  async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
467
630
  const checked = await checkedValue(table, column)
468
631
  if (checked !== undefined) return checked
469
- return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample()
470
- }
471
-
472
- /**
473
- * Writes into `row` a value for each of `columns`: `chosen`'s (a file, a CHECK's value, a marker, a null), else, for a
474
- * number a unique index covers, its next number once every other column places the row in its group, else a sample
475
- * of its type.
476
- */
477
- async function fillRow(
478
- table: string,
479
- columns: readonly SeedColumn[],
480
- row: Map<string, SampleValue>,
481
- chosen: (column: SeedColumn) => Promise<SampleValue | undefined>,
482
- ): Promise<void> {
483
- const later: SeedColumn[] = []
484
- for (const column of columns) {
485
- const value = await chosen(column)
486
- if (value !== undefined) row.set(column.name, value)
487
- else if (await numbered(table, column)) later.push(column)
488
- else row.set(column.name, column.sample())
489
- }
490
- for (const column of later) row.set(column.name, await nextNumberOf(table, column, row))
632
+ return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample(0)
491
633
  }
492
634
 
493
635
  function columnsOf(table: string): readonly SeedColumn[] {
@@ -518,46 +660,133 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
518
660
  return isMarkable(column) && !keyed && (await checksOn(table, column.name)).length === 0
519
661
  }
520
662
 
663
+ /** The open columns of `key` as the referenced row holds them. */
664
+ function keyValues(key: ForeignKey, open: readonly string[], row: Readonly<Record<string, unknown>>): Map<string, SampleValue> {
665
+ const values = new Map<string, SampleValue>()
666
+ key.columns.forEach((name, index) => {
667
+ const referenced = key.references[index] ?? ''
668
+ if (open.includes(name)) values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
669
+ })
670
+ return values
671
+ }
672
+
521
673
  /**
522
- * The values of a foreign key outside the containment chain: `null` where every open column admits it, else the
523
- * key of a row of the referenced table, an existing one (a reference table's rows come from a migration) or one the
524
- * fixture inserts, which `inserted` records when given. A required key to a dimension or child table is refused: its
525
- * row would lie in another chain.
674
+ * The ways to fill a foreign key outside the containment chain: `null` where every open column admits it, an existing
675
+ * row of an unscoped table (a reference table's rows come from a migration), and a row the fixture inserts, which
676
+ * `inserted` records when given. A row of a dimension or child table is always a fresh one: an existing one lies in
677
+ * another chain. The key's columns the row already holds (a tenant-holding key's ancestors) the referenced row holds too.
526
678
  */
527
- async function referencedKey(
679
+ async function referenceSlot(
528
680
  models: TableModels,
529
681
  table: string,
530
682
  key: ForeignKey,
531
683
  open: readonly string[],
684
+ assigned: ReadonlyMap<string, SampleValue>,
532
685
  depth: number,
533
686
  inserted?: InsertedRow[],
534
- ) {
687
+ ): Promise<Slot> {
535
688
  const columns = columnsOf(table)
536
- const values = new Map<string, SampleValue>()
689
+ const options: SlotOption[] = []
537
690
  if (open.every((name) => columns.find((column) => column.name === name)?.nullable === true)) {
538
- for (const name of open) values.set(name, null)
539
- return values
691
+ options.push({ grouped: false, values: async () => new Map(open.map((name) => [name, null])) })
692
+ }
693
+ // The key's columns the row holds already, or another slot fills first (a column two keys share), as the referenced
694
+ // row names them.
695
+ const shared = key.columns.filter((name) => !open.includes(name))
696
+ const fixedOf = (row: ReadonlyMap<string, SampleValue>): Map<string, SampleValue> => {
697
+ const fixed = new Map<string, SampleValue>()
698
+ key.columns.forEach((name, index) => {
699
+ if (shared.includes(name)) fixed.set(key.references[index] ?? '', row.get(name) ?? null)
700
+ })
701
+ return fixed
540
702
  }
541
703
  const target = modelOf(models, key.table)
542
704
  const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
543
- if (scoped || open.length !== key.columns.length || key.table === table || depth >= MAX_REFERENCE_DEPTH) {
705
+ const refused = key.table === table
706
+ ? 'which references its own table'
707
+ : depth >= MAX_REFERENCE_DEPTH
708
+ ? `whose referenced rows nest deeper than ${MAX_REFERENCE_DEPTH}`
709
+ : undefined
710
+ if (refused === undefined) {
711
+ if (!scoped) {
712
+ options.push(keptOption(async (row) => {
713
+ const existing = await backend.firstRow(key.table, key.references, fixedOf(row))
714
+ if (existing === undefined) throw new SeedLimitError(`the isolation fixture finds no row of ${key.table} to reference`)
715
+ return keyValues(key, open, existing)
716
+ }, shared))
717
+ }
718
+ options.push(keptOption(async (row) => keyValues(key, open, await freshRow(models, key, fixedOf(row), depth + 1, inserted)), shared))
719
+ }
720
+ if (options.length === 0) {
544
721
  throw new SeedLimitError(
545
- `the isolation fixture cannot fill ${table}.${
546
- open.join(', ')
547
- }: a required foreign key to ${key.table} outside the containment chain; give the column a default or make it nullable`,
722
+ `the isolation fixture cannot fill ${table}.${open.join(', ')}: a required foreign key to ${key.table} outside the containment chain, ${refused}`,
548
723
  )
549
724
  }
550
- const existing = await backend.firstRow(key.table, key.references)
551
- const row = existing ?? (await insert(models, key.table, new Map(), [], depth + 1, inserted)).stored
552
- const match = new Map<string, SampleValue>()
553
- key.columns.forEach((name, index) => {
554
- const referenced = key.references[index] ?? ''
555
- const value = keyValue(row[referenced], `${key.table}.${referenced}`)
556
- values.set(name, value)
557
- match.set(referenced, value)
558
- })
559
- if (existing === undefined) inserted?.push({ table: key.table, match })
560
- return values
725
+ return { columns: open, options, reads: shared.filter((name) => !assigned.has(name)) }
726
+ }
727
+
728
+ /**
729
+ * Gives each dimension of `model`'s chain that `values` lacks a fresh value, and inserts the row of each such
730
+ * container a table owns, outermost first; `inserted` records them when given.
731
+ */
732
+ async function placeContainers(
733
+ models: TableModels,
734
+ model: TableModel,
735
+ values: Map<string, string>,
736
+ world: string,
737
+ depth: number,
738
+ inserted?: InsertedRow[],
739
+ ): Promise<void> {
740
+ for (let index = model.chain.length - 1; index >= 0; index--) {
741
+ const link = model.chain[index]
742
+ if (link === undefined || values.has(link.dimension)) continue
743
+ const value = scopeValue(model.name, link.column, link.dimension, world)
744
+ values.set(link.dimension, value)
745
+ const owner = ownerOf(models, link.dimension)
746
+ if (owner === undefined || owner.name === model.name || owner.scope.mode !== 'dimension') continue
747
+ await insert(models, owner.name, placement(owner, values, value), [], depth, inserted)
748
+ inserted?.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
749
+ }
750
+ }
751
+
752
+ /**
753
+ * A fresh row of the table `key` references, holding `fixed` (referenced column → value), as stored. A row of a dimension
754
+ * or child table lies in the chain `fixed` holds of it, else in fresh values with containers of its own.
755
+ */
756
+ async function freshRow(
757
+ models: TableModels,
758
+ key: ForeignKey,
759
+ fixed: ReadonlyMap<string, SampleValue>,
760
+ depth: number,
761
+ inserted?: InsertedRow[],
762
+ ): Promise<Readonly<Record<string, unknown>>> {
763
+ const target = modelOf(models, key.table)
764
+ const scope = target?.scope
765
+ if (target === undefined || scope === undefined || (scope.mode !== 'dimension' && scope.mode !== 'child')) {
766
+ const { stored } = await insert(models, key.table, fixed, [], depth, inserted)
767
+ inserted?.push({
768
+ table: key.table,
769
+ match: new Map(key.references.map((name) => [name, keyValue(stored[name], `${key.table}.${name}`)])),
770
+ })
771
+ return stored
772
+ }
773
+ if (fixed.has(scope.key)) {
774
+ throw new SeedLimitError(`the isolation fixture cannot insert a row of ${key.table} whose key the referencing row fixes`)
775
+ }
776
+ const values = new Map<string, string>()
777
+ for (const link of target.chain) {
778
+ const value = fixed.get(link.column)
779
+ if (value !== undefined && value !== null) values.set(link.dimension, String(value))
780
+ }
781
+ await placeContainers(models, target, values, 'referenced', depth, inserted)
782
+ const rowKey = scopeValue(target.name, scope.key, scope.mode === 'dimension' ? scope.dimension : target.name, 'referenced')
783
+ const assigned = placement(target, values, rowKey)
784
+ for (const [name, value] of fixed) {
785
+ if (!assigned.has(name)) assigned.set(name, value)
786
+ }
787
+ const { stored } = await insert(models, target.name, assigned, [], depth, inserted)
788
+ inserted?.push({ table: target.name, match: new Map([[scope.key, rowKey]]) })
789
+ return stored
561
790
  }
562
791
 
563
792
  /** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
@@ -582,11 +811,74 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
582
811
  }
583
812
 
584
813
  /**
585
- * Inserts one row: `assigned` as given, a file column a seeded file, a foreign key outside the chain `null` or referencing a row, a column a CHECK
586
- * names its `IN` list's first value or `null`, every other text column a marker and every other required column a
587
- * sample. Answers what the fixture wrote, and the row as stored (its database defaults filled). A CHECK or a foreign
588
- * key the values still fail is a `SeedLimitError` that names the constraint. `inserted` records every row a foreign
589
- * key or a file column made it insert, not the row itself.
814
+ * The ways to fill `column`: a file column a seeded file; a column a CHECK names the `IN` list's first value or `null`,
815
+ * then every value the CHECKs naming it list or compare with, and samples of its type; a text column a marker; any other
816
+ * nullable column `null`; a number a unique index covers its next number in the row's group; else samples of its type.
817
+ */
818
+ async function columnSlot(
819
+ model: TableModel | undefined,
820
+ table: string,
821
+ column: SeedColumn,
822
+ markers: string[],
823
+ inserted: InsertedRow[] | undefined,
824
+ ungrouped: ReadonlySet<string>,
825
+ ): Promise<Slot> {
826
+ const name = column.name
827
+ const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
828
+ const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(column.sample(variant)) })
829
+ const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
830
+ const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
831
+ const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
832
+ if (kind !== undefined) {
833
+ return {
834
+ columns: [name],
835
+ options: [keptOption(async () => single(await seedFile(kind, inserted))), ...(column.nullable ? [valueOption(name, null)] : [])],
836
+ }
837
+ }
838
+ const named = await checksOn(table, name)
839
+ const isNumbered = await numbered(table, column)
840
+ if (named.length > 0) {
841
+ const checked = await checkedValue(table, column)
842
+ const first = checked === undefined ? (isNumbered ? next : sampled(0)) : valueOption(name, checked)
843
+ const tried: SampleValue[] = column.nullable ? [null] : []
844
+ for (const check of named) {
845
+ for (const literal of [...check.values, ...check.literals]) tried.push(...literalValues(column, literal))
846
+ }
847
+ const listed = [...new Set(tried)].filter((value) => value !== checked).map((value) => valueOption(name, value))
848
+ return { columns: [name], options: [first, ...listed, ...(isNumbered ? [next] : []), ...samples] }
849
+ }
850
+ if (await holdsMarker(model, table, column)) {
851
+ return {
852
+ columns: [name],
853
+ options: [keptOption(async () => {
854
+ const marker = `m${randomHex()}${randomHex()}`
855
+ markers.push(marker)
856
+ return single(marker)
857
+ })],
858
+ }
859
+ }
860
+ if (column.nullable) return { columns: [name], options: [valueOption(name, null)] }
861
+ return { columns: [name], options: isNumbered ? [next] : samples }
862
+ }
863
+
864
+ /** The columns of the constraint a row failed, or `undefined` when the seeding cannot tell (an index on an expression). */
865
+ async function violatedColumns(table: string, violation: Violation): Promise<readonly string[] | undefined> {
866
+ if (violation.columns !== undefined) return violation.columns
867
+ if (violation.kind === 'check') {
868
+ checks ??= backend.checks()
869
+ return (await checks).find((check) => check.table === table && check.name === violation.name)?.columns
870
+ }
871
+ return (await uniqueIndexesOf(table)).find((index) => index.name === violation.name)?.columns
872
+ }
873
+
874
+ /**
875
+ * Inserts one row: `assigned` as given, every other column a database default leaves open filled by its slot
876
+ * (`columnSlot`, `referenceSlot`), each slot's first option first. When the database refuses the row for a CHECK or
877
+ * a unique index, the fixture tries the next combination of the options of the slots that constraint names (all of
878
+ * them when it names none it can read), up to `MAX_ROW_ATTEMPTS` rows; the last refusal is the `SeedLimitError`.
879
+ * Answers what the fixture wrote, and the row as stored (its database defaults filled). `inserted` records every row
880
+ * a foreign key or a file column made it insert, not the row itself. A number a unique index covers is numbered within
881
+ * its group without the columns in `ungrouped` (a container the row will not lie in).
590
882
  */
591
883
  async function insert(
592
884
  models: TableModels,
@@ -595,39 +887,66 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
595
887
  markers: string[],
596
888
  depth = 0,
597
889
  inserted?: InsertedRow[],
890
+ ungrouped: ReadonlySet<string> = new Set(),
598
891
  ): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
599
892
  const model = modelOf(models, table)
600
893
  const columns = columnsOf(table)
601
- // A column with a database default keeps it unless the fixture assigned it, a foreign key's included.
894
+ // A column with a database default keeps it unless the fixture assigned it or fills a foreign key over it.
602
895
  const defaulted = new Set(columns.filter((column) => column.defaulted).map((column) => column.name))
603
- const keyed = new Map<string, SampleValue>()
896
+ const slots: Slot[] = []
897
+ const slotted = new Set<string>()
604
898
  for (const key of model?.foreignKeys ?? []) {
605
- const open = key.columns.filter((column) => !assigned.has(column) && !defaulted.has(column))
606
- if (open.length === 0) continue
607
- for (const [name, value] of await referencedKey(models, table, key, open, depth, inserted)) keyed.set(name, value)
899
+ const open = key.columns.filter((column) => !assigned.has(column) && !slotted.has(column))
900
+ // A key whose columns all have defaults keeps them; one the fixture fills fills its defaulted columns too, which
901
+ // alone may name no row the key's other columns pick.
902
+ if (open.every((column) => defaulted.has(column))) continue
903
+ slots.push(await referenceSlot(models, table, key, open, assigned, depth, inserted))
904
+ for (const name of open) slotted.add(name)
608
905
  }
609
- const row = new Map<string, SampleValue>()
610
- const open: SeedColumn[] = []
611
906
  for (const column of columns) {
612
- const name = column.name
613
907
  // An assigned `null` is the fixture's value too, never a gap to fill.
614
- const given = assigned.has(name) ? assigned : keyed.has(name) ? keyed : undefined
615
- if (given !== undefined) row.set(name, given.get(name) ?? null)
616
- else if (!column.defaulted) open.push(column)
908
+ if (assigned.has(column.name) || column.defaulted || slotted.has(column.name)) continue
909
+ slots.push(await columnSlot(model, table, column, markers, inserted, ungrouped))
617
910
  }
618
- await fillRow(table, open, row, async (column) => {
619
- const kind = model !== undefined && Object.hasOwn(model.files, column.name) ? model.files[column.name] : undefined
620
- if (kind !== undefined) return seedFile(kind, inserted)
621
- const checked = await checkedValue(table, column)
622
- if (checked !== undefined) return checked
623
- if (await holdsMarker(model, table, column)) {
624
- const marker = `m${randomHex()}${randomHex()}`
625
- markers.push(marker)
626
- return marker
911
+ const order = slotOrder(slots)
912
+ const choice = slots.map(() => 0)
913
+ const involved: number[] = []
914
+ // The refusal of the row the fixture prefers, which the error names once no other row passes.
915
+ let refused: SeedLimitError | undefined
916
+ for (let attempt = 0; attempt < MAX_ROW_ATTEMPTS; attempt++) {
917
+ const row = new Map(assigned)
918
+ let complete = true
919
+ for (const index of order) {
920
+ const slot = slots[index]
921
+ if (slot === undefined) continue
922
+ const picked = await pickOption(slot, choice, index, row)
923
+ if ('error' in picked) {
924
+ // No option of the slot is usable from its current one on: the next combination, or the reason.
925
+ if ((choice[index] ?? 0) === 0 || !involved.includes(index)) throw picked.error
926
+ refused ??= picked.error
927
+ complete = false
928
+ break
929
+ }
930
+ for (const [name, value] of picked.values) row.set(name, value)
627
931
  }
628
- return column.nullable ? null : undefined
629
- })
630
- return { row, stored: await backend.insert(table, row) }
932
+ if (complete) {
933
+ try {
934
+ return { row, stored: await backend.insert(table, row) }
935
+ } catch (error) {
936
+ if (!(error instanceof ConstraintLimitError) || error.violation.kind === 'foreign') throw error
937
+ refused ??= error
938
+ const named = await violatedColumns(table, error.violation)
939
+ const touched = [...slots.keys()].filter((index) => named === undefined || (slots[index]?.columns ?? []).some((name) => named.includes(name)))
940
+ // A constraint over the assigned columns only has nothing to try.
941
+ if (touched.length === 0) throw error
942
+ for (const index of touched) {
943
+ if (!involved.includes(index)) involved.push(index)
944
+ }
945
+ }
946
+ }
947
+ if (!advanceChoice(slots, choice, involved)) break
948
+ }
949
+ throw refused ?? new SeedLimitError(`the isolation fixture tried ${MAX_ROW_ATTEMPTS} rows of ${table}`)
631
950
  }
632
951
 
633
952
  /** The columns a model's row is placed by: its own key when it owns a dimension, and each link of its chain. */
@@ -770,7 +1089,12 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
770
1089
  pins: Readonly<Record<string, string>>,
771
1090
  scopes: ScopeValues,
772
1091
  inserted: InsertedRow[],
773
- ): Promise<{ readonly world: Omit<WorldRow, 'updates'>; readonly row: ReadonlyMap<string, SampleValue> }> {
1092
+ ): Promise<{
1093
+ readonly world: Omit<WorldRow, 'updates'>
1094
+ readonly row: ReadonlyMap<string, SampleValue>
1095
+ /** The row as stored, its defaults filled. */
1096
+ readonly holds: Readonly<Record<string, unknown>>
1097
+ }> {
774
1098
  const markers: string[] = []
775
1099
  const scope = model.scope
776
1100
  if (scope.mode !== 'dimension' && scope.mode !== 'child') {
@@ -786,7 +1110,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
786
1110
  if (own !== undefined) {
787
1111
  values.set(own, key)
788
1112
  }
789
- const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[]) => {
1113
+ const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[], holds: Readonly<Record<string, unknown>> = {}) => {
790
1114
  const chain = [
791
1115
  ...(own === undefined ? [] : [{ type: own, value: key }]),
792
1116
  ...links.flatMap((link) => {
@@ -802,7 +1126,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
802
1126
  markers,
803
1127
  stored,
804
1128
  }
805
- return { world: seeded, row }
1129
+ return { world: seeded, row, holds }
806
1130
  }
807
1131
  if (own !== undefined && stored.has(own)) {
808
1132
  if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
@@ -851,16 +1175,39 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
851
1175
  assigned.set(name, pinned)
852
1176
  markers.push(pinned)
853
1177
  }
854
- const { row } = await insert(models, model.name, assigned, markers)
1178
+ const { row, stored: holds } = await insert(models, model.name, assigned, markers, 0, inserted)
855
1179
  inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
856
- return worldRow(row, [])
1180
+ return worldRow(row, [], holds)
1181
+ }
1182
+
1183
+ /** `work`, after which a failure removes the rows it recorded in `inserted` before it rethrows. */
1184
+ async function removedOnFailure<T>(inserted: readonly InsertedRow[], what: string, work: () => Promise<T>): Promise<T> {
1185
+ try {
1186
+ return await work()
1187
+ } catch (error) {
1188
+ try {
1189
+ await backend.remove(inserted)
1190
+ } catch (cleanup) {
1191
+ throw new AggregateError([error, cleanup], `the isolation fixture could not ${what}, nor remove what it had seeded`)
1192
+ }
1193
+ throw error
1194
+ }
857
1195
  }
858
1196
 
859
- /** A seeded row's values of the policy's update columns: as written, or a sample where the database filled the column. */
860
- async function updatesOf(model: TableModel, row: ReadonlyMap<string, SampleValue>): Promise<Record<string, SampleValue>> {
1197
+ /**
1198
+ * A seeded row's values of the policy's update columns, which its CHECKs accepted: as written, as stored where the
1199
+ * database filled the column (a default), or a sample where the stored value is no plain value.
1200
+ */
1201
+ async function updatesOf(
1202
+ model: TableModel,
1203
+ row: ReadonlyMap<string, SampleValue>,
1204
+ stored: Readonly<Record<string, unknown>> = {},
1205
+ ): Promise<Record<string, SampleValue>> {
861
1206
  const updates: Record<string, SampleValue> = {}
862
1207
  for (const name of namesOf(model.update)) {
863
- updates[name] = row.get(name) ?? await updateSample(model.name, name)
1208
+ const written = row.get(name)
1209
+ const kept = written === undefined ? plainValue(stored[name]) : written
1210
+ updates[name] = kept === undefined ? await updateSample(model.name, name) : kept
864
1211
  }
865
1212
  return updates
866
1213
  }
@@ -890,8 +1237,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
890
1237
  // Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
891
1238
  return {
892
1239
  dimension,
893
- own: { ...own.world, updates: await updatesOf(model, own.row) },
894
- other: { ...other.world, updates: await updatesOf(model, other.row) },
1240
+ own: { ...own.world, updates: await updatesOf(model, own.row, own.holds) },
1241
+ other: { ...other.world, updates: await updatesOf(model, other.row, other.holds) },
895
1242
  remove: () => backend.remove(inserted),
896
1243
  }
897
1244
  },
@@ -899,8 +1246,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
899
1246
  const { models, model } = scopedModel(tables, table)
900
1247
  checkApplicationValues(models, { [table]: values })
901
1248
  const markers: string[] = []
902
- const { key, row } = await seedApplicationRow(models, model, values, new Map(), markers)
903
- return { key, updates: await updatesOf(model, row), markers }
1249
+ const { key, row, stored } = await seedApplicationRow(models, model, values, new Map(), markers)
1250
+ return { key, updates: await updatesOf(model, row, stored), markers }
904
1251
  },
905
1252
  async seedApplicationRows(tables, rows) {
906
1253
  const models = tableModels(tables)
@@ -953,35 +1300,34 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
953
1300
  const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
954
1301
  const markers: string[] = []
955
1302
  const inserted: InsertedRow[] = []
956
- await insert(models, table, placement(model, values, key), markers, 0, inserted)
1303
+ await removedOnFailure(inserted, 'seed the row', () => insert(models, table, placement(model, values, key), markers, 0, inserted))
957
1304
  inserted.push({ table, match: new Map([[scope.key, key]]) })
958
1305
  return { key, markers, remove: () => backend.remove(inserted) }
959
1306
  },
960
1307
  async sampleInsert(tables, table, beside) {
961
1308
  const { models, model } = scopedModel(tables, table)
962
- const values: Record<string, SampleValue> = {}
963
- const columns = columnsOf(table)
964
- const required = columns.filter((column) => inSet(model.insert, column.name) && isRequired(column))
965
- for (const key of model.foreignKeys) {
966
- const open = key.columns.filter((name) => required.some((column) => column.name === name))
967
- if (open.length === 0) continue
968
- for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
969
- }
970
- // The row as the insert will write it: in `beside`'s containers, which the handler places it in.
971
- const containers = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
972
- const row = new Map<string, SampleValue>()
973
- for (const link of model.chain) {
974
- const value = containers.get(link.dimension)
975
- if (value !== undefined) row.set(link.column, value)
1309
+ const scope = model.scope
1310
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
1311
+ throw new Error(`${table} is a ${scope.mode} table; no store inserts into it`)
976
1312
  }
977
- for (const [name, value] of Object.entries(values)) row.set(name, value)
978
- const open = required.filter((column) => !(column.name in values))
979
- await fillRow(table, open, row, async (column) => {
980
- const kind = Object.hasOwn(model.files, column.name) ? model.files[column.name] : undefined
981
- return kind === undefined ? checkedValue(table, column) : seedFile(kind)
1313
+ // A probe row the database judges, placed as the insert will place it (in `beside`'s containers, else in fresh
1314
+ // ones it removes with the probe), numbered within the containers known; its values are the sample.
1315
+ const values = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
1316
+ const ungrouped = new Set(model.chain.filter((link) => !values.has(link.dimension)).map((link) => link.column))
1317
+ const placed: InsertedRow[] = []
1318
+ const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'probe')
1319
+ const { row } = await removedOnFailure(placed, 'insert a probe row', async () => {
1320
+ await placeContainers(models, model, values, 'probe', 0, placed)
1321
+ return insert(models, table, placement(model, values, key), [], 0, undefined, ungrouped)
982
1322
  })
983
- for (const column of open) values[column.name] = row.get(column.name) ?? null
984
- return values
1323
+ await backend.remove([{ table, match: new Map([[scope.key, key]]) }, ...placed])
1324
+ const sample: Record<string, SampleValue> = {}
1325
+ for (const column of columnsOf(table)) {
1326
+ if (!inSet(model.insert, column.name) || !row.has(column.name)) continue
1327
+ // A nullable column a CHECK ties to another is written as the probe held it; any other is left to the insert.
1328
+ if (isRequired(column) || (await checksOn(table, column.name)).length > 0) sample[column.name] = row.get(column.name) ?? null
1329
+ }
1330
+ return sample
985
1331
  },
986
1332
  seededObjects: () => [...seededObjects],
987
1333
  }