@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.60

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.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +59 -11
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +55 -9
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +369 -147
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1933 -168
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +8 -1
  35. package/src/testing-shared.ts +758 -140
  36. package/src/testing-sqlite.ts +212 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +159 -27
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +31 -9
  47. package/types/src/errors.d.ts +7 -4
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +18 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +4 -0
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +165 -73
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +347 -23
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +4 -1
  70. package/types/src/testing-shared.d.ts +112 -23
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -7,6 +7,7 @@ import { type ApplicationRowRefusal, applicationRowRefusalText, type Application
7
7
  import { inSet, namesOf } from './builtins'
8
8
  import type { Database } from './database'
9
9
  import type { Primitive } from './description'
10
+ import { jsonInput } from './json'
10
11
  import { FILES_TABLE } from './migrations'
11
12
  import { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
12
13
  import { refuseInProduction } from './production'
@@ -16,6 +17,15 @@ import type { TableProbe } from './store'
16
17
  /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
17
18
  export type SampleValue = Primitive | null
18
19
 
20
+ /**
21
+ * A seeded value as a backend binds it: a JSON column's value as the JSON text the layer would write for it, so a
22
+ * seeded row and the kits' cases that write the same value through the layer hold the same JSON.
23
+ */
24
+ export function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): SampleValue {
25
+ if (value === null || !columns.some((column) => column.table === table && column.name === name && column.json)) return value
26
+ return jsonInput(value, `${table}.${name}`)
27
+ }
28
+
19
29
  /** One seeded row and where it lies. */
20
30
  export interface WorldRow {
21
31
  /** The row's key: the dimension value of a dimension table's row, a child's own key. */
@@ -29,19 +39,24 @@ export interface WorldRow {
29
39
  * share link's chain is this list.
30
40
  */
31
41
  readonly chain: readonly { readonly type: string; readonly value: string }[]
32
- /** 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. */
33
43
  readonly updates: Readonly<Record<string, SampleValue>>
34
44
  /**
35
45
  * The distinct value written into every text column the fixture filled itself, in this row and in its containers.
36
46
  * Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
37
47
  */
38
48
  readonly markers: readonly string[]
49
+ /**
50
+ * The values of the text columns of a row the table already held under a known scope value (`seedWorlds`' `scopes`),
51
+ * which no fixture wrote and other rows may share; empty for a row the fixture inserted.
52
+ */
53
+ readonly stored: readonly string[]
39
54
  }
40
55
 
41
56
  /** One seeded row of an application table, which lies in no dimension. */
42
57
  export interface ApplicationRow {
43
58
  readonly key: string
44
- /** 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. */
45
60
  readonly updates: Readonly<Record<string, SampleValue>>
46
61
  /** The distinct value written into every text column the fixture filled itself. */
47
62
  readonly markers: readonly string[]
@@ -63,17 +78,38 @@ export interface SeededApplicationRows {
63
78
  export interface SeededRow {
64
79
  readonly key: string
65
80
  readonly markers: readonly string[]
81
+ /** Deletes the row, the rows its foreign keys made the fixture insert, and every row that refers to them. */
82
+ readonly remove: () => Promise<void>
66
83
  }
67
84
 
68
85
  /**
69
- * What the isolation fixture cannot seed for a schema: a CHECK its values fail, a required foreign key to a scoped table
70
- * outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
71
- * 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.
72
89
  */
73
90
  export class SeedLimitError extends Error {
74
91
  override readonly name = 'SeedLimitError'
75
92
  }
76
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
+
77
113
  /** One row of a table in each of two containment chains that share no value. */
78
114
  export interface IsolationWorlds {
79
115
  /**
@@ -84,12 +120,19 @@ export interface IsolationWorlds {
84
120
  readonly own: WorldRow
85
121
  readonly other: WorldRow
86
122
  /**
87
- * Deletes both rows of the table and every row that refers to them, however deep; the containers stay. A case whose
88
- * rows hold pinned values removes them, so the next case can pin the same values again under a unique index.
123
+ * Deletes both rows of the table it inserted, every container row it inserted when it was given known scope values,
124
+ * and every row that refers to them, however deep; the other containers stay. A case whose rows hold pinned values or
125
+ * known scope values removes them, so the next case can seed the same values again under a unique index.
89
126
  */
90
127
  readonly remove: () => Promise<void>
91
128
  }
92
129
 
130
+ /**
131
+ * Known values of dimensions, by dimension: the own world's and the other world's, which differ. A dimension whose values
132
+ * are a fixed set (an enum the input names it by) takes these instead of fresh ones.
133
+ */
134
+ export type ScopeValues = Readonly<Record<string, { readonly own: string; readonly other: string }>>
135
+
93
136
  /** What a test kit seeds through, over its migrated schema. */
94
137
  export interface TestSeeding {
95
138
  /**
@@ -98,13 +141,17 @@ export interface TestSeeding {
98
141
  * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
99
142
  * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
100
143
  * counts among the other row's markers, so a leak of it is still found. A pin of a column that places the row, or of
101
- * no text column, throws.
144
+ * no text column, throws. `scopes` place each world in known values of a dimension instead of fresh ones: a row of
145
+ * the table that owns it with that key is used as it is stored (a migration wrote it), its containers' values with it,
146
+ * and is inserted otherwise. A stored row of `table` itself takes no `values` or `pins`: they throw. A seed that throws
147
+ * removes what it inserted.
102
148
  */
103
149
  seedWorlds<DB, P>(
104
150
  tables: Tables<DB, P>,
105
151
  table: string,
106
152
  values?: Readonly<Record<string, SampleValue>>,
107
153
  pins?: Readonly<Record<string, string>>,
154
+ scopes?: ScopeValues,
108
155
  ): Promise<IsolationWorlds>
109
156
  /**
110
157
  * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
@@ -123,13 +170,19 @@ export interface TestSeeding {
123
170
  rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>,
124
171
  ): Promise<SeededApplicationRows>
125
172
  /**
126
- * Seeds one row of `table`, a child or dimension table that lies in the object of `under` (a row `seedWorlds`
127
- * seeded), placed in that row's chain: the row a fixture names by id, such as a note's comment. Answers its key and
128
- * the markers it holds.
173
+ * Seeds one row of `table`, a child or dimension table that lies in the object `under`'s chain starts at (a row
174
+ * `seedWorlds` seeded, or a value of its chain with the values outside it), placed in that chain: the row a fixture
175
+ * names by id, such as a note's comment. Answers its key and the markers it holds.
129
176
  */
130
- seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: WorldRow): Promise<SeededRow>
131
- /** Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file column a seeded file. */
132
- sampleInsert<DB, P>(tables: Tables<DB, P>, table: string): Promise<Readonly<Record<string, SampleValue>>>
177
+ seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: Pick<WorldRow, 'chain'>): Promise<SeededRow>
178
+ /**
179
+ * Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
180
+ * column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
181
+ * containers. A number column a unique index covers takes the next number above the largest the table holds now in the
182
+ * row's group (the index's other columns as the row will have them, its containers' from `beside`), so insert the
183
+ * values before taking the next sample, or the two share it.
184
+ */
185
+ sampleInsert<DB, P>(tables: Tables<DB, P>, table: string, beside?: WorldRow): Promise<Readonly<Record<string, SampleValue>>>
133
186
  /**
134
187
  * The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
135
188
  * which a test's object store holds when a handler serves or opens the file.
@@ -159,8 +212,16 @@ export interface SeedColumn {
159
212
  readonly text: boolean
160
213
  /** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
161
214
  readonly uuid: boolean
162
- /** 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. */
163
- readonly sample: () => Primitive
215
+ /** A number type: where a unique index covers it, the fixture writes the next number of the row's group instead of its sample. */
216
+ readonly number: boolean
217
+ /** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
218
+ readonly json: boolean
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
164
225
  }
165
226
 
166
227
  /** A CHECK constraint of the schema, by the columns it names. */
@@ -169,7 +230,24 @@ export interface CheckConstraint {
169
230
  readonly table: string
170
231
  readonly columns: readonly string[]
171
232
  /** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
172
- 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[]
236
+ }
237
+
238
+ /** A literal of a CHECK expression. */
239
+ export type CheckLiteral = string | number
240
+
241
+ /**
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
243
+ * plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
244
+ */
245
+ export interface UniqueIndex {
246
+ readonly name: string
247
+ readonly table: string
248
+ readonly columns: readonly string[]
249
+ /** `NULLS NOT DISTINCT`: a null in a key column collides with another row's null there. */
250
+ readonly nullsNotDistinct: boolean
173
251
  }
174
252
 
175
253
  /** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
@@ -200,10 +278,25 @@ export interface SeedingBackend {
200
278
  readonly columns: readonly SeedColumn[]
201
279
  /** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
202
280
  checks(): Promise<readonly CheckConstraint[]>
203
- /** Inserts one row and answers it as stored; a CHECK or foreign key it fails is a `SeedLimitError` (`checkLimit`, `foreignKeyLimit`). */
281
+ /** Every unique index of plain columns and no predicate of the schema's tables; read once, on the first column that needs them. */
282
+ uniqueIndexes(): Promise<readonly UniqueIndex[]>
283
+ /**
284
+ * The smallest whole number above every value `column` holds in the rows of `table` that match one of `groups`
285
+ * (`groupsWhere`), and at least 1, as the column's type holds it; `undefined` when the type holds no such number, or
286
+ * the largest is no finite number.
287
+ */
288
+ nextNumber(table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): Promise<Primitive | undefined>
289
+ /**
290
+ * Inserts one row and answers it as stored; a CHECK, foreign key or unique index it fails is a `SeedLimitError`
291
+ * (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
292
+ */
204
293
  insert(table: string, values: ReadonlyMap<string, SampleValue>): Promise<Readonly<Record<string, unknown>>>
205
- /** One row of `table`, of `columns`, or `undefined` when it has none. */
206
- firstRow(table: string, columns: readonly string[]): Promise<Readonly<Record<string, unknown>> | undefined>
294
+ /** One row of `table` that holds `where` (column → value; every row when empty), of `columns`, or `undefined` when none does. */
295
+ firstRow(
296
+ table: string,
297
+ columns: readonly string[],
298
+ where?: ReadonlyMap<string, SampleValue>,
299
+ ): Promise<Readonly<Record<string, unknown>> | undefined>
207
300
  insertFile(file: SeededFile): Promise<void>
208
301
  /**
209
302
  * Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
@@ -214,20 +307,60 @@ export interface SeedingBackend {
214
307
  }
215
308
 
216
309
  /** The seed limit of a CHECK a seeded row fails. */
217
- export function checkLimit(constraint: string, table: string): SeedLimitError {
218
- return new SeedLimitError(
219
- `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 },
220
314
  )
221
315
  }
222
316
 
223
317
  /** The seed limit of a foreign key a seeded row breaks. */
224
- export function foreignKeyLimit(constraint: string, table: string): SeedLimitError {
225
- 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
+ })
323
+ }
324
+
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. */
326
+ export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
327
+ return new SeedLimitError(
328
+ `the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value`,
329
+ )
330
+ }
331
+
332
+ /** The seed limit of a row whose values another row of the table already holds under a unique index. */
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 },
337
+ )
226
338
  }
227
339
 
228
340
  /** The seed limit of a required column whose type the fixture has no sample of. */
229
341
  export function typeLimit(table: string, column: string, type: string): SeedLimitError {
230
- 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`)
343
+ }
344
+
345
+ /**
346
+ * A condition that matches a row holding every value of one of `groups` (column → value, `null` matched by `IS NULL`; an
347
+ * empty group matches every row, no group none), in the dialect's quoting and placeholders, with the values it binds.
348
+ */
349
+ export function groupsWhere(
350
+ groups: readonly ReadonlyMap<string, SampleValue>[],
351
+ quote: (identifier: string) => string,
352
+ placeholder: (position: number) => string,
353
+ ): { where: string; values: SampleValue[] } {
354
+ const values: SampleValue[] = []
355
+ const each = groups.map((group) => {
356
+ const terms = [...group].map(([column, value]) => {
357
+ if (value === null) return `${quote(column)} IS NULL`
358
+ values.push(value)
359
+ return `${quote(column)} = ${placeholder(values.length)}`
360
+ })
361
+ return terms.length === 0 ? 'TRUE' : `(${terms.join(' AND ')})`
362
+ })
363
+ return { where: each.length === 0 ? 'FALSE' : each.join(' OR '), values }
231
364
  }
232
365
 
233
366
  export function randomHex(): string {
@@ -241,6 +374,14 @@ function applicationRowError(refusal: ApplicationRowRefusal): Error {
241
374
  }
242
375
 
243
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
+
244
385
  function keyValue(value: unknown, where: string): SampleValue {
245
386
  if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
246
387
  return value
@@ -278,6 +419,9 @@ function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly mo
278
419
  if (model === undefined) {
279
420
  throw new Error(`${table} is not a table of the policies`)
280
421
  }
422
+ if (model.view) {
423
+ throw new Error(`${table} is a view, whose rows come from the tables it reads: seed those instead`)
424
+ }
281
425
  return { models, model }
282
426
  }
283
427
 
@@ -292,7 +436,124 @@ function ownerOf(models: TableModels, dimension: string): TableModel | undefined
292
436
  }
293
437
 
294
438
  /** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
295
- 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
+ }
296
557
  /** The digest of the empty object a seeded file stands for. */
297
558
  const EMPTY_SHA256 = createHash('sha256').digest('hex')
298
559
 
@@ -305,6 +566,7 @@ export const SEEDED_OBJECT_VERSION = '"seeded"'
305
566
  /** The isolation fixtures over the schema `backend` describes. */
306
567
  export function testSeeding(backend: SeedingBackend): TestSeeding {
307
568
  let checks: Promise<readonly CheckConstraint[]> | undefined
569
+ let uniqueIndexes: Promise<readonly UniqueIndex[]> | undefined
308
570
  const seededObjects: string[] = []
309
571
 
310
572
  /** The CHECK constraints that name `column` of `table`. */
@@ -325,9 +587,49 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
325
587
  return column.nullable ? null : undefined
326
588
  }
327
589
 
328
- /** A required column's sample: an `IN` list's first value where a CHECK names one, else a sample of its type. */
590
+ async function uniqueIndexesOf(table: string): Promise<readonly UniqueIndex[]> {
591
+ uniqueIndexes ??= backend.uniqueIndexes()
592
+ return (await uniqueIndexes).filter((index) => index.table === table)
593
+ }
594
+
595
+ /** Whether the fixture numbers `column` (`nextNumberOf`) instead of writing its type's sample: a number a unique index covers. */
596
+ async function numbered(table: string, column: SeedColumn): Promise<boolean> {
597
+ return column.number && (await uniqueIndexesOf(table)).some((index) => index.columns.includes(column.name))
598
+ }
599
+
600
+ /**
601
+ * The number a column `numbered` names takes in `row` (column → value, as the row has them so far): the next above the
602
+ * largest of its group under every unique index that covers it, so the row collides with no row of the table, whoever
603
+ * wrote it. The group is the rows that hold the index's other columns as `row` does: under a fresh parent it is empty
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
605
+ * the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
606
+ */
607
+ async function nextNumberOf(
608
+ table: string,
609
+ column: SeedColumn,
610
+ row: ReadonlyMap<string, SampleValue>,
611
+ ungrouped: ReadonlySet<string> = new Set(),
612
+ ): Promise<SampleValue> {
613
+ const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
614
+ const groups: Map<string, SampleValue>[] = []
615
+ for (const index of covering) {
616
+ const group = new Map<string, SampleValue>()
617
+ for (const other of index.columns) {
618
+ if (other !== column.name && row.has(other) && !ungrouped.has(other)) group.set(other, row.get(other) ?? null)
619
+ }
620
+ if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
621
+ }
622
+ if (groups.length === 0) return column.sample(0)
623
+ const next = await backend.nextNumber(table, column.name, groups)
624
+ if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
625
+ return next
626
+ }
627
+
628
+ /** A required column's sample where the row is not at hand: an `IN` list's first value where a CHECK names one, else a sample of its type. */
329
629
  async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
330
- return (await checkedValue(table, column)) ?? column.sample()
630
+ const checked = await checkedValue(table, column)
631
+ if (checked !== undefined) return checked
632
+ return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample(0)
331
633
  }
332
634
 
333
635
  function columnsOf(table: string): readonly SeedColumn[] {
@@ -358,53 +660,143 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
358
660
  return isMarkable(column) && !keyed && (await checksOn(table, column.name)).length === 0
359
661
  }
360
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
+
361
673
  /**
362
- * The values of a foreign key outside the containment chain: `null` where every open column admits it, else the
363
- * key of a row of the referenced table, an existing one (a reference table's rows come from a migration) or one the
364
- * fixture inserts, which `inserted` records when given. A required key to a dimension or child table is refused: its
365
- * 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.
366
678
  */
367
- async function referencedKey(
679
+ async function referenceSlot(
368
680
  models: TableModels,
369
681
  table: string,
370
682
  key: ForeignKey,
371
683
  open: readonly string[],
684
+ assigned: ReadonlyMap<string, SampleValue>,
372
685
  depth: number,
373
686
  inserted?: InsertedRow[],
374
- ) {
687
+ ): Promise<Slot> {
375
688
  const columns = columnsOf(table)
376
- const values = new Map<string, SampleValue>()
689
+ const options: SlotOption[] = []
377
690
  if (open.every((name) => columns.find((column) => column.name === name)?.nullable === true)) {
378
- for (const name of open) values.set(name, null)
379
- 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
380
702
  }
381
703
  const target = modelOf(models, key.table)
382
704
  const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
383
- 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) {
384
721
  throw new SeedLimitError(
385
- `the isolation fixture cannot fill ${table}.${
386
- open.join(', ')
387
- }: 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}`,
388
723
  )
389
724
  }
390
- const existing = await backend.firstRow(key.table, key.references)
391
- const row = existing ?? (await insert(models, key.table, new Map(), [], depth + 1, inserted)).stored
392
- const match = new Map<string, SampleValue>()
393
- key.columns.forEach((name, index) => {
394
- const referenced = key.references[index] ?? ''
395
- const value = keyValue(row[referenced], `${key.table}.${referenced}`)
396
- values.set(name, value)
397
- match.set(referenced, value)
398
- })
399
- if (existing === undefined) inserted?.push({ table: key.table, match })
400
- 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
+ }
401
750
  }
402
751
 
403
- /** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
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
790
+ }
791
+
792
+ /**
793
+ * A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. Either
794
+ * holds a random v4 uuid's 122 bits, so a large seed never collides on a key.
795
+ */
404
796
  function scopeValue(table: string, name: string, dimension: string, world: string): string {
405
797
  const column = columnOf(table, name)
406
798
  if (column.uuid) return crypto.randomUUID()
407
- if (column.text) return `${dimension}-${world}-${randomHex()}`
799
+ if (column.text) return `${dimension}-${world}-${crypto.randomUUID()}`
408
800
  throw new Error(`${table}.${name} holds a ${dimension} as ${column.type}; a key or containment column holds its scope value as text or uuid`)
409
801
  }
410
802
 
@@ -422,11 +814,74 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
422
814
  }
423
815
 
424
816
  /**
425
- * 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
426
- * names its `IN` list's first value or `null`, every other text column a marker and every other required column a
427
- * sample. Answers what the fixture wrote, and the row as stored (its database defaults filled). A CHECK or a foreign
428
- * key the values still fail is a `SeedLimitError` that names the constraint. `inserted` records every row a foreign
429
- * key or a file column made it insert, not the row itself.
817
+ * The ways to fill `column`: a file column a seeded file; a column a CHECK names the `IN` list's first value or `null`,
818
+ * then every value the CHECKs naming it list or compare with, and samples of its type; a text column a marker; any other
819
+ * nullable column `null`; a number a unique index covers its next number in the row's group; else samples of its type.
820
+ */
821
+ async function columnSlot(
822
+ model: TableModel | undefined,
823
+ table: string,
824
+ column: SeedColumn,
825
+ markers: string[],
826
+ inserted: InsertedRow[] | undefined,
827
+ ungrouped: ReadonlySet<string>,
828
+ ): Promise<Slot> {
829
+ const name = column.name
830
+ const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
831
+ const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(column.sample(variant)) })
832
+ const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
833
+ const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
834
+ const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
835
+ if (kind !== undefined) {
836
+ return {
837
+ columns: [name],
838
+ options: [keptOption(async () => single(await seedFile(kind, inserted))), ...(column.nullable ? [valueOption(name, null)] : [])],
839
+ }
840
+ }
841
+ const named = await checksOn(table, name)
842
+ const isNumbered = await numbered(table, column)
843
+ if (named.length > 0) {
844
+ const checked = await checkedValue(table, column)
845
+ const first = checked === undefined ? (isNumbered ? next : sampled(0)) : valueOption(name, checked)
846
+ const tried: SampleValue[] = column.nullable ? [null] : []
847
+ for (const check of named) {
848
+ for (const literal of [...check.values, ...check.literals]) tried.push(...literalValues(column, literal))
849
+ }
850
+ const listed = [...new Set(tried)].filter((value) => value !== checked).map((value) => valueOption(name, value))
851
+ return { columns: [name], options: [first, ...listed, ...(isNumbered ? [next] : []), ...samples] }
852
+ }
853
+ if (await holdsMarker(model, table, column)) {
854
+ return {
855
+ columns: [name],
856
+ options: [keptOption(async () => {
857
+ const marker = `m${randomHex()}${randomHex()}`
858
+ markers.push(marker)
859
+ return single(marker)
860
+ })],
861
+ }
862
+ }
863
+ if (column.nullable) return { columns: [name], options: [valueOption(name, null)] }
864
+ return { columns: [name], options: isNumbered ? [next] : samples }
865
+ }
866
+
867
+ /** The columns of the constraint a row failed, or `undefined` when the seeding cannot tell (an index on an expression). */
868
+ async function violatedColumns(table: string, violation: Violation): Promise<readonly string[] | undefined> {
869
+ if (violation.columns !== undefined) return violation.columns
870
+ if (violation.kind === 'check') {
871
+ checks ??= backend.checks()
872
+ return (await checks).find((check) => check.table === table && check.name === violation.name)?.columns
873
+ }
874
+ return (await uniqueIndexesOf(table)).find((index) => index.name === violation.name)?.columns
875
+ }
876
+
877
+ /**
878
+ * Inserts one row: `assigned` as given, every other column a database default leaves open filled by its slot
879
+ * (`columnSlot`, `referenceSlot`), each slot's first option first. When the database refuses the row for a CHECK or
880
+ * a unique index, the fixture tries the next combination of the options of the slots that constraint names (all of
881
+ * them when it names none it can read), up to `MAX_ROW_ATTEMPTS` rows; the last refusal is the `SeedLimitError`.
882
+ * Answers what the fixture wrote, and the row as stored (its database defaults filled). `inserted` records every row
883
+ * a foreign key or a file column made it insert, not the row itself. A number a unique index covers is numbered within
884
+ * its group without the columns in `ungrouped` (a container the row will not lie in).
430
885
  */
431
886
  async function insert(
432
887
  models: TableModels,
@@ -435,42 +890,66 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
435
890
  markers: string[],
436
891
  depth = 0,
437
892
  inserted?: InsertedRow[],
893
+ ungrouped: ReadonlySet<string> = new Set(),
438
894
  ): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
439
895
  const model = modelOf(models, table)
440
896
  const columns = columnsOf(table)
441
- // A column with a database default keeps it unless the fixture assigned it, a foreign key's included.
897
+ // A column with a database default keeps it unless the fixture assigned it or fills a foreign key over it.
442
898
  const defaulted = new Set(columns.filter((column) => column.defaulted).map((column) => column.name))
443
- const keyed = new Map<string, SampleValue>()
899
+ const slots: Slot[] = []
900
+ const slotted = new Set<string>()
444
901
  for (const key of model?.foreignKeys ?? []) {
445
- const open = key.columns.filter((column) => !assigned.has(column) && !defaulted.has(column))
446
- if (open.length === 0) continue
447
- for (const [name, value] of await referencedKey(models, table, key, open, depth, inserted)) keyed.set(name, value)
902
+ const open = key.columns.filter((column) => !assigned.has(column) && !slotted.has(column))
903
+ // A key whose columns all have defaults keeps them; one the fixture fills fills its defaulted columns too, which
904
+ // alone may name no row the key's other columns pick.
905
+ if (open.every((column) => defaulted.has(column))) continue
906
+ slots.push(await referenceSlot(models, table, key, open, assigned, depth, inserted))
907
+ for (const name of open) slotted.add(name)
448
908
  }
449
- const row = new Map<string, SampleValue>()
450
909
  for (const column of columns) {
451
- const name = column.name
452
910
  // An assigned `null` is the fixture's value too, never a gap to fill.
453
- const given = assigned.has(name) ? assigned : keyed.has(name) ? keyed : undefined
454
- if (given !== undefined) {
455
- row.set(name, given.get(name) ?? null)
456
- continue
911
+ if (assigned.has(column.name) || column.defaulted || slotted.has(column.name)) continue
912
+ slots.push(await columnSlot(model, table, column, markers, inserted, ungrouped))
913
+ }
914
+ const order = slotOrder(slots)
915
+ const choice = slots.map(() => 0)
916
+ const involved: number[] = []
917
+ // The refusal of the row the fixture prefers, which the error names once no other row passes.
918
+ let refused: SeedLimitError | undefined
919
+ for (let attempt = 0; attempt < MAX_ROW_ATTEMPTS; attempt++) {
920
+ const row = new Map(assigned)
921
+ let complete = true
922
+ for (const index of order) {
923
+ const slot = slots[index]
924
+ if (slot === undefined) continue
925
+ const picked = await pickOption(slot, choice, index, row)
926
+ if ('error' in picked) {
927
+ // No option of the slot is usable from its current one on: the next combination, or the reason.
928
+ if ((choice[index] ?? 0) === 0 || !involved.includes(index)) throw picked.error
929
+ refused ??= picked.error
930
+ complete = false
931
+ break
932
+ }
933
+ for (const [name, value] of picked.values) row.set(name, value)
457
934
  }
458
- if (column.defaulted) continue
459
- const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
460
- const checked = kind === undefined ? await checkedValue(table, column) : undefined
461
- if (kind !== undefined) {
462
- row.set(name, await seedFile(kind, inserted))
463
- } else if (checked !== undefined) {
464
- row.set(name, checked)
465
- } else if (await holdsMarker(model, table, column)) {
466
- const marker = `m${randomHex()}${randomHex()}`
467
- markers.push(marker)
468
- row.set(name, marker)
469
- } else {
470
- row.set(name, column.nullable ? null : column.sample())
935
+ if (complete) {
936
+ try {
937
+ return { row, stored: await backend.insert(table, row) }
938
+ } catch (error) {
939
+ if (!(error instanceof ConstraintLimitError) || error.violation.kind === 'foreign') throw error
940
+ refused ??= error
941
+ const named = await violatedColumns(table, error.violation)
942
+ const touched = [...slots.keys()].filter((index) => named === undefined || (slots[index]?.columns ?? []).some((name) => named.includes(name)))
943
+ // A constraint over the assigned columns only has nothing to try.
944
+ if (touched.length === 0) throw error
945
+ for (const index of touched) {
946
+ if (!involved.includes(index)) involved.push(index)
947
+ }
948
+ }
471
949
  }
950
+ if (!advanceChoice(slots, choice, involved)) break
472
951
  }
473
- return { row, stored: await backend.insert(table, row) }
952
+ throw refused ?? new SeedLimitError(`the isolation fixture tried ${MAX_ROW_ATTEMPTS} rows of ${table}`)
474
953
  }
475
954
 
476
955
  /** The columns a model's row is placed by: its own key when it owns a dimension, and each link of its chain. */
@@ -541,35 +1020,137 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
541
1020
  /** The value a pin gives the row of `world`: as written in the own row, distinct in the other. */
542
1021
  const pinnedValue = (value: string, world: string): string => (world === 'own' ? value : `${value}-${world}`)
543
1022
 
1023
+ /**
1024
+ * The dimension values the row of `owner` keyed `key` lies in, as the table stores it: its own, then each container's;
1025
+ * `undefined` when the table holds no such row.
1026
+ */
1027
+ async function storedChain(owner: TableModel, key: string): Promise<ReadonlyMap<string, string> | undefined> {
1028
+ const scope = owner.scope
1029
+ if (scope.mode !== 'dimension') return undefined
1030
+ const row = await backend.firstRow(owner.name, [scope.key, ...owner.chain.map((link) => link.column)], new Map([[scope.key, key]]))
1031
+ if (row === undefined) return undefined
1032
+ const chain = new Map([[scope.dimension, key]])
1033
+ for (const link of owner.chain) chain.set(link.dimension, String(keyValue(row[link.column], `${owner.name}.${link.column}`)))
1034
+ return chain
1035
+ }
1036
+
1037
+ /**
1038
+ * The dimension values a row of `model` lies in for `world`, as far as `scopes` know them: each known value, and every
1039
+ * value a stored row of a known one holds. `stored` are the dimensions whose row a table holds already.
1040
+ */
1041
+ async function knownValues(
1042
+ models: TableModels,
1043
+ model: TableModel,
1044
+ world: 'own' | 'other',
1045
+ scopes: ScopeValues,
1046
+ ): Promise<{ readonly values: Map<string, string>; readonly stored: ReadonlySet<string> }> {
1047
+ const own = model.scope.mode === 'dimension' ? [model.scope.dimension] : []
1048
+ const dimensions = [...own, ...model.chain.map((link) => link.dimension)].filter((dimension) => Object.hasOwn(scopes, dimension))
1049
+ const values = new Map<string, string>()
1050
+ for (const dimension of dimensions) {
1051
+ const known = scopes[dimension]
1052
+ if (known !== undefined) values.set(dimension, world === 'own' ? known.own : known.other)
1053
+ }
1054
+ const stored = new Set<string>()
1055
+ for (const dimension of dimensions) {
1056
+ const owner = ownerOf(models, dimension)
1057
+ const value = values.get(dimension)
1058
+ const chain = owner === undefined || value === undefined ? undefined : await storedChain(owner, value)
1059
+ for (const [type, found] of chain ?? []) {
1060
+ const expected = values.get(type)
1061
+ if (expected !== undefined && expected !== found) {
1062
+ throw new Error(`the stored ${dimension} '${value}' lies in the ${type} '${found}', not in the known '${expected}'`)
1063
+ }
1064
+ values.set(type, found)
1065
+ stored.add(type)
1066
+ }
1067
+ }
1068
+ return { values, stored }
1069
+ }
1070
+
1071
+ /** The values of the text columns that would hold a marker in the stored row of `model` keyed `key`. */
1072
+ async function storedTexts(model: TableModel, key: string): Promise<string[]> {
1073
+ const scope = model.scope
1074
+ if (scope.mode !== 'dimension') return []
1075
+ const names: string[] = []
1076
+ for (const column of columnsOf(model.name)) {
1077
+ if (await holdsMarker(model, model.name, column)) names.push(column.name)
1078
+ }
1079
+ if (names.length === 0) return []
1080
+ const row = await backend.firstRow(model.name, names, new Map([[scope.key, key]]))
1081
+ return names.flatMap((name) => {
1082
+ const value = row?.[name]
1083
+ return typeof value === 'string' && value !== '' ? [value] : []
1084
+ })
1085
+ }
1086
+
544
1087
  async function seedWorld(
545
1088
  models: TableModels,
546
1089
  model: TableModel,
547
- world: string,
1090
+ world: 'own' | 'other',
548
1091
  seed: Readonly<Record<string, SampleValue>>,
549
1092
  pins: Readonly<Record<string, string>>,
1093
+ scopes: ScopeValues,
550
1094
  inserted: InsertedRow[],
551
- ): Promise<WorldRow> {
1095
+ ): Promise<{
1096
+ readonly world: Omit<WorldRow, 'updates'>
1097
+ readonly row: ReadonlyMap<string, SampleValue>
1098
+ /** The row as stored, its defaults filled. */
1099
+ readonly holds: Readonly<Record<string, unknown>>
1100
+ }> {
552
1101
  const markers: string[] = []
553
- const values = new Map<string, string>()
554
- const links: readonly Container[] = model.chain
555
- for (const link of links) {
556
- values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
557
- }
558
1102
  const scope = model.scope
559
1103
  if (scope.mode !== 'dimension' && scope.mode !== 'child') {
560
1104
  throw new Error(`${model.name} is not a dimension or child table`)
561
1105
  }
562
- const key = scopeValue(model.name, scope.key, scope.mode === 'dimension' ? scope.dimension : model.name, world)
563
- if (scope.mode === 'dimension') {
564
- values.set(scope.dimension, key)
1106
+ const { values, stored } = await knownValues(models, model, world, scopes)
1107
+ const links: readonly Container[] = model.chain
1108
+ for (const link of links) {
1109
+ if (!values.has(link.dimension)) values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
1110
+ }
1111
+ const own = scope.mode === 'dimension' ? scope.dimension : undefined
1112
+ const key = (own === undefined ? undefined : values.get(own)) ?? scopeValue(model.name, scope.key, own ?? model.name, world)
1113
+ if (own !== undefined) {
1114
+ values.set(own, key)
565
1115
  }
566
- // Containers first, outermost first: a composite foreign key needs its target row.
1116
+ const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[], holds: Readonly<Record<string, unknown>> = {}) => {
1117
+ const chain = [
1118
+ ...(own === undefined ? [] : [{ type: own, value: key }]),
1119
+ ...links.flatMap((link) => {
1120
+ const value = values.get(link.dimension)
1121
+ return value === undefined ? [] : [{ type: link.dimension, value }]
1122
+ }),
1123
+ ]
1124
+ const seeded = {
1125
+ key,
1126
+ parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
1127
+ scope: values.get(grantDimension(models, model)) ?? key,
1128
+ chain,
1129
+ markers,
1130
+ stored,
1131
+ }
1132
+ return { world: seeded, row, holds }
1133
+ }
1134
+ if (own !== undefined && stored.has(own)) {
1135
+ if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
1136
+ throw new Error(
1137
+ `${model.name} already holds the ${own} '${key}' (a migration wrote it), so a case writes no seed or pin into it; seed the state of a row the case inserts`,
1138
+ )
1139
+ }
1140
+ return worldRow(new Map(), await storedTexts(model, key))
1141
+ }
1142
+ // Containers first, outermost first: a composite foreign key needs its target row. A stored one is used as it is.
567
1143
  for (let index = links.length - 1; index >= 0; index--) {
568
1144
  const link = links[index]
569
1145
  const owner = link === undefined ? undefined : ownerOf(models, link.dimension)
570
1146
  const value = link === undefined ? undefined : values.get(link.dimension)
571
- if (owner !== undefined && owner.name !== model.name && value !== undefined) {
572
- await insert(models, owner.name, placement(owner, values, value), markers)
1147
+ if (link === undefined || owner === undefined || owner.name === model.name || value === undefined || stored.has(link.dimension)) continue
1148
+ // With known values, every container goes with the worlds: one of a known value, so the next case can insert it
1149
+ // again, and one inside a stored row, which no removal of that row reaches.
1150
+ const tracked = Object.keys(scopes).length > 0 ? inserted : undefined
1151
+ await insert(models, owner.name, placement(owner, values, value), markers, 0, tracked)
1152
+ if (tracked !== undefined && owner.scope.mode === 'dimension') {
1153
+ tracked.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
573
1154
  }
574
1155
  }
575
1156
  const assigned = placement(model, values, key)
@@ -597,39 +1178,70 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
597
1178
  assigned.set(name, pinned)
598
1179
  markers.push(pinned)
599
1180
  }
600
- const { row } = await insert(models, model.name, assigned, markers)
1181
+ const { row, stored: holds } = await insert(models, model.name, assigned, markers, 0, inserted)
601
1182
  inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
1183
+ return worldRow(row, [], holds)
1184
+ }
1185
+
1186
+ /** `work`, after which a failure removes the rows it recorded in `inserted` before it rethrows. */
1187
+ async function removedOnFailure<T>(inserted: readonly InsertedRow[], what: string, work: () => Promise<T>): Promise<T> {
1188
+ try {
1189
+ return await work()
1190
+ } catch (error) {
1191
+ try {
1192
+ await backend.remove(inserted)
1193
+ } catch (cleanup) {
1194
+ throw new AggregateError([error, cleanup], `the isolation fixture could not ${what}, nor remove what it had seeded`)
1195
+ }
1196
+ throw error
1197
+ }
1198
+ }
1199
+
1200
+ /**
1201
+ * A seeded row's values of the policy's update columns, which its CHECKs accepted: as written, as stored where the
1202
+ * database filled the column (a default), or a sample where the stored value is no plain value.
1203
+ */
1204
+ async function updatesOf(
1205
+ model: TableModel,
1206
+ row: ReadonlyMap<string, SampleValue>,
1207
+ stored: Readonly<Record<string, unknown>> = {},
1208
+ ): Promise<Record<string, SampleValue>> {
602
1209
  const updates: Record<string, SampleValue> = {}
603
1210
  for (const name of namesOf(model.update)) {
604
- updates[name] = row.get(name) ?? await updateSample(model.name, name)
605
- }
606
- const dimension = grantDimension(models, model)
607
- const chain = [
608
- ...(scope.mode === 'dimension' ? [{ type: scope.dimension, value: key }] : []),
609
- ...links.flatMap((link) => {
610
- const value = values.get(link.dimension)
611
- return value === undefined ? [] : [{ type: link.dimension, value }]
612
- }),
613
- ]
614
- return {
615
- key,
616
- parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
617
- scope: values.get(dimension) ?? key,
618
- chain,
619
- updates,
620
- markers,
1211
+ const written = row.get(name)
1212
+ const kept = written === undefined ? plainValue(stored[name]) : written
1213
+ updates[name] = kept === undefined ? await updateSample(model.name, name) : kept
621
1214
  }
1215
+ return updates
622
1216
  }
623
1217
 
624
1218
  return {
625
- async seedWorlds(tables, table, values = {}, pins = {}) {
1219
+ async seedWorlds(tables, table, values = {}, pins = {}, scopes = {}) {
626
1220
  const { models, model } = scopedModel(tables, table)
627
1221
  const dimension = grantDimension(models, model)
1222
+ for (const [name, known] of Object.entries(scopes)) {
1223
+ if (known.own === known.other) throw new Error(`the two worlds share the ${name} '${known.own}'; each needs a value of its own`)
1224
+ }
628
1225
  const inserted: InsertedRow[] = []
1226
+ let own: Awaited<ReturnType<typeof seedWorld>>
1227
+ let other: Awaited<ReturnType<typeof seedWorld>>
1228
+ try {
1229
+ own = await seedWorld(models, model, 'own', values, pins, scopes, inserted)
1230
+ other = await seedWorld(models, model, 'other', values, pins, scopes, inserted)
1231
+ } catch (error) {
1232
+ // A row of a known value left behind would pass for one a migration wrote in every later case.
1233
+ try {
1234
+ await backend.remove(inserted)
1235
+ } catch (cleanup) {
1236
+ throw new AggregateError([error, cleanup], 'the isolation fixture could not seed the worlds, nor remove what it had seeded')
1237
+ }
1238
+ throw error
1239
+ }
1240
+ // Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
629
1241
  return {
630
1242
  dimension,
631
- own: await seedWorld(models, model, 'own', values, pins, inserted),
632
- other: await seedWorld(models, model, 'other', values, pins, inserted),
1243
+ own: { ...own.world, updates: await updatesOf(model, own.row, own.holds) },
1244
+ other: { ...other.world, updates: await updatesOf(model, other.row, other.holds) },
633
1245
  remove: () => backend.remove(inserted),
634
1246
  }
635
1247
  },
@@ -637,12 +1249,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
637
1249
  const { models, model } = scopedModel(tables, table)
638
1250
  checkApplicationValues(models, { [table]: values })
639
1251
  const markers: string[] = []
640
- const { key, row } = await seedApplicationRow(models, model, values, new Map(), markers)
641
- const updates: Record<string, SampleValue> = {}
642
- for (const name of namesOf(model.update)) {
643
- updates[name] = row.get(name) ?? await updateSample(table, name)
644
- }
645
- return { key, updates, markers }
1252
+ const { key, row, stored } = await seedApplicationRow(models, model, values, new Map(), markers)
1253
+ return { key, updates: await updatesOf(model, row, stored), markers }
646
1254
  },
647
1255
  async seedApplicationRows(tables, rows) {
648
1256
  const models = tableModels(tables)
@@ -694,25 +1302,35 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
694
1302
  }
695
1303
  const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
696
1304
  const markers: string[] = []
697
- await insert(models, table, placement(model, values, key), markers)
698
- return { key, markers }
1305
+ const inserted: InsertedRow[] = []
1306
+ await removedOnFailure(inserted, 'seed the row', () => insert(models, table, placement(model, values, key), markers, 0, inserted))
1307
+ inserted.push({ table, match: new Map([[scope.key, key]]) })
1308
+ return { key, markers, remove: () => backend.remove(inserted) }
699
1309
  },
700
- async sampleInsert(tables, table) {
1310
+ async sampleInsert(tables, table, beside) {
701
1311
  const { models, model } = scopedModel(tables, table)
702
- const values: Record<string, SampleValue> = {}
703
- const columns = columnsOf(table)
704
- const required = columns.filter((column) => inSet(model.insert, column.name) && isRequired(column))
705
- for (const key of model.foreignKeys) {
706
- const open = key.columns.filter((name) => required.some((column) => column.name === name))
707
- if (open.length === 0) continue
708
- for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
1312
+ const scope = model.scope
1313
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
1314
+ throw new Error(`${table} is a ${scope.mode} table; no store inserts into it`)
709
1315
  }
710
- for (const column of required) {
711
- const name = column.name
712
- const kind = Object.hasOwn(model.files, name) ? model.files[name] : undefined
713
- if (!(name in values)) values[name] = kind === undefined ? await requiredSample(table, column) : await seedFile(kind)
1316
+ // A probe row the database judges, placed as the insert will place it (in `beside`'s containers, else in fresh
1317
+ // ones it removes with the probe), numbered within the containers known; its values are the sample.
1318
+ const values = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
1319
+ const ungrouped = new Set(model.chain.filter((link) => !values.has(link.dimension)).map((link) => link.column))
1320
+ const placed: InsertedRow[] = []
1321
+ const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'probe')
1322
+ const { row } = await removedOnFailure(placed, 'insert a probe row', async () => {
1323
+ await placeContainers(models, model, values, 'probe', 0, placed)
1324
+ return insert(models, table, placement(model, values, key), [], 0, undefined, ungrouped)
1325
+ })
1326
+ await backend.remove([{ table, match: new Map([[scope.key, key]]) }, ...placed])
1327
+ const sample: Record<string, SampleValue> = {}
1328
+ for (const column of columnsOf(table)) {
1329
+ if (!inSet(model.insert, column.name) || !row.has(column.name)) continue
1330
+ // A nullable column a CHECK ties to another is written as the probe held it; any other is left to the insert.
1331
+ if (isRequired(column) || (await checksOn(table, column.name)).length > 0) sample[column.name] = row.get(column.name) ?? null
714
1332
  }
715
- return values
1333
+ return sample
716
1334
  },
717
1335
  seededObjects: () => [...seededObjects],
718
1336
  }