@fabrika/db 0.9.0-dev.7 → 0.9.0-dev.71

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 +69 -13
  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 +67 -9
  10. package/src/errors.ts +9 -5
  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 +187 -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 +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  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 +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  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 +40 -9
  47. package/types/src/errors.d.ts +8 -5
  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 +35 -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 +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  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 +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  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 +176 -22
@@ -3,18 +3,128 @@
3
3
  // probe. Not a subpath: each kit refuses a production process before it imports this module.
4
4
 
5
5
  import { createHash } from 'node:crypto'
6
+ import { z } from 'zod/v4'
6
7
  import { type ApplicationRowRefusal, applicationRowRefusalText, type ApplicationRowsPlan, planApplicationRows } from './application-rows'
7
- import { inSet, namesOf } from './builtins'
8
+ import { inSet, namesOf, ownEntry } from './builtins'
8
9
  import type { Database } from './database'
9
- import type { Primitive } from './description'
10
+ import { isPrimitive, type Primitive } from './description'
11
+ import { isJsonColumnValue, type JsonColumnValue, jsonInput, type JsonSchema } from './json'
10
12
  import { FILES_TABLE } from './migrations'
11
13
  import { type Container, type ForeignKey, modelOf, type TableModel, type TableModels, tableModels, type Tables } from './policy'
12
14
  import { refuseInProduction } from './production'
13
15
  import { frameworkSideOf } from './registry'
14
16
  import type { TableProbe } from './store'
15
17
 
16
- /** A value a test row holds in a column; `null` for a nullable column the fixture left empty. */
17
- export type SampleValue = Primitive | null
18
+ /**
19
+ * A value a test row holds in a column; `null` for a nullable column the fixture left empty. Only a JSON column holds
20
+ * an object or an array: the sample of one whose policy declares a schema (`jsonSample`).
21
+ */
22
+ export type SampleValue = Primitive | JsonColumnValue | null
23
+
24
+ /**
25
+ * 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
26
+ * seeded row and the kits' cases that write the same value through the layer hold the same JSON.
27
+ */
28
+ export function seedBinding(columns: readonly SeedColumn[], table: string, name: string, value: SampleValue): Primitive | null {
29
+ if (value !== null && columns.some((column) => column.table === table && column.name === name && column.json)) {
30
+ return jsonInput(value, `${table}.${name}`)
31
+ }
32
+ if (value === null || isPrimitive(value)) return value
33
+ throw new SeedLimitError(`the isolation fixture cannot write an object or an array into ${table}.${name}, which is no JSON column`)
34
+ }
35
+
36
+ /** A string of a JSON Schema `format` zod emits, which a plain sample would not pass. */
37
+ const FORMAT_SAMPLES: Readonly<Record<string, string>> = {
38
+ uuid: '00000000-0000-4000-8000-000000000000',
39
+ email: 'sample@example.test',
40
+ uri: 'https://example.test/',
41
+ 'date-time': '2026-01-01T00:00:00.000Z',
42
+ date: '2026-01-01',
43
+ time: '12:00:00',
44
+ duration: 'PT1H',
45
+ }
46
+
47
+ /** How deep a sample follows nested schemas and references: a recursive schema's sample stops at its optional members. */
48
+ const MAX_SAMPLE_DEPTH = 16
49
+
50
+ /**
51
+ * A value JSON Schema `node` admits, built the plain way (`const`, a default, the first enum member or branch, an
52
+ * object's required members, the least array, a string or number its bounds admit); `undefined` where none is built.
53
+ */
54
+ function jsonSchemaSample(node: z.core.JSONSchema._JSONSchema, root: z.core.JSONSchema.JSONSchema, depth: number): unknown {
55
+ if (typeof node === 'boolean') return node ? 'sample' : undefined
56
+ if (depth > MAX_SAMPLE_DEPTH) return undefined
57
+ if (node.$ref !== undefined) {
58
+ const name = node.$ref.startsWith('#/$defs/') ? node.$ref.slice('#/$defs/'.length) : undefined
59
+ const target = node.$ref === '#' ? root : name === undefined ? undefined : root.$defs?.[name]
60
+ return target === undefined ? undefined : jsonSchemaSample(target, root, depth + 1)
61
+ }
62
+ if (node.const !== undefined) return node.const
63
+ if (node.default !== undefined) return node.default
64
+ if (node.enum !== undefined) return node.enum[0]
65
+ for (const branch of node.anyOf ?? node.oneOf ?? []) {
66
+ const sample = jsonSchemaSample(branch, root, depth + 1)
67
+ if (sample !== undefined) return sample
68
+ }
69
+ if (node.allOf !== undefined) {
70
+ const parts = node.allOf.map((part) => jsonSchemaSample(part, root, depth + 1))
71
+ return parts.every((part) => typeof part === 'object' && part !== null && !Array.isArray(part)) ? Object.assign({}, ...parts) : parts[0]
72
+ }
73
+ switch (node.type) {
74
+ case 'object': {
75
+ const sample: Record<string, unknown> = {}
76
+ for (const key of node.required ?? []) {
77
+ const member = node.properties?.[key]
78
+ const value = member === undefined ? undefined : jsonSchemaSample(member, root, depth + 1)
79
+ if (value === undefined) return undefined
80
+ sample[key] = value
81
+ }
82
+ return sample
83
+ }
84
+ case 'array': {
85
+ if (node.prefixItems !== undefined) return node.prefixItems.map((item) => jsonSchemaSample(item, root, depth + 1))
86
+ const items = node.items
87
+ const item = items === undefined || Array.isArray(items) ? 'sample' : jsonSchemaSample(items, root, depth + 1)
88
+ return Array.from({ length: node.minItems ?? 0 }, () => item)
89
+ }
90
+ case 'string': {
91
+ if (node.format !== undefined) return FORMAT_SAMPLES[node.format]
92
+ const least = node.minLength ?? 0
93
+ return 'sample'.padEnd(least, 'x').slice(0, Math.max(least, node.maxLength ?? 6))
94
+ }
95
+ case 'number':
96
+ case 'integer': {
97
+ const least = node.minimum ?? (node.exclusiveMinimum === undefined ? undefined : node.exclusiveMinimum + 1)
98
+ const most = node.maximum ?? (node.exclusiveMaximum === undefined ? undefined : node.exclusiveMaximum - 1)
99
+ const value = least ?? (most !== undefined && most < 0 ? most : 0)
100
+ return node.type === 'integer' ? Math.ceil(value) : value
101
+ }
102
+ case 'boolean':
103
+ return false
104
+ case 'null':
105
+ return null
106
+ default:
107
+ return 'sample'
108
+ }
109
+ }
110
+
111
+ /**
112
+ * The sample of a JSON column whose policy declares `schema`: built from the schema's JSON Schema and parsed by the
113
+ * schema, which answers the value the layer would store. A `SeedLimitError` when the sample does not pass (a pattern,
114
+ * a refinement), as for a type the fixture has no sample of.
115
+ */
116
+ export function jsonSample(schema: JsonSchema, where: string): JsonColumnValue {
117
+ const described = z.toJSONSchema(schema, { io: 'input' })
118
+ const parsed = z.safeParse(schema, jsonSchemaSample(described, described, 0))
119
+ if (!parsed.success) {
120
+ throw new SeedLimitError(`the isolation fixture cannot fill ${where}: the sample it builds from its JSON schema does not pass it`)
121
+ }
122
+ const value: unknown = parsed.data
123
+ if (!isJsonColumnValue(value)) {
124
+ throw new SeedLimitError(`the isolation fixture cannot fill ${where}: its JSON schema answers no JSON value for the sample`)
125
+ }
126
+ return value
127
+ }
18
128
 
19
129
  /** One seeded row and where it lies. */
20
130
  export interface WorldRow {
@@ -29,19 +139,24 @@ export interface WorldRow {
29
139
  * share link's chain is this list.
30
140
  */
31
141
  readonly chain: readonly { readonly type: string; readonly value: string }[]
32
- /** The row's values of the policy's update columns, as seeded. */
142
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
33
143
  readonly updates: Readonly<Record<string, SampleValue>>
34
144
  /**
35
145
  * The distinct value written into every text column the fixture filled itself, in this row and in its containers.
36
146
  * Each occurs in no other fixture, so one found in an answer to another scope is a leaked row.
37
147
  */
38
148
  readonly markers: readonly string[]
149
+ /**
150
+ * The values of the text columns of a row the table already held under a known scope value (`seedWorlds`' `scopes`),
151
+ * which no fixture wrote and other rows may share; empty for a row the fixture inserted.
152
+ */
153
+ readonly stored: readonly string[]
39
154
  }
40
155
 
41
156
  /** One seeded row of an application table, which lies in no dimension. */
42
157
  export interface ApplicationRow {
43
158
  readonly key: string
44
- /** The row's values of the policy's update columns, as seeded. */
159
+ /** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
45
160
  readonly updates: Readonly<Record<string, SampleValue>>
46
161
  /** The distinct value written into every text column the fixture filled itself. */
47
162
  readonly markers: readonly string[]
@@ -63,17 +178,38 @@ export interface SeededApplicationRows {
63
178
  export interface SeededRow {
64
179
  readonly key: string
65
180
  readonly markers: readonly string[]
181
+ /** Deletes the row, the rows its foreign keys made the fixture insert, and every row that refers to them. */
182
+ readonly remove: () => Promise<void>
66
183
  }
67
184
 
68
185
  /**
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.
186
+ * What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
187
+ * foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
188
+ * column, never a failure of the handler or the policy a case is about.
72
189
  */
73
190
  export class SeedLimitError extends Error {
74
191
  override readonly name = 'SeedLimitError'
75
192
  }
76
193
 
194
+ /** The constraint a seeded row failed, as a backend reads it off the database's error. */
195
+ export interface Violation {
196
+ readonly kind: 'check' | 'unique' | 'foreign'
197
+ /** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
198
+ readonly name: string
199
+ /** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
200
+ readonly columns?: readonly string[]
201
+ }
202
+
203
+ /** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
204
+ export class ConstraintLimitError extends SeedLimitError {
205
+ readonly violation: Violation
206
+
207
+ constructor(message: string, violation: Violation) {
208
+ super(message)
209
+ this.violation = violation
210
+ }
211
+ }
212
+
77
213
  /** One row of a table in each of two containment chains that share no value. */
78
214
  export interface IsolationWorlds {
79
215
  /**
@@ -84,12 +220,19 @@ export interface IsolationWorlds {
84
220
  readonly own: WorldRow
85
221
  readonly other: WorldRow
86
222
  /**
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.
223
+ * Deletes both rows of the table it inserted, every container row it inserted when it was given known scope values,
224
+ * and every row that refers to them, however deep; the other containers stay. A case whose rows hold pinned values or
225
+ * known scope values removes them, so the next case can seed the same values again under a unique index.
89
226
  */
90
227
  readonly remove: () => Promise<void>
91
228
  }
92
229
 
230
+ /**
231
+ * Known values of dimensions, by dimension: the own world's and the other world's, which differ. A dimension whose values
232
+ * are a fixed set (an enum the input names it by) takes these instead of fresh ones.
233
+ */
234
+ export type ScopeValues = Readonly<Record<string, { readonly own: string; readonly other: string }>>
235
+
93
236
  /** What a test kit seeds through, over its migrated schema. */
94
237
  export interface TestSeeding {
95
238
  /**
@@ -98,13 +241,17 @@ export interface TestSeeding {
98
241
  * marker, so a seed of one, or of a column that places the row, throws. `pins` (column → value) give a text column of
99
242
  * `table` a known value instead of its marker: the value in the own row, and `<value>-other` in the other row, which
100
243
  * 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.
244
+ * no text column, throws. `scopes` place each world in known values of a dimension instead of fresh ones: a row of
245
+ * the table that owns it with that key is used as it is stored (a migration wrote it), its containers' values with it,
246
+ * and is inserted otherwise. A stored row of `table` itself takes no `values` or `pins`: they throw. A seed that throws
247
+ * removes what it inserted.
102
248
  */
103
249
  seedWorlds<DB, P>(
104
250
  tables: Tables<DB, P>,
105
251
  table: string,
106
252
  values?: Readonly<Record<string, SampleValue>>,
107
253
  pins?: Readonly<Record<string, string>>,
254
+ scopes?: ScopeValues,
108
255
  ): Promise<IsolationWorlds>
109
256
  /**
110
257
  * Seeds one row of the application table `table`: its key, version and creator stamped, `values` (column → value)
@@ -123,13 +270,19 @@ export interface TestSeeding {
123
270
  rows: Readonly<Record<string, Readonly<Record<string, SampleValue>>>>,
124
271
  ): Promise<SeededApplicationRows>
125
272
  /**
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.
273
+ * Seeds one row of `table`, a child or dimension table that lies in the object `under`'s chain starts at (a row
274
+ * `seedWorlds` seeded, or a value of its chain with the values outside it), placed in that chain: the row a fixture
275
+ * names by id, such as a note's comment. Answers its key and the markers it holds.
276
+ */
277
+ seedUnder<DB, P>(tables: Tables<DB, P>, table: string, under: Pick<WorldRow, 'chain'>): Promise<SeededRow>
278
+ /**
279
+ * Values for the policy's insert columns of `table` that its schema accepts: every required one, sampled; a file
280
+ * column a seeded file. `beside` is a row `seedWorlds` seeded that the inserted row will lie beside, in the same
281
+ * containers. A number column a unique index covers takes the next number above the largest the table holds now in the
282
+ * row's group (the index's other columns as the row will have them, its containers' from `beside`), so insert the
283
+ * values before taking the next sample, or the two share it.
129
284
  */
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>>>
285
+ sampleInsert<DB, P>(tables: Tables<DB, P>, table: string, beside?: WorldRow): Promise<Readonly<Record<string, SampleValue>>>
133
286
  /**
134
287
  * The object key of every file the fixture seeded into a file column, oldest first. Each stands for an empty object,
135
288
  * which a test's object store holds when a handler serves or opens the file.
@@ -159,8 +312,16 @@ export interface SeedColumn {
159
312
  readonly text: boolean
160
313
  /** A uuid type: a key or containment column of it holds a random uuid as its scope value. */
161
314
  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
315
+ /** A number type: where a unique index covers it, the fixture writes the next number of the row's group instead of its sample. */
316
+ readonly number: boolean
317
+ /** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
318
+ readonly json: boolean
319
+ /**
320
+ * A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
321
+ * cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
322
+ * day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
323
+ */
324
+ readonly sample: (variant: number) => Primitive
164
325
  }
165
326
 
166
327
  /** A CHECK constraint of the schema, by the columns it names. */
@@ -169,7 +330,24 @@ export interface CheckConstraint {
169
330
  readonly table: string
170
331
  readonly columns: readonly string[]
171
332
  /** 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[]
333
+ readonly values: readonly CheckLiteral[]
334
+ /** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
335
+ readonly literals: readonly CheckLiteral[]
336
+ }
337
+
338
+ /** A literal of a CHECK expression. */
339
+ export type CheckLiteral = string | number
340
+
341
+ /**
342
+ * A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
343
+ * plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
344
+ */
345
+ export interface UniqueIndex {
346
+ readonly name: string
347
+ readonly table: string
348
+ readonly columns: readonly string[]
349
+ /** `NULLS NOT DISTINCT`: a null in a key column collides with another row's null there. */
350
+ readonly nullsNotDistinct: boolean
173
351
  }
174
352
 
175
353
  /** A live, empty file of `kind`, as the framework's put leaves one once a reference claims it. */
@@ -200,10 +378,25 @@ export interface SeedingBackend {
200
378
  readonly columns: readonly SeedColumn[]
201
379
  /** Every CHECK constraint of the schema's tables; read once, on the first column that needs them. */
202
380
  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`). */
381
+ /** Every unique index of plain columns and no predicate of the schema's tables; read once, on the first column that needs them. */
382
+ uniqueIndexes(): Promise<readonly UniqueIndex[]>
383
+ /**
384
+ * The smallest whole number above every value `column` holds in the rows of `table` that match one of `groups`
385
+ * (`groupsWhere`), and at least 1, as the column's type holds it; `undefined` when the type holds no such number, or
386
+ * the largest is no finite number.
387
+ */
388
+ nextNumber(table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): Promise<Primitive | undefined>
389
+ /**
390
+ * Inserts one row and answers it as stored; a CHECK, foreign key or unique index it fails is a `SeedLimitError`
391
+ * (`checkLimit`, `foreignKeyLimit`, `uniqueValueLimit`).
392
+ */
204
393
  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>
394
+ /** One row of `table` that holds `where` (column → value; every row when empty), of `columns`, or `undefined` when none does. */
395
+ firstRow(
396
+ table: string,
397
+ columns: readonly string[],
398
+ where?: ReadonlyMap<string, SampleValue>,
399
+ ): Promise<Readonly<Record<string, unknown>> | undefined>
207
400
  insertFile(file: SeededFile): Promise<void>
208
401
  /**
209
402
  * Deletes `rows` (each found by its `match`; one already gone is skipped) and every row that refers to one of them,
@@ -214,20 +407,60 @@ export interface SeedingBackend {
214
407
  }
215
408
 
216
409
  /** 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`,
410
+ export function checkLimit(constraint: string, table: string): ConstraintLimitError {
411
+ return new ConstraintLimitError(
412
+ `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)`,
413
+ { kind: 'check', name: constraint },
220
414
  )
221
415
  }
222
416
 
223
417
  /** 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}`)
418
+ export function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError {
419
+ return new ConstraintLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`, {
420
+ kind: 'foreign',
421
+ name: constraint,
422
+ })
423
+ }
424
+
425
+ /** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
426
+ export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
427
+ return new SeedLimitError(
428
+ `the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value`,
429
+ )
430
+ }
431
+
432
+ /** The seed limit of a row whose values another row of the table already holds under a unique index. */
433
+ export function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError {
434
+ return new ConstraintLimitError(
435
+ `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)`,
436
+ columns === undefined ? { kind: 'unique', name: index } : { kind: 'unique', name: index, columns },
437
+ )
226
438
  }
227
439
 
228
440
  /** The seed limit of a required column whose type the fixture has no sample of. */
229
441
  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`)
442
+ return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}): it has no sample of that type`)
443
+ }
444
+
445
+ /**
446
+ * A condition that matches a row holding every value of one of `groups` (column → value, `null` matched by `IS NULL`; an
447
+ * empty group matches every row, no group none), in the dialect's quoting and placeholders, with the values it binds.
448
+ */
449
+ export function groupsWhere(
450
+ groups: readonly ReadonlyMap<string, SampleValue>[],
451
+ quote: (identifier: string) => string,
452
+ placeholder: (position: number) => string,
453
+ ): { where: string; values: SampleValue[] } {
454
+ const values: SampleValue[] = []
455
+ const each = groups.map((group) => {
456
+ const terms = [...group].map(([column, value]) => {
457
+ if (value === null) return `${quote(column)} IS NULL`
458
+ values.push(value)
459
+ return `${quote(column)} = ${placeholder(values.length)}`
460
+ })
461
+ return terms.length === 0 ? 'TRUE' : `(${terms.join(' AND ')})`
462
+ })
463
+ return { where: each.length === 0 ? 'FALSE' : each.join(' OR '), values }
231
464
  }
232
465
 
233
466
  export function randomHex(): string {
@@ -241,6 +474,14 @@ function applicationRowError(refusal: ApplicationRowRefusal): Error {
241
474
  }
242
475
 
243
476
  /** A key value as the database returned it, for the foreign key that references it. */
477
+ /** `value` as the fixture can write it back, or `undefined` when it is none it writes (a JSON object, bytes). */
478
+ function plainValue(value: unknown): SampleValue | undefined {
479
+ if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
480
+ return value
481
+ }
482
+ return value instanceof Date ? value : undefined
483
+ }
484
+
244
485
  function keyValue(value: unknown, where: string): SampleValue {
245
486
  if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
246
487
  return value
@@ -278,6 +519,9 @@ function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly mo
278
519
  if (model === undefined) {
279
520
  throw new Error(`${table} is not a table of the policies`)
280
521
  }
522
+ if (model.view) {
523
+ throw new Error(`${table} is a view, whose rows come from the tables it reads: seed those instead`)
524
+ }
281
525
  return { models, model }
282
526
  }
283
527
 
@@ -292,7 +536,124 @@ function ownerOf(models: TableModels, dimension: string): TableModel | undefined
292
536
  }
293
537
 
294
538
  /** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
295
- const MAX_REFERENCE_DEPTH = 4
539
+ const MAX_REFERENCE_DEPTH = 16
540
+ /** How many rows the fixture tries for one insert before it reports the last constraint they failed. */
541
+ const MAX_ROW_ATTEMPTS = 64
542
+ /** How many samples of its type the fixture tries in a column whose values a constraint may refuse. */
543
+ const SAMPLE_VARIANTS = 4
544
+
545
+ /** One way to fill a slot of a row: its values, given the row so far; a `SeedLimitError` when it has none. */
546
+ interface SlotOption {
547
+ /** It reads the row's other values (a number a unique index numbers within its group), so it is taken last and never kept. */
548
+ readonly grouped: boolean
549
+ readonly values: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>
550
+ }
551
+
552
+ /**
553
+ * Columns the fixture fills together (one column, or a foreign key's open columns) and the ways it may fill them, first
554
+ * first. `reads` are the columns of the row its options read, which other slots fill first.
555
+ */
556
+ interface Slot {
557
+ readonly columns: readonly string[]
558
+ readonly options: readonly SlotOption[]
559
+ readonly reads?: readonly string[]
560
+ }
561
+
562
+ /**
563
+ * An option computed once for each value of `reads` in the row: a fresh referenced row is inserted once for the values
564
+ * it shares with the row, and again only when they change.
565
+ */
566
+ function keptOption(
567
+ compute: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>,
568
+ reads: readonly string[] = [],
569
+ ): SlotOption {
570
+ const computed = new Map<string, Promise<ReadonlyMap<string, SampleValue>>>()
571
+ return {
572
+ grouped: false,
573
+ values: (row) => {
574
+ const key = reads.map((name) => valueKey(row.get(name) ?? null)).join('\u0000')
575
+ const values = computed.get(key) ?? compute(row)
576
+ computed.set(key, values)
577
+ return values
578
+ },
579
+ }
580
+ }
581
+
582
+ function valueKey(value: SampleValue): string {
583
+ if (value === null) return 'null'
584
+ return `${typeof value}:${value instanceof Date ? value.toISOString() : String(value)}`
585
+ }
586
+
587
+ /**
588
+ * The order the fixture fills `slots` in: a slot after the slots that fill the columns it reads, and a slot that numbers
589
+ * within the row's group last, once every other slot placed the row. A cycle keeps the declared order.
590
+ */
591
+ function slotOrder(slots: readonly Slot[]): number[] {
592
+ const filledBy = new Map<string, number>()
593
+ slots.forEach((slot, index) => {
594
+ for (const name of slot.columns) filledBy.set(name, index)
595
+ })
596
+ const grouped = (index: number): boolean => slots[index]?.options.some((option) => option.grouped) ?? false
597
+ const pending = [...slots.keys()].sort((left, right) => Number(grouped(left)) - Number(grouped(right)))
598
+ const order: number[] = []
599
+ while (pending.length > 0) {
600
+ const ready = pending.findIndex((index) =>
601
+ (slots[index]?.reads ?? []).every((name) => {
602
+ const filler = filledBy.get(name)
603
+ return filler === undefined || filler === index || order.includes(filler)
604
+ })
605
+ )
606
+ const [next] = pending.splice(Math.max(ready, 0), 1)
607
+ if (next !== undefined) order.push(next)
608
+ }
609
+ return order
610
+ }
611
+
612
+ function valueOption(name: string, value: SampleValue): SlotOption {
613
+ return { grouped: false, values: async () => new Map([[name, value]]) }
614
+ }
615
+
616
+ /** 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. */
617
+ function literalValues(column: SeedColumn, literal: CheckLiteral): SampleValue[] {
618
+ if (column.number) return typeof literal === 'number' && Number.isSafeInteger(literal) ? [literal, literal + 1, literal - 1] : []
619
+ return column.text && typeof literal === 'string' ? [literal] : []
620
+ }
621
+
622
+ /** The first usable option of `slot` from `choice[index]` on, which `choice` then records; `undefined` when none is. */
623
+ async function pickOption(
624
+ slot: Slot,
625
+ choice: number[],
626
+ index: number,
627
+ row: ReadonlyMap<string, SampleValue>,
628
+ ): Promise<{ readonly values: ReadonlyMap<string, SampleValue> } | { readonly error: SeedLimitError }> {
629
+ let refused: SeedLimitError | undefined
630
+ for (let at = choice[index] ?? 0; at < slot.options.length; at++) {
631
+ const option = slot.options[at]
632
+ if (option === undefined) continue
633
+ try {
634
+ const values = await option.values(row)
635
+ choice[index] = at
636
+ return { values }
637
+ } catch (error) {
638
+ if (!(error instanceof SeedLimitError)) throw error
639
+ refused = error
640
+ }
641
+ }
642
+ return { error: refused ?? new SeedLimitError('the isolation fixture has no value to try') }
643
+ }
644
+
645
+ /** The next combination of the `involved` slots' options, the first involved changing first; `false` once all were tried. */
646
+ function advanceChoice(slots: readonly Slot[], choice: number[], involved: readonly number[]): boolean {
647
+ for (const index of involved) {
648
+ const at = choice[index] ?? 0
649
+ if (at + 1 < (slots[index]?.options.length ?? 0)) {
650
+ choice[index] = at + 1
651
+ return true
652
+ }
653
+ choice[index] = 0
654
+ }
655
+ return false
656
+ }
296
657
  /** The digest of the empty object a seeded file stands for. */
297
658
  const EMPTY_SHA256 = createHash('sha256').digest('hex')
298
659
 
@@ -305,6 +666,7 @@ export const SEEDED_OBJECT_VERSION = '"seeded"'
305
666
  /** The isolation fixtures over the schema `backend` describes. */
306
667
  export function testSeeding(backend: SeedingBackend): TestSeeding {
307
668
  let checks: Promise<readonly CheckConstraint[]> | undefined
669
+ let uniqueIndexes: Promise<readonly UniqueIndex[]> | undefined
308
670
  const seededObjects: string[] = []
309
671
 
310
672
  /** The CHECK constraints that name `column` of `table`. */
@@ -325,9 +687,55 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
325
687
  return column.nullable ? null : undefined
326
688
  }
327
689
 
328
- /** A required column's sample: an `IN` list's first value where a CHECK names one, else a sample of its type. */
329
- async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
330
- return (await checkedValue(table, column)) ?? column.sample()
690
+ async function uniqueIndexesOf(table: string): Promise<readonly UniqueIndex[]> {
691
+ uniqueIndexes ??= backend.uniqueIndexes()
692
+ return (await uniqueIndexes).filter((index) => index.table === table)
693
+ }
694
+
695
+ /** Whether the fixture numbers `column` (`nextNumberOf`) instead of writing its type's sample: a number a unique index covers. */
696
+ async function numbered(table: string, column: SeedColumn): Promise<boolean> {
697
+ return column.number && (await uniqueIndexesOf(table)).some((index) => index.columns.includes(column.name))
698
+ }
699
+
700
+ /**
701
+ * The number a column `numbered` names takes in `row` (column → value, as the row has them so far): the next above the
702
+ * largest of its group under every unique index that covers it, so the row collides with no row of the table, whoever
703
+ * wrote it. The group is the rows that hold the index's other columns as `row` does: under a fresh parent it is empty
704
+ * and the number 1, which a bounded CHECK passes as before. A key column `row` holds no value for yet is left out of
705
+ * the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
706
+ */
707
+ async function nextNumberOf(
708
+ table: string,
709
+ column: SeedColumn,
710
+ row: ReadonlyMap<string, SampleValue>,
711
+ ungrouped: ReadonlySet<string> = new Set(),
712
+ ): Promise<SampleValue> {
713
+ const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
714
+ const groups: Map<string, SampleValue>[] = []
715
+ for (const index of covering) {
716
+ const group = new Map<string, SampleValue>()
717
+ for (const other of index.columns) {
718
+ if (other !== column.name && row.has(other) && !ungrouped.has(other)) group.set(other, row.get(other) ?? null)
719
+ }
720
+ if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
721
+ }
722
+ if (groups.length === 0) return column.sample(0)
723
+ const next = await backend.nextNumber(table, column.name, groups)
724
+ if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
725
+ return next
726
+ }
727
+
728
+ /** 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. */
729
+ async function requiredSample(model: TableModel, column: SeedColumn): Promise<SampleValue> {
730
+ const checked = await checkedValue(model.name, column)
731
+ if (checked !== undefined) return checked
732
+ return (await numbered(model.name, column)) ? nextNumberOf(model.name, column, new Map()) : sampleOf(model, column, 0)
733
+ }
734
+
735
+ /** A sample of `column`'s type; of a JSON column whose policy declares a schema, one the schema accepts (`jsonSample`). */
736
+ function sampleOf(model: TableModel | undefined, column: SeedColumn, variant: number): SampleValue {
737
+ const schema = model === undefined ? undefined : ownEntry(model.jsonSchemas, column.name)
738
+ return model === undefined || schema === undefined ? column.sample(variant) : jsonSample(schema, `${model.name}.${column.name}`)
331
739
  }
332
740
 
333
741
  function columnsOf(table: string): readonly SeedColumn[] {
@@ -347,9 +755,9 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
347
755
  }
348
756
 
349
757
  /** A column the seeded row left to its default: null only where the column admits it. */
350
- async function updateSample(table: string, name: string): Promise<SampleValue> {
351
- const column = columnOf(table, name)
352
- return column.nullable ? null : requiredSample(table, column)
758
+ async function updateSample(model: TableModel, name: string): Promise<SampleValue> {
759
+ const column = columnOf(model.name, name)
760
+ return column.nullable ? null : requiredSample(model, column)
353
761
  }
354
762
 
355
763
  /** Whether the fixture writes a marker into `column`: text that holds no foreign key and that no CHECK names. */
@@ -358,53 +766,143 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
358
766
  return isMarkable(column) && !keyed && (await checksOn(table, column.name)).length === 0
359
767
  }
360
768
 
769
+ /** The open columns of `key` as the referenced row holds them. */
770
+ function keyValues(key: ForeignKey, open: readonly string[], row: Readonly<Record<string, unknown>>): Map<string, SampleValue> {
771
+ const values = new Map<string, SampleValue>()
772
+ key.columns.forEach((name, index) => {
773
+ const referenced = key.references[index] ?? ''
774
+ if (open.includes(name)) values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
775
+ })
776
+ return values
777
+ }
778
+
361
779
  /**
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.
780
+ * The ways to fill a foreign key outside the containment chain: `null` where every open column admits it, an existing
781
+ * row of an unscoped table (a reference table's rows come from a migration), and a row the fixture inserts, which
782
+ * `inserted` records when given. A row of a dimension or child table is always a fresh one: an existing one lies in
783
+ * another chain. The key's columns the row already holds (a tenant-holding key's ancestors) the referenced row holds too.
366
784
  */
367
- async function referencedKey(
785
+ async function referenceSlot(
368
786
  models: TableModels,
369
787
  table: string,
370
788
  key: ForeignKey,
371
789
  open: readonly string[],
790
+ assigned: ReadonlyMap<string, SampleValue>,
372
791
  depth: number,
373
792
  inserted?: InsertedRow[],
374
- ) {
793
+ ): Promise<Slot> {
375
794
  const columns = columnsOf(table)
376
- const values = new Map<string, SampleValue>()
795
+ const options: SlotOption[] = []
377
796
  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
797
+ options.push({ grouped: false, values: async () => new Map(open.map((name) => [name, null])) })
798
+ }
799
+ // The key's columns the row holds already, or another slot fills first (a column two keys share), as the referenced
800
+ // row names them.
801
+ const shared = key.columns.filter((name) => !open.includes(name))
802
+ const fixedOf = (row: ReadonlyMap<string, SampleValue>): Map<string, SampleValue> => {
803
+ const fixed = new Map<string, SampleValue>()
804
+ key.columns.forEach((name, index) => {
805
+ if (shared.includes(name)) fixed.set(key.references[index] ?? '', row.get(name) ?? null)
806
+ })
807
+ return fixed
380
808
  }
381
809
  const target = modelOf(models, key.table)
382
810
  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) {
811
+ const refused = key.table === table
812
+ ? 'which references its own table'
813
+ : depth >= MAX_REFERENCE_DEPTH
814
+ ? `whose referenced rows nest deeper than ${MAX_REFERENCE_DEPTH}`
815
+ : undefined
816
+ if (refused === undefined) {
817
+ if (!scoped) {
818
+ options.push(keptOption(async (row) => {
819
+ const existing = await backend.firstRow(key.table, key.references, fixedOf(row))
820
+ if (existing === undefined) throw new SeedLimitError(`the isolation fixture finds no row of ${key.table} to reference`)
821
+ return keyValues(key, open, existing)
822
+ }, shared))
823
+ }
824
+ options.push(keptOption(async (row) => keyValues(key, open, await freshRow(models, key, fixedOf(row), depth + 1, inserted)), shared))
825
+ }
826
+ if (options.length === 0) {
384
827
  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`,
828
+ `the isolation fixture cannot fill ${table}.${open.join(', ')}: a required foreign key to ${key.table} outside the containment chain, ${refused}`,
388
829
  )
389
830
  }
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
831
+ return { columns: open, options, reads: shared.filter((name) => !assigned.has(name)) }
832
+ }
833
+
834
+ /**
835
+ * Gives each dimension of `model`'s chain that `values` lacks a fresh value, and inserts the row of each such
836
+ * container a table owns, outermost first; `inserted` records them when given.
837
+ */
838
+ async function placeContainers(
839
+ models: TableModels,
840
+ model: TableModel,
841
+ values: Map<string, string>,
842
+ world: string,
843
+ depth: number,
844
+ inserted?: InsertedRow[],
845
+ ): Promise<void> {
846
+ for (let index = model.chain.length - 1; index >= 0; index--) {
847
+ const link = model.chain[index]
848
+ if (link === undefined || values.has(link.dimension)) continue
849
+ const value = scopeValue(model.name, link.column, link.dimension, world)
850
+ values.set(link.dimension, value)
851
+ const owner = ownerOf(models, link.dimension)
852
+ if (owner === undefined || owner.name === model.name || owner.scope.mode !== 'dimension') continue
853
+ await insert(models, owner.name, placement(owner, values, value), [], depth, inserted)
854
+ inserted?.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
855
+ }
856
+ }
857
+
858
+ /**
859
+ * A fresh row of the table `key` references, holding `fixed` (referenced column → value), as stored. A row of a dimension
860
+ * or child table lies in the chain `fixed` holds of it, else in fresh values with containers of its own.
861
+ */
862
+ async function freshRow(
863
+ models: TableModels,
864
+ key: ForeignKey,
865
+ fixed: ReadonlyMap<string, SampleValue>,
866
+ depth: number,
867
+ inserted?: InsertedRow[],
868
+ ): Promise<Readonly<Record<string, unknown>>> {
869
+ const target = modelOf(models, key.table)
870
+ const scope = target?.scope
871
+ if (target === undefined || scope === undefined || (scope.mode !== 'dimension' && scope.mode !== 'child')) {
872
+ const { stored } = await insert(models, key.table, fixed, [], depth, inserted)
873
+ inserted?.push({
874
+ table: key.table,
875
+ match: new Map(key.references.map((name) => [name, keyValue(stored[name], `${key.table}.${name}`)])),
876
+ })
877
+ return stored
878
+ }
879
+ if (fixed.has(scope.key)) {
880
+ throw new SeedLimitError(`the isolation fixture cannot insert a row of ${key.table} whose key the referencing row fixes`)
881
+ }
882
+ const values = new Map<string, string>()
883
+ for (const link of target.chain) {
884
+ const value = fixed.get(link.column)
885
+ if (value !== undefined && value !== null) values.set(link.dimension, String(value))
886
+ }
887
+ await placeContainers(models, target, values, 'referenced', depth, inserted)
888
+ const rowKey = scopeValue(target.name, scope.key, scope.mode === 'dimension' ? scope.dimension : target.name, 'referenced')
889
+ const assigned = placement(target, values, rowKey)
890
+ for (const [name, value] of fixed) {
891
+ if (!assigned.has(name)) assigned.set(name, value)
892
+ }
893
+ const { stored } = await insert(models, target.name, assigned, [], depth, inserted)
894
+ inserted?.push({ table: target.name, match: new Map([[scope.key, rowKey]]) })
895
+ return stored
401
896
  }
402
897
 
403
- /** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
898
+ /**
899
+ * A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. Either
900
+ * holds a random v4 uuid's 122 bits, so a large seed never collides on a key.
901
+ */
404
902
  function scopeValue(table: string, name: string, dimension: string, world: string): string {
405
903
  const column = columnOf(table, name)
406
904
  if (column.uuid) return crypto.randomUUID()
407
- if (column.text) return `${dimension}-${world}-${randomHex()}`
905
+ if (column.text) return `${dimension}-${world}-${crypto.randomUUID()}`
408
906
  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
907
  }
410
908
 
@@ -422,11 +920,74 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
422
920
  }
423
921
 
424
922
  /**
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.
923
+ * The ways to fill `column`: a file column a seeded file; a column a CHECK names the `IN` list's first value or `null`,
924
+ * then every value the CHECKs naming it list or compare with, and samples of its type; a text column a marker; any other
925
+ * nullable column `null`; a number a unique index covers its next number in the row's group; else samples of its type.
926
+ */
927
+ async function columnSlot(
928
+ model: TableModel | undefined,
929
+ table: string,
930
+ column: SeedColumn,
931
+ markers: string[],
932
+ inserted: InsertedRow[] | undefined,
933
+ ungrouped: ReadonlySet<string>,
934
+ ): Promise<Slot> {
935
+ const name = column.name
936
+ const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
937
+ const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(sampleOf(model, column, variant)) })
938
+ const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
939
+ const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
940
+ const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
941
+ if (kind !== undefined) {
942
+ return {
943
+ columns: [name],
944
+ options: [keptOption(async () => single(await seedFile(kind, inserted))), ...(column.nullable ? [valueOption(name, null)] : [])],
945
+ }
946
+ }
947
+ const named = await checksOn(table, name)
948
+ const isNumbered = await numbered(table, column)
949
+ if (named.length > 0) {
950
+ const checked = await checkedValue(table, column)
951
+ const first = checked === undefined ? (isNumbered ? next : sampled(0)) : valueOption(name, checked)
952
+ const tried: SampleValue[] = column.nullable ? [null] : []
953
+ for (const check of named) {
954
+ for (const literal of [...check.values, ...check.literals]) tried.push(...literalValues(column, literal))
955
+ }
956
+ const listed = [...new Set(tried)].filter((value) => value !== checked).map((value) => valueOption(name, value))
957
+ return { columns: [name], options: [first, ...listed, ...(isNumbered ? [next] : []), ...samples] }
958
+ }
959
+ if (await holdsMarker(model, table, column)) {
960
+ return {
961
+ columns: [name],
962
+ options: [keptOption(async () => {
963
+ const marker = `m${randomHex()}${randomHex()}`
964
+ markers.push(marker)
965
+ return single(marker)
966
+ })],
967
+ }
968
+ }
969
+ if (column.nullable) return { columns: [name], options: [valueOption(name, null)] }
970
+ return { columns: [name], options: isNumbered ? [next] : samples }
971
+ }
972
+
973
+ /** The columns of the constraint a row failed, or `undefined` when the seeding cannot tell (an index on an expression). */
974
+ async function violatedColumns(table: string, violation: Violation): Promise<readonly string[] | undefined> {
975
+ if (violation.columns !== undefined) return violation.columns
976
+ if (violation.kind === 'check') {
977
+ checks ??= backend.checks()
978
+ return (await checks).find((check) => check.table === table && check.name === violation.name)?.columns
979
+ }
980
+ return (await uniqueIndexesOf(table)).find((index) => index.name === violation.name)?.columns
981
+ }
982
+
983
+ /**
984
+ * Inserts one row: `assigned` as given, every other column a database default leaves open filled by its slot
985
+ * (`columnSlot`, `referenceSlot`), each slot's first option first. When the database refuses the row for a CHECK or
986
+ * a unique index, the fixture tries the next combination of the options of the slots that constraint names (all of
987
+ * them when it names none it can read), up to `MAX_ROW_ATTEMPTS` rows; the last refusal is the `SeedLimitError`.
988
+ * Answers what the fixture wrote, and the row as stored (its database defaults filled). `inserted` records every row
989
+ * a foreign key or a file column made it insert, not the row itself. A number a unique index covers is numbered within
990
+ * its group without the columns in `ungrouped` (a container the row will not lie in).
430
991
  */
431
992
  async function insert(
432
993
  models: TableModels,
@@ -435,42 +996,66 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
435
996
  markers: string[],
436
997
  depth = 0,
437
998
  inserted?: InsertedRow[],
999
+ ungrouped: ReadonlySet<string> = new Set(),
438
1000
  ): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
439
1001
  const model = modelOf(models, table)
440
1002
  const columns = columnsOf(table)
441
- // A column with a database default keeps it unless the fixture assigned it, a foreign key's included.
1003
+ // A column with a database default keeps it unless the fixture assigned it or fills a foreign key over it.
442
1004
  const defaulted = new Set(columns.filter((column) => column.defaulted).map((column) => column.name))
443
- const keyed = new Map<string, SampleValue>()
1005
+ const slots: Slot[] = []
1006
+ const slotted = new Set<string>()
444
1007
  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)
1008
+ const open = key.columns.filter((column) => !assigned.has(column) && !slotted.has(column))
1009
+ // A key whose columns all have defaults keeps them; one the fixture fills fills its defaulted columns too, which
1010
+ // alone may name no row the key's other columns pick.
1011
+ if (open.every((column) => defaulted.has(column))) continue
1012
+ slots.push(await referenceSlot(models, table, key, open, assigned, depth, inserted))
1013
+ for (const name of open) slotted.add(name)
448
1014
  }
449
- const row = new Map<string, SampleValue>()
450
1015
  for (const column of columns) {
451
- const name = column.name
452
1016
  // 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
1017
+ if (assigned.has(column.name) || column.defaulted || slotted.has(column.name)) continue
1018
+ slots.push(await columnSlot(model, table, column, markers, inserted, ungrouped))
1019
+ }
1020
+ const order = slotOrder(slots)
1021
+ const choice = slots.map(() => 0)
1022
+ const involved: number[] = []
1023
+ // The refusal of the row the fixture prefers, which the error names once no other row passes.
1024
+ let refused: SeedLimitError | undefined
1025
+ for (let attempt = 0; attempt < MAX_ROW_ATTEMPTS; attempt++) {
1026
+ const row = new Map(assigned)
1027
+ let complete = true
1028
+ for (const index of order) {
1029
+ const slot = slots[index]
1030
+ if (slot === undefined) continue
1031
+ const picked = await pickOption(slot, choice, index, row)
1032
+ if ('error' in picked) {
1033
+ // No option of the slot is usable from its current one on: the next combination, or the reason.
1034
+ if ((choice[index] ?? 0) === 0 || !involved.includes(index)) throw picked.error
1035
+ refused ??= picked.error
1036
+ complete = false
1037
+ break
1038
+ }
1039
+ for (const [name, value] of picked.values) row.set(name, value)
457
1040
  }
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())
1041
+ if (complete) {
1042
+ try {
1043
+ return { row, stored: await backend.insert(table, row) }
1044
+ } catch (error) {
1045
+ if (!(error instanceof ConstraintLimitError) || error.violation.kind === 'foreign') throw error
1046
+ refused ??= error
1047
+ const named = await violatedColumns(table, error.violation)
1048
+ const touched = [...slots.keys()].filter((index) => named === undefined || (slots[index]?.columns ?? []).some((name) => named.includes(name)))
1049
+ // A constraint over the assigned columns only has nothing to try.
1050
+ if (touched.length === 0) throw error
1051
+ for (const index of touched) {
1052
+ if (!involved.includes(index)) involved.push(index)
1053
+ }
1054
+ }
471
1055
  }
1056
+ if (!advanceChoice(slots, choice, involved)) break
472
1057
  }
473
- return { row, stored: await backend.insert(table, row) }
1058
+ throw refused ?? new SeedLimitError(`the isolation fixture tried ${MAX_ROW_ATTEMPTS} rows of ${table}`)
474
1059
  }
475
1060
 
476
1061
  /** 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 +1126,137 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
541
1126
  /** The value a pin gives the row of `world`: as written in the own row, distinct in the other. */
542
1127
  const pinnedValue = (value: string, world: string): string => (world === 'own' ? value : `${value}-${world}`)
543
1128
 
1129
+ /**
1130
+ * The dimension values the row of `owner` keyed `key` lies in, as the table stores it: its own, then each container's;
1131
+ * `undefined` when the table holds no such row.
1132
+ */
1133
+ async function storedChain(owner: TableModel, key: string): Promise<ReadonlyMap<string, string> | undefined> {
1134
+ const scope = owner.scope
1135
+ if (scope.mode !== 'dimension') return undefined
1136
+ const row = await backend.firstRow(owner.name, [scope.key, ...owner.chain.map((link) => link.column)], new Map([[scope.key, key]]))
1137
+ if (row === undefined) return undefined
1138
+ const chain = new Map([[scope.dimension, key]])
1139
+ for (const link of owner.chain) chain.set(link.dimension, String(keyValue(row[link.column], `${owner.name}.${link.column}`)))
1140
+ return chain
1141
+ }
1142
+
1143
+ /**
1144
+ * The dimension values a row of `model` lies in for `world`, as far as `scopes` know them: each known value, and every
1145
+ * value a stored row of a known one holds. `stored` are the dimensions whose row a table holds already.
1146
+ */
1147
+ async function knownValues(
1148
+ models: TableModels,
1149
+ model: TableModel,
1150
+ world: 'own' | 'other',
1151
+ scopes: ScopeValues,
1152
+ ): Promise<{ readonly values: Map<string, string>; readonly stored: ReadonlySet<string> }> {
1153
+ const own = model.scope.mode === 'dimension' ? [model.scope.dimension] : []
1154
+ const dimensions = [...own, ...model.chain.map((link) => link.dimension)].filter((dimension) => Object.hasOwn(scopes, dimension))
1155
+ const values = new Map<string, string>()
1156
+ for (const dimension of dimensions) {
1157
+ const known = scopes[dimension]
1158
+ if (known !== undefined) values.set(dimension, world === 'own' ? known.own : known.other)
1159
+ }
1160
+ const stored = new Set<string>()
1161
+ for (const dimension of dimensions) {
1162
+ const owner = ownerOf(models, dimension)
1163
+ const value = values.get(dimension)
1164
+ const chain = owner === undefined || value === undefined ? undefined : await storedChain(owner, value)
1165
+ for (const [type, found] of chain ?? []) {
1166
+ const expected = values.get(type)
1167
+ if (expected !== undefined && expected !== found) {
1168
+ throw new Error(`the stored ${dimension} '${value}' lies in the ${type} '${found}', not in the known '${expected}'`)
1169
+ }
1170
+ values.set(type, found)
1171
+ stored.add(type)
1172
+ }
1173
+ }
1174
+ return { values, stored }
1175
+ }
1176
+
1177
+ /** The values of the text columns that would hold a marker in the stored row of `model` keyed `key`. */
1178
+ async function storedTexts(model: TableModel, key: string): Promise<string[]> {
1179
+ const scope = model.scope
1180
+ if (scope.mode !== 'dimension') return []
1181
+ const names: string[] = []
1182
+ for (const column of columnsOf(model.name)) {
1183
+ if (await holdsMarker(model, model.name, column)) names.push(column.name)
1184
+ }
1185
+ if (names.length === 0) return []
1186
+ const row = await backend.firstRow(model.name, names, new Map([[scope.key, key]]))
1187
+ return names.flatMap((name) => {
1188
+ const value = row?.[name]
1189
+ return typeof value === 'string' && value !== '' ? [value] : []
1190
+ })
1191
+ }
1192
+
544
1193
  async function seedWorld(
545
1194
  models: TableModels,
546
1195
  model: TableModel,
547
- world: string,
1196
+ world: 'own' | 'other',
548
1197
  seed: Readonly<Record<string, SampleValue>>,
549
1198
  pins: Readonly<Record<string, string>>,
1199
+ scopes: ScopeValues,
550
1200
  inserted: InsertedRow[],
551
- ): Promise<WorldRow> {
1201
+ ): Promise<{
1202
+ readonly world: Omit<WorldRow, 'updates'>
1203
+ readonly row: ReadonlyMap<string, SampleValue>
1204
+ /** The row as stored, its defaults filled. */
1205
+ readonly holds: Readonly<Record<string, unknown>>
1206
+ }> {
552
1207
  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
1208
  const scope = model.scope
559
1209
  if (scope.mode !== 'dimension' && scope.mode !== 'child') {
560
1210
  throw new Error(`${model.name} is not a dimension or child table`)
561
1211
  }
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)
1212
+ const { values, stored } = await knownValues(models, model, world, scopes)
1213
+ const links: readonly Container[] = model.chain
1214
+ for (const link of links) {
1215
+ if (!values.has(link.dimension)) values.set(link.dimension, scopeValue(model.name, link.column, link.dimension, world))
1216
+ }
1217
+ const own = scope.mode === 'dimension' ? scope.dimension : undefined
1218
+ const key = (own === undefined ? undefined : values.get(own)) ?? scopeValue(model.name, scope.key, own ?? model.name, world)
1219
+ if (own !== undefined) {
1220
+ values.set(own, key)
1221
+ }
1222
+ const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[], holds: Readonly<Record<string, unknown>> = {}) => {
1223
+ const chain = [
1224
+ ...(own === undefined ? [] : [{ type: own, value: key }]),
1225
+ ...links.flatMap((link) => {
1226
+ const value = values.get(link.dimension)
1227
+ return value === undefined ? [] : [{ type: link.dimension, value }]
1228
+ }),
1229
+ ]
1230
+ const seeded = {
1231
+ key,
1232
+ parent: scope.mode === 'child' ? (values.get(links[0]?.dimension ?? '') ?? null) : null,
1233
+ scope: values.get(grantDimension(models, model)) ?? key,
1234
+ chain,
1235
+ markers,
1236
+ stored,
1237
+ }
1238
+ return { world: seeded, row, holds }
1239
+ }
1240
+ if (own !== undefined && stored.has(own)) {
1241
+ if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
1242
+ throw new Error(
1243
+ `${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`,
1244
+ )
1245
+ }
1246
+ return worldRow(new Map(), await storedTexts(model, key))
565
1247
  }
566
- // Containers first, outermost first: a composite foreign key needs its target row.
1248
+ // Containers first, outermost first: a composite foreign key needs its target row. A stored one is used as it is.
567
1249
  for (let index = links.length - 1; index >= 0; index--) {
568
1250
  const link = links[index]
569
1251
  const owner = link === undefined ? undefined : ownerOf(models, link.dimension)
570
1252
  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)
1253
+ if (link === undefined || owner === undefined || owner.name === model.name || value === undefined || stored.has(link.dimension)) continue
1254
+ // With known values, every container goes with the worlds: one of a known value, so the next case can insert it
1255
+ // again, and one inside a stored row, which no removal of that row reaches.
1256
+ const tracked = Object.keys(scopes).length > 0 ? inserted : undefined
1257
+ await insert(models, owner.name, placement(owner, values, value), markers, 0, tracked)
1258
+ if (tracked !== undefined && owner.scope.mode === 'dimension') {
1259
+ tracked.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
573
1260
  }
574
1261
  }
575
1262
  const assigned = placement(model, values, key)
@@ -597,39 +1284,70 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
597
1284
  assigned.set(name, pinned)
598
1285
  markers.push(pinned)
599
1286
  }
600
- const { row } = await insert(models, model.name, assigned, markers)
1287
+ const { row, stored: holds } = await insert(models, model.name, assigned, markers, 0, inserted)
601
1288
  inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
1289
+ return worldRow(row, [], holds)
1290
+ }
1291
+
1292
+ /** `work`, after which a failure removes the rows it recorded in `inserted` before it rethrows. */
1293
+ async function removedOnFailure<T>(inserted: readonly InsertedRow[], what: string, work: () => Promise<T>): Promise<T> {
1294
+ try {
1295
+ return await work()
1296
+ } catch (error) {
1297
+ try {
1298
+ await backend.remove(inserted)
1299
+ } catch (cleanup) {
1300
+ throw new AggregateError([error, cleanup], `the isolation fixture could not ${what}, nor remove what it had seeded`)
1301
+ }
1302
+ throw error
1303
+ }
1304
+ }
1305
+
1306
+ /**
1307
+ * A seeded row's values of the policy's update columns, which its CHECKs accepted: as written, as stored where the
1308
+ * database filled the column (a default), or a sample where the stored value is no plain value.
1309
+ */
1310
+ async function updatesOf(
1311
+ model: TableModel,
1312
+ row: ReadonlyMap<string, SampleValue>,
1313
+ stored: Readonly<Record<string, unknown>> = {},
1314
+ ): Promise<Record<string, SampleValue>> {
602
1315
  const updates: Record<string, SampleValue> = {}
603
1316
  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,
1317
+ const written = row.get(name)
1318
+ const kept = written === undefined ? plainValue(stored[name]) : written
1319
+ updates[name] = kept === undefined ? await updateSample(model, name) : kept
621
1320
  }
1321
+ return updates
622
1322
  }
623
1323
 
624
1324
  return {
625
- async seedWorlds(tables, table, values = {}, pins = {}) {
1325
+ async seedWorlds(tables, table, values = {}, pins = {}, scopes = {}) {
626
1326
  const { models, model } = scopedModel(tables, table)
627
1327
  const dimension = grantDimension(models, model)
1328
+ for (const [name, known] of Object.entries(scopes)) {
1329
+ if (known.own === known.other) throw new Error(`the two worlds share the ${name} '${known.own}'; each needs a value of its own`)
1330
+ }
628
1331
  const inserted: InsertedRow[] = []
1332
+ let own: Awaited<ReturnType<typeof seedWorld>>
1333
+ let other: Awaited<ReturnType<typeof seedWorld>>
1334
+ try {
1335
+ own = await seedWorld(models, model, 'own', values, pins, scopes, inserted)
1336
+ other = await seedWorld(models, model, 'other', values, pins, scopes, inserted)
1337
+ } catch (error) {
1338
+ // A row of a known value left behind would pass for one a migration wrote in every later case.
1339
+ try {
1340
+ await backend.remove(inserted)
1341
+ } catch (cleanup) {
1342
+ throw new AggregateError([error, cleanup], 'the isolation fixture could not seed the worlds, nor remove what it had seeded')
1343
+ }
1344
+ throw error
1345
+ }
1346
+ // Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
629
1347
  return {
630
1348
  dimension,
631
- own: await seedWorld(models, model, 'own', values, pins, inserted),
632
- other: await seedWorld(models, model, 'other', values, pins, inserted),
1349
+ own: { ...own.world, updates: await updatesOf(model, own.row, own.holds) },
1350
+ other: { ...other.world, updates: await updatesOf(model, other.row, other.holds) },
633
1351
  remove: () => backend.remove(inserted),
634
1352
  }
635
1353
  },
@@ -637,12 +1355,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
637
1355
  const { models, model } = scopedModel(tables, table)
638
1356
  checkApplicationValues(models, { [table]: values })
639
1357
  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 }
1358
+ const { key, row, stored } = await seedApplicationRow(models, model, values, new Map(), markers)
1359
+ return { key, updates: await updatesOf(model, row, stored), markers }
646
1360
  },
647
1361
  async seedApplicationRows(tables, rows) {
648
1362
  const models = tableModels(tables)
@@ -694,25 +1408,35 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
694
1408
  }
695
1409
  const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
696
1410
  const markers: string[] = []
697
- await insert(models, table, placement(model, values, key), markers)
698
- return { key, markers }
1411
+ const inserted: InsertedRow[] = []
1412
+ await removedOnFailure(inserted, 'seed the row', () => insert(models, table, placement(model, values, key), markers, 0, inserted))
1413
+ inserted.push({ table, match: new Map([[scope.key, key]]) })
1414
+ return { key, markers, remove: () => backend.remove(inserted) }
699
1415
  },
700
- async sampleInsert(tables, table) {
1416
+ async sampleInsert(tables, table, beside) {
701
1417
  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
1418
+ const scope = model.scope
1419
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
1420
+ throw new Error(`${table} is a ${scope.mode} table; no store inserts into it`)
709
1421
  }
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)
1422
+ // A probe row the database judges, placed as the insert will place it (in `beside`'s containers, else in fresh
1423
+ // ones it removes with the probe), numbered within the containers known; its values are the sample.
1424
+ const values = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
1425
+ const ungrouped = new Set(model.chain.filter((link) => !values.has(link.dimension)).map((link) => link.column))
1426
+ const placed: InsertedRow[] = []
1427
+ const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'probe')
1428
+ const { row } = await removedOnFailure(placed, 'insert a probe row', async () => {
1429
+ await placeContainers(models, model, values, 'probe', 0, placed)
1430
+ return insert(models, table, placement(model, values, key), [], 0, undefined, ungrouped)
1431
+ })
1432
+ await backend.remove([{ table, match: new Map([[scope.key, key]]) }, ...placed])
1433
+ const sample: Record<string, SampleValue> = {}
1434
+ for (const column of columnsOf(table)) {
1435
+ if (!inSet(model.insert, column.name) || !row.has(column.name)) continue
1436
+ // A nullable column a CHECK ties to another is written as the probe held it; any other is left to the insert.
1437
+ if (isRequired(column) || (await checksOn(table, column.name)).length > 0) sample[column.name] = row.get(column.name) ?? null
714
1438
  }
715
- return values
1439
+ return sample
716
1440
  },
717
1441
  seededObjects: () => [...seededObjects],
718
1442
  }