@fabrika/db 0.9.0-dev.17 → 0.9.0-dev.18
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.
- package/package.json +4 -4
- package/src/testing-shared.ts +476 -130
- package/src/testing-sqlite.ts +70 -23
- package/src/testing.ts +55 -17
- package/types/src/testing-shared.d.ts +32 -11
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/db",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.18",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -92,9 +92,9 @@
|
|
|
92
92
|
"test": "bun test"
|
|
93
93
|
},
|
|
94
94
|
"dependencies": {
|
|
95
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
96
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
97
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
95
|
+
"@fabrika/auth-core": "0.9.0-dev.18",
|
|
96
|
+
"@fabrika/platform": "0.9.0-dev.18",
|
|
97
|
+
"@fabrika/platform-node": "0.9.0-dev.18",
|
|
98
98
|
"kysely": "0.29.6",
|
|
99
99
|
"kysely-postgres-js": "5.0.1",
|
|
100
100
|
"zod": "^3.25.76"
|
package/src/testing-shared.ts
CHANGED
|
@@ -39,7 +39,7 @@ export interface WorldRow {
|
|
|
39
39
|
* share link's chain is this list.
|
|
40
40
|
*/
|
|
41
41
|
readonly chain: readonly { readonly type: string; readonly value: string }[]
|
|
42
|
-
/** The row's values of the policy's update columns, as
|
|
42
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
43
43
|
readonly updates: Readonly<Record<string, SampleValue>>
|
|
44
44
|
/**
|
|
45
45
|
* The distinct value written into every text column the fixture filled itself, in this row and in its containers.
|
|
@@ -56,7 +56,7 @@ export interface WorldRow {
|
|
|
56
56
|
/** One seeded row of an application table, which lies in no dimension. */
|
|
57
57
|
export interface ApplicationRow {
|
|
58
58
|
readonly key: string
|
|
59
|
-
/** The row's values of the policy's update columns, as
|
|
59
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
60
60
|
readonly updates: Readonly<Record<string, SampleValue>>
|
|
61
61
|
/** The distinct value written into every text column the fixture filled itself. */
|
|
62
62
|
readonly markers: readonly string[]
|
|
@@ -83,14 +83,33 @@ export interface SeededRow {
|
|
|
83
83
|
}
|
|
84
84
|
|
|
85
85
|
/**
|
|
86
|
-
* What the isolation fixture cannot seed for a schema: a CHECK
|
|
87
|
-
*
|
|
88
|
-
* failure of the handler or the policy a case is about.
|
|
86
|
+
* What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
|
|
87
|
+
* foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
|
|
88
|
+
* column, never a failure of the handler or the policy a case is about.
|
|
89
89
|
*/
|
|
90
90
|
export class SeedLimitError extends Error {
|
|
91
91
|
override readonly name = 'SeedLimitError'
|
|
92
92
|
}
|
|
93
93
|
|
|
94
|
+
/** The constraint a seeded row failed, as a backend reads it off the database's error. */
|
|
95
|
+
export interface Violation {
|
|
96
|
+
readonly kind: 'check' | 'unique' | 'foreign'
|
|
97
|
+
/** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
|
|
98
|
+
readonly name: string
|
|
99
|
+
/** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
|
|
100
|
+
readonly columns?: readonly string[]
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
|
|
104
|
+
export class ConstraintLimitError extends SeedLimitError {
|
|
105
|
+
readonly violation: Violation
|
|
106
|
+
|
|
107
|
+
constructor(message: string, violation: Violation) {
|
|
108
|
+
super(message)
|
|
109
|
+
this.violation = violation
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
94
113
|
/** One row of a table in each of two containment chains that share no value. */
|
|
95
114
|
export interface IsolationWorlds {
|
|
96
115
|
/**
|
|
@@ -197,8 +216,12 @@ export interface SeedColumn {
|
|
|
197
216
|
readonly number: boolean
|
|
198
217
|
/** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
|
|
199
218
|
readonly json: boolean
|
|
200
|
-
/**
|
|
201
|
-
|
|
219
|
+
/**
|
|
220
|
+
* A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
|
|
221
|
+
* cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
|
|
222
|
+
* day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
|
|
223
|
+
*/
|
|
224
|
+
readonly sample: (variant: number) => Primitive
|
|
202
225
|
}
|
|
203
226
|
|
|
204
227
|
/** A CHECK constraint of the schema, by the columns it names. */
|
|
@@ -207,9 +230,14 @@ export interface CheckConstraint {
|
|
|
207
230
|
readonly table: string
|
|
208
231
|
readonly columns: readonly string[]
|
|
209
232
|
/** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
|
|
210
|
-
readonly values: readonly
|
|
233
|
+
readonly values: readonly CheckLiteral[]
|
|
234
|
+
/** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
|
|
235
|
+
readonly literals: readonly CheckLiteral[]
|
|
211
236
|
}
|
|
212
237
|
|
|
238
|
+
/** A literal of a CHECK expression. */
|
|
239
|
+
export type CheckLiteral = string | number
|
|
240
|
+
|
|
213
241
|
/**
|
|
214
242
|
* A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
|
|
215
243
|
* plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
|
|
@@ -279,34 +307,39 @@ export interface SeedingBackend {
|
|
|
279
307
|
}
|
|
280
308
|
|
|
281
309
|
/** The seed limit of a CHECK a seeded row fails. */
|
|
282
|
-
export function checkLimit(constraint: string, table: string):
|
|
283
|
-
return new
|
|
284
|
-
`the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}:
|
|
310
|
+
export function checkLimit(constraint: string, table: string): ConstraintLimitError {
|
|
311
|
+
return new ConstraintLimitError(
|
|
312
|
+
`the isolation fixture cannot satisfy the CHECK ${constraint} of ${table}: no row it tried passes it (the values the CHECK names, null where a column admits it, samples of each type, fresh referenced rows)`,
|
|
313
|
+
{ kind: 'check', name: constraint },
|
|
285
314
|
)
|
|
286
315
|
}
|
|
287
316
|
|
|
288
317
|
/** The seed limit of a foreign key a seeded row breaks. */
|
|
289
|
-
export function foreignKeyLimit(constraint: string, table: string):
|
|
290
|
-
return new
|
|
318
|
+
export function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError {
|
|
319
|
+
return new ConstraintLimitError(`the isolation fixture's row of ${table} breaks the foreign key ${constraint}`, {
|
|
320
|
+
kind: 'foreign',
|
|
321
|
+
name: constraint,
|
|
322
|
+
})
|
|
291
323
|
}
|
|
292
324
|
|
|
293
325
|
/** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
|
|
294
326
|
export function uniqueLimit(index: string, table: string, column: string): SeedLimitError {
|
|
295
327
|
return new SeedLimitError(
|
|
296
|
-
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value
|
|
328
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: ${column} holds no number above its largest value`,
|
|
297
329
|
)
|
|
298
330
|
}
|
|
299
331
|
|
|
300
332
|
/** The seed limit of a row whose values another row of the table already holds under a unique index. */
|
|
301
|
-
export function uniqueValueLimit(index: string, table: string):
|
|
302
|
-
return new
|
|
303
|
-
`the isolation fixture cannot satisfy the unique index ${index} of ${table}:
|
|
333
|
+
export function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError {
|
|
334
|
+
return new ConstraintLimitError(
|
|
335
|
+
`the isolation fixture cannot satisfy the unique index ${index} of ${table}: every row it tried holds values another row holds there (samples of each type, the values a CHECK names, fresh referenced rows)`,
|
|
336
|
+
columns === undefined ? { kind: 'unique', name: index } : { kind: 'unique', name: index, columns },
|
|
304
337
|
)
|
|
305
338
|
}
|
|
306
339
|
|
|
307
340
|
/** The seed limit of a required column whose type the fixture has no sample of. */
|
|
308
341
|
export function typeLimit(table: string, column: string, type: string): SeedLimitError {
|
|
309
|
-
return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type})
|
|
342
|
+
return new SeedLimitError(`the isolation fixture cannot fill ${table}.${column} (${type}): it has no sample of that type`)
|
|
310
343
|
}
|
|
311
344
|
|
|
312
345
|
/**
|
|
@@ -341,6 +374,14 @@ function applicationRowError(refusal: ApplicationRowRefusal): Error {
|
|
|
341
374
|
}
|
|
342
375
|
|
|
343
376
|
/** A key value as the database returned it, for the foreign key that references it. */
|
|
377
|
+
/** `value` as the fixture can write it back, or `undefined` when it is none it writes (a JSON object, bytes). */
|
|
378
|
+
function plainValue(value: unknown): SampleValue | undefined {
|
|
379
|
+
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
380
|
+
return value
|
|
381
|
+
}
|
|
382
|
+
return value instanceof Date ? value : undefined
|
|
383
|
+
}
|
|
384
|
+
|
|
344
385
|
function keyValue(value: unknown, where: string): SampleValue {
|
|
345
386
|
if (value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {
|
|
346
387
|
return value
|
|
@@ -395,7 +436,124 @@ function ownerOf(models: TableModels, dimension: string): TableModel | undefined
|
|
|
395
436
|
}
|
|
396
437
|
|
|
397
438
|
/** How many referenced rows deep the fixture follows required foreign keys outside the chain before it gives up. */
|
|
398
|
-
const MAX_REFERENCE_DEPTH =
|
|
439
|
+
const MAX_REFERENCE_DEPTH = 16
|
|
440
|
+
/** How many rows the fixture tries for one insert before it reports the last constraint they failed. */
|
|
441
|
+
const MAX_ROW_ATTEMPTS = 64
|
|
442
|
+
/** How many samples of its type the fixture tries in a column whose values a constraint may refuse. */
|
|
443
|
+
const SAMPLE_VARIANTS = 4
|
|
444
|
+
|
|
445
|
+
/** One way to fill a slot of a row: its values, given the row so far; a `SeedLimitError` when it has none. */
|
|
446
|
+
interface SlotOption {
|
|
447
|
+
/** It reads the row's other values (a number a unique index numbers within its group), so it is taken last and never kept. */
|
|
448
|
+
readonly grouped: boolean
|
|
449
|
+
readonly values: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Columns the fixture fills together (one column, or a foreign key's open columns) and the ways it may fill them, first
|
|
454
|
+
* first. `reads` are the columns of the row its options read, which other slots fill first.
|
|
455
|
+
*/
|
|
456
|
+
interface Slot {
|
|
457
|
+
readonly columns: readonly string[]
|
|
458
|
+
readonly options: readonly SlotOption[]
|
|
459
|
+
readonly reads?: readonly string[]
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* An option computed once for each value of `reads` in the row: a fresh referenced row is inserted once for the values
|
|
464
|
+
* it shares with the row, and again only when they change.
|
|
465
|
+
*/
|
|
466
|
+
function keptOption(
|
|
467
|
+
compute: (row: ReadonlyMap<string, SampleValue>) => Promise<ReadonlyMap<string, SampleValue>>,
|
|
468
|
+
reads: readonly string[] = [],
|
|
469
|
+
): SlotOption {
|
|
470
|
+
const computed = new Map<string, Promise<ReadonlyMap<string, SampleValue>>>()
|
|
471
|
+
return {
|
|
472
|
+
grouped: false,
|
|
473
|
+
values: (row) => {
|
|
474
|
+
const key = reads.map((name) => valueKey(row.get(name) ?? null)).join('\u0000')
|
|
475
|
+
const values = computed.get(key) ?? compute(row)
|
|
476
|
+
computed.set(key, values)
|
|
477
|
+
return values
|
|
478
|
+
},
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function valueKey(value: SampleValue): string {
|
|
483
|
+
if (value === null) return 'null'
|
|
484
|
+
return `${typeof value}:${value instanceof Date ? value.toISOString() : String(value)}`
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* The order the fixture fills `slots` in: a slot after the slots that fill the columns it reads, and a slot that numbers
|
|
489
|
+
* within the row's group last, once every other slot placed the row. A cycle keeps the declared order.
|
|
490
|
+
*/
|
|
491
|
+
function slotOrder(slots: readonly Slot[]): number[] {
|
|
492
|
+
const filledBy = new Map<string, number>()
|
|
493
|
+
slots.forEach((slot, index) => {
|
|
494
|
+
for (const name of slot.columns) filledBy.set(name, index)
|
|
495
|
+
})
|
|
496
|
+
const grouped = (index: number): boolean => slots[index]?.options.some((option) => option.grouped) ?? false
|
|
497
|
+
const pending = [...slots.keys()].sort((left, right) => Number(grouped(left)) - Number(grouped(right)))
|
|
498
|
+
const order: number[] = []
|
|
499
|
+
while (pending.length > 0) {
|
|
500
|
+
const ready = pending.findIndex((index) =>
|
|
501
|
+
(slots[index]?.reads ?? []).every((name) => {
|
|
502
|
+
const filler = filledBy.get(name)
|
|
503
|
+
return filler === undefined || filler === index || order.includes(filler)
|
|
504
|
+
})
|
|
505
|
+
)
|
|
506
|
+
const [next] = pending.splice(Math.max(ready, 0), 1)
|
|
507
|
+
if (next !== undefined) order.push(next)
|
|
508
|
+
}
|
|
509
|
+
return order
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
function valueOption(name: string, value: SampleValue): SlotOption {
|
|
513
|
+
return { grouped: false, values: async () => new Map([[name, value]]) }
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** The values a literal of a CHECK suggests for `column`: a number and its neighbours in a number column, a text in a text column. */
|
|
517
|
+
function literalValues(column: SeedColumn, literal: CheckLiteral): SampleValue[] {
|
|
518
|
+
if (column.number) return typeof literal === 'number' && Number.isSafeInteger(literal) ? [literal, literal + 1, literal - 1] : []
|
|
519
|
+
return column.text && typeof literal === 'string' ? [literal] : []
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
/** The first usable option of `slot` from `choice[index]` on, which `choice` then records; `undefined` when none is. */
|
|
523
|
+
async function pickOption(
|
|
524
|
+
slot: Slot,
|
|
525
|
+
choice: number[],
|
|
526
|
+
index: number,
|
|
527
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
528
|
+
): Promise<{ readonly values: ReadonlyMap<string, SampleValue> } | { readonly error: SeedLimitError }> {
|
|
529
|
+
let refused: SeedLimitError | undefined
|
|
530
|
+
for (let at = choice[index] ?? 0; at < slot.options.length; at++) {
|
|
531
|
+
const option = slot.options[at]
|
|
532
|
+
if (option === undefined) continue
|
|
533
|
+
try {
|
|
534
|
+
const values = await option.values(row)
|
|
535
|
+
choice[index] = at
|
|
536
|
+
return { values }
|
|
537
|
+
} catch (error) {
|
|
538
|
+
if (!(error instanceof SeedLimitError)) throw error
|
|
539
|
+
refused = error
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
return { error: refused ?? new SeedLimitError('the isolation fixture has no value to try') }
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
/** The next combination of the `involved` slots' options, the first involved changing first; `false` once all were tried. */
|
|
546
|
+
function advanceChoice(slots: readonly Slot[], choice: number[], involved: readonly number[]): boolean {
|
|
547
|
+
for (const index of involved) {
|
|
548
|
+
const at = choice[index] ?? 0
|
|
549
|
+
if (at + 1 < (slots[index]?.options.length ?? 0)) {
|
|
550
|
+
choice[index] = at + 1
|
|
551
|
+
return true
|
|
552
|
+
}
|
|
553
|
+
choice[index] = 0
|
|
554
|
+
}
|
|
555
|
+
return false
|
|
556
|
+
}
|
|
399
557
|
/** The digest of the empty object a seeded file stands for. */
|
|
400
558
|
const EMPTY_SHA256 = createHash('sha256').digest('hex')
|
|
401
559
|
|
|
@@ -446,17 +604,22 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
446
604
|
* and the number 1, which a bounded CHECK passes as before. A key column `row` holds no value for yet is left out of
|
|
447
605
|
* the group, which only widens it; an index the row holds `null` in never conflicts, unless its nulls are not distinct.
|
|
448
606
|
*/
|
|
449
|
-
async function nextNumberOf(
|
|
607
|
+
async function nextNumberOf(
|
|
608
|
+
table: string,
|
|
609
|
+
column: SeedColumn,
|
|
610
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
611
|
+
ungrouped: ReadonlySet<string> = new Set(),
|
|
612
|
+
): Promise<SampleValue> {
|
|
450
613
|
const covering = (await uniqueIndexesOf(table)).filter((index) => index.columns.includes(column.name))
|
|
451
614
|
const groups: Map<string, SampleValue>[] = []
|
|
452
615
|
for (const index of covering) {
|
|
453
616
|
const group = new Map<string, SampleValue>()
|
|
454
617
|
for (const other of index.columns) {
|
|
455
|
-
if (other !== column.name && row.has(other)) group.set(other, row.get(other) ?? null)
|
|
618
|
+
if (other !== column.name && row.has(other) && !ungrouped.has(other)) group.set(other, row.get(other) ?? null)
|
|
456
619
|
}
|
|
457
620
|
if (index.nullsNotDistinct || ![...group.values()].includes(null)) groups.push(group)
|
|
458
621
|
}
|
|
459
|
-
if (groups.length === 0) return column.sample()
|
|
622
|
+
if (groups.length === 0) return column.sample(0)
|
|
460
623
|
const next = await backend.nextNumber(table, column.name, groups)
|
|
461
624
|
if (next === undefined) throw uniqueLimit(covering.map((index) => index.name).join(', '), table, column.name)
|
|
462
625
|
return next
|
|
@@ -466,28 +629,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
466
629
|
async function requiredSample(table: string, column: SeedColumn): Promise<SampleValue> {
|
|
467
630
|
const checked = await checkedValue(table, column)
|
|
468
631
|
if (checked !== undefined) return checked
|
|
469
|
-
return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample()
|
|
470
|
-
}
|
|
471
|
-
|
|
472
|
-
/**
|
|
473
|
-
* Writes into `row` a value for each of `columns`: `chosen`'s (a file, a CHECK's value, a marker, a null), else, for a
|
|
474
|
-
* number a unique index covers, its next number once every other column places the row in its group, else a sample
|
|
475
|
-
* of its type.
|
|
476
|
-
*/
|
|
477
|
-
async function fillRow(
|
|
478
|
-
table: string,
|
|
479
|
-
columns: readonly SeedColumn[],
|
|
480
|
-
row: Map<string, SampleValue>,
|
|
481
|
-
chosen: (column: SeedColumn) => Promise<SampleValue | undefined>,
|
|
482
|
-
): Promise<void> {
|
|
483
|
-
const later: SeedColumn[] = []
|
|
484
|
-
for (const column of columns) {
|
|
485
|
-
const value = await chosen(column)
|
|
486
|
-
if (value !== undefined) row.set(column.name, value)
|
|
487
|
-
else if (await numbered(table, column)) later.push(column)
|
|
488
|
-
else row.set(column.name, column.sample())
|
|
489
|
-
}
|
|
490
|
-
for (const column of later) row.set(column.name, await nextNumberOf(table, column, row))
|
|
632
|
+
return (await numbered(table, column)) ? nextNumberOf(table, column, new Map()) : column.sample(0)
|
|
491
633
|
}
|
|
492
634
|
|
|
493
635
|
function columnsOf(table: string): readonly SeedColumn[] {
|
|
@@ -518,46 +660,133 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
518
660
|
return isMarkable(column) && !keyed && (await checksOn(table, column.name)).length === 0
|
|
519
661
|
}
|
|
520
662
|
|
|
663
|
+
/** The open columns of `key` as the referenced row holds them. */
|
|
664
|
+
function keyValues(key: ForeignKey, open: readonly string[], row: Readonly<Record<string, unknown>>): Map<string, SampleValue> {
|
|
665
|
+
const values = new Map<string, SampleValue>()
|
|
666
|
+
key.columns.forEach((name, index) => {
|
|
667
|
+
const referenced = key.references[index] ?? ''
|
|
668
|
+
if (open.includes(name)) values.set(name, keyValue(row[referenced], `${key.table}.${referenced}`))
|
|
669
|
+
})
|
|
670
|
+
return values
|
|
671
|
+
}
|
|
672
|
+
|
|
521
673
|
/**
|
|
522
|
-
* The
|
|
523
|
-
*
|
|
524
|
-
*
|
|
525
|
-
* row
|
|
674
|
+
* The ways to fill a foreign key outside the containment chain: `null` where every open column admits it, an existing
|
|
675
|
+
* row of an unscoped table (a reference table's rows come from a migration), and a row the fixture inserts, which
|
|
676
|
+
* `inserted` records when given. A row of a dimension or child table is always a fresh one: an existing one lies in
|
|
677
|
+
* another chain. The key's columns the row already holds (a tenant-holding key's ancestors) the referenced row holds too.
|
|
526
678
|
*/
|
|
527
|
-
async function
|
|
679
|
+
async function referenceSlot(
|
|
528
680
|
models: TableModels,
|
|
529
681
|
table: string,
|
|
530
682
|
key: ForeignKey,
|
|
531
683
|
open: readonly string[],
|
|
684
|
+
assigned: ReadonlyMap<string, SampleValue>,
|
|
532
685
|
depth: number,
|
|
533
686
|
inserted?: InsertedRow[],
|
|
534
|
-
) {
|
|
687
|
+
): Promise<Slot> {
|
|
535
688
|
const columns = columnsOf(table)
|
|
536
|
-
const
|
|
689
|
+
const options: SlotOption[] = []
|
|
537
690
|
if (open.every((name) => columns.find((column) => column.name === name)?.nullable === true)) {
|
|
538
|
-
|
|
539
|
-
|
|
691
|
+
options.push({ grouped: false, values: async () => new Map(open.map((name) => [name, null])) })
|
|
692
|
+
}
|
|
693
|
+
// The key's columns the row holds already, or another slot fills first (a column two keys share), as the referenced
|
|
694
|
+
// row names them.
|
|
695
|
+
const shared = key.columns.filter((name) => !open.includes(name))
|
|
696
|
+
const fixedOf = (row: ReadonlyMap<string, SampleValue>): Map<string, SampleValue> => {
|
|
697
|
+
const fixed = new Map<string, SampleValue>()
|
|
698
|
+
key.columns.forEach((name, index) => {
|
|
699
|
+
if (shared.includes(name)) fixed.set(key.references[index] ?? '', row.get(name) ?? null)
|
|
700
|
+
})
|
|
701
|
+
return fixed
|
|
540
702
|
}
|
|
541
703
|
const target = modelOf(models, key.table)
|
|
542
704
|
const scoped = target?.scope.mode === 'dimension' || target?.scope.mode === 'child'
|
|
543
|
-
|
|
705
|
+
const refused = key.table === table
|
|
706
|
+
? 'which references its own table'
|
|
707
|
+
: depth >= MAX_REFERENCE_DEPTH
|
|
708
|
+
? `whose referenced rows nest deeper than ${MAX_REFERENCE_DEPTH}`
|
|
709
|
+
: undefined
|
|
710
|
+
if (refused === undefined) {
|
|
711
|
+
if (!scoped) {
|
|
712
|
+
options.push(keptOption(async (row) => {
|
|
713
|
+
const existing = await backend.firstRow(key.table, key.references, fixedOf(row))
|
|
714
|
+
if (existing === undefined) throw new SeedLimitError(`the isolation fixture finds no row of ${key.table} to reference`)
|
|
715
|
+
return keyValues(key, open, existing)
|
|
716
|
+
}, shared))
|
|
717
|
+
}
|
|
718
|
+
options.push(keptOption(async (row) => keyValues(key, open, await freshRow(models, key, fixedOf(row), depth + 1, inserted)), shared))
|
|
719
|
+
}
|
|
720
|
+
if (options.length === 0) {
|
|
544
721
|
throw new SeedLimitError(
|
|
545
|
-
`the isolation fixture cannot fill ${table}.${
|
|
546
|
-
open.join(', ')
|
|
547
|
-
}: a required foreign key to ${key.table} outside the containment chain; give the column a default or make it nullable`,
|
|
722
|
+
`the isolation fixture cannot fill ${table}.${open.join(', ')}: a required foreign key to ${key.table} outside the containment chain, ${refused}`,
|
|
548
723
|
)
|
|
549
724
|
}
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
725
|
+
return { columns: open, options, reads: shared.filter((name) => !assigned.has(name)) }
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
/**
|
|
729
|
+
* Gives each dimension of `model`'s chain that `values` lacks a fresh value, and inserts the row of each such
|
|
730
|
+
* container a table owns, outermost first; `inserted` records them when given.
|
|
731
|
+
*/
|
|
732
|
+
async function placeContainers(
|
|
733
|
+
models: TableModels,
|
|
734
|
+
model: TableModel,
|
|
735
|
+
values: Map<string, string>,
|
|
736
|
+
world: string,
|
|
737
|
+
depth: number,
|
|
738
|
+
inserted?: InsertedRow[],
|
|
739
|
+
): Promise<void> {
|
|
740
|
+
for (let index = model.chain.length - 1; index >= 0; index--) {
|
|
741
|
+
const link = model.chain[index]
|
|
742
|
+
if (link === undefined || values.has(link.dimension)) continue
|
|
743
|
+
const value = scopeValue(model.name, link.column, link.dimension, world)
|
|
744
|
+
values.set(link.dimension, value)
|
|
745
|
+
const owner = ownerOf(models, link.dimension)
|
|
746
|
+
if (owner === undefined || owner.name === model.name || owner.scope.mode !== 'dimension') continue
|
|
747
|
+
await insert(models, owner.name, placement(owner, values, value), [], depth, inserted)
|
|
748
|
+
inserted?.push({ table: owner.name, match: new Map([[owner.scope.key, value]]) })
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
/**
|
|
753
|
+
* A fresh row of the table `key` references, holding `fixed` (referenced column → value), as stored. A row of a dimension
|
|
754
|
+
* or child table lies in the chain `fixed` holds of it, else in fresh values with containers of its own.
|
|
755
|
+
*/
|
|
756
|
+
async function freshRow(
|
|
757
|
+
models: TableModels,
|
|
758
|
+
key: ForeignKey,
|
|
759
|
+
fixed: ReadonlyMap<string, SampleValue>,
|
|
760
|
+
depth: number,
|
|
761
|
+
inserted?: InsertedRow[],
|
|
762
|
+
): Promise<Readonly<Record<string, unknown>>> {
|
|
763
|
+
const target = modelOf(models, key.table)
|
|
764
|
+
const scope = target?.scope
|
|
765
|
+
if (target === undefined || scope === undefined || (scope.mode !== 'dimension' && scope.mode !== 'child')) {
|
|
766
|
+
const { stored } = await insert(models, key.table, fixed, [], depth, inserted)
|
|
767
|
+
inserted?.push({
|
|
768
|
+
table: key.table,
|
|
769
|
+
match: new Map(key.references.map((name) => [name, keyValue(stored[name], `${key.table}.${name}`)])),
|
|
770
|
+
})
|
|
771
|
+
return stored
|
|
772
|
+
}
|
|
773
|
+
if (fixed.has(scope.key)) {
|
|
774
|
+
throw new SeedLimitError(`the isolation fixture cannot insert a row of ${key.table} whose key the referencing row fixes`)
|
|
775
|
+
}
|
|
776
|
+
const values = new Map<string, string>()
|
|
777
|
+
for (const link of target.chain) {
|
|
778
|
+
const value = fixed.get(link.column)
|
|
779
|
+
if (value !== undefined && value !== null) values.set(link.dimension, String(value))
|
|
780
|
+
}
|
|
781
|
+
await placeContainers(models, target, values, 'referenced', depth, inserted)
|
|
782
|
+
const rowKey = scopeValue(target.name, scope.key, scope.mode === 'dimension' ? scope.dimension : target.name, 'referenced')
|
|
783
|
+
const assigned = placement(target, values, rowKey)
|
|
784
|
+
for (const [name, value] of fixed) {
|
|
785
|
+
if (!assigned.has(name)) assigned.set(name, value)
|
|
786
|
+
}
|
|
787
|
+
const { stored } = await insert(models, target.name, assigned, [], depth, inserted)
|
|
788
|
+
inserted?.push({ table: target.name, match: new Map([[scope.key, rowKey]]) })
|
|
789
|
+
return stored
|
|
561
790
|
}
|
|
562
791
|
|
|
563
792
|
/** A value of `dimension` for the column that carries it: a uuid, or text that names the world it belongs to. */
|
|
@@ -582,11 +811,74 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
582
811
|
}
|
|
583
812
|
|
|
584
813
|
/**
|
|
585
|
-
*
|
|
586
|
-
*
|
|
587
|
-
*
|
|
588
|
-
|
|
589
|
-
|
|
814
|
+
* The ways to fill `column`: a file column a seeded file; a column a CHECK names the `IN` list's first value or `null`,
|
|
815
|
+
* then every value the CHECKs naming it list or compare with, and samples of its type; a text column a marker; any other
|
|
816
|
+
* nullable column `null`; a number a unique index covers its next number in the row's group; else samples of its type.
|
|
817
|
+
*/
|
|
818
|
+
async function columnSlot(
|
|
819
|
+
model: TableModel | undefined,
|
|
820
|
+
table: string,
|
|
821
|
+
column: SeedColumn,
|
|
822
|
+
markers: string[],
|
|
823
|
+
inserted: InsertedRow[] | undefined,
|
|
824
|
+
ungrouped: ReadonlySet<string>,
|
|
825
|
+
): Promise<Slot> {
|
|
826
|
+
const name = column.name
|
|
827
|
+
const single = (value: SampleValue): ReadonlyMap<string, SampleValue> => new Map([[name, value]])
|
|
828
|
+
const sampled = (variant: number): SlotOption => ({ grouped: false, values: async () => single(column.sample(variant)) })
|
|
829
|
+
const samples = Array.from({ length: SAMPLE_VARIANTS }, (_, variant) => sampled(variant))
|
|
830
|
+
const next: SlotOption = { grouped: true, values: async (row) => single(await nextNumberOf(table, column, row, ungrouped)) }
|
|
831
|
+
const kind = model !== undefined && Object.hasOwn(model.files, name) ? model.files[name] : undefined
|
|
832
|
+
if (kind !== undefined) {
|
|
833
|
+
return {
|
|
834
|
+
columns: [name],
|
|
835
|
+
options: [keptOption(async () => single(await seedFile(kind, inserted))), ...(column.nullable ? [valueOption(name, null)] : [])],
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
const named = await checksOn(table, name)
|
|
839
|
+
const isNumbered = await numbered(table, column)
|
|
840
|
+
if (named.length > 0) {
|
|
841
|
+
const checked = await checkedValue(table, column)
|
|
842
|
+
const first = checked === undefined ? (isNumbered ? next : sampled(0)) : valueOption(name, checked)
|
|
843
|
+
const tried: SampleValue[] = column.nullable ? [null] : []
|
|
844
|
+
for (const check of named) {
|
|
845
|
+
for (const literal of [...check.values, ...check.literals]) tried.push(...literalValues(column, literal))
|
|
846
|
+
}
|
|
847
|
+
const listed = [...new Set(tried)].filter((value) => value !== checked).map((value) => valueOption(name, value))
|
|
848
|
+
return { columns: [name], options: [first, ...listed, ...(isNumbered ? [next] : []), ...samples] }
|
|
849
|
+
}
|
|
850
|
+
if (await holdsMarker(model, table, column)) {
|
|
851
|
+
return {
|
|
852
|
+
columns: [name],
|
|
853
|
+
options: [keptOption(async () => {
|
|
854
|
+
const marker = `m${randomHex()}${randomHex()}`
|
|
855
|
+
markers.push(marker)
|
|
856
|
+
return single(marker)
|
|
857
|
+
})],
|
|
858
|
+
}
|
|
859
|
+
}
|
|
860
|
+
if (column.nullable) return { columns: [name], options: [valueOption(name, null)] }
|
|
861
|
+
return { columns: [name], options: isNumbered ? [next] : samples }
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
/** The columns of the constraint a row failed, or `undefined` when the seeding cannot tell (an index on an expression). */
|
|
865
|
+
async function violatedColumns(table: string, violation: Violation): Promise<readonly string[] | undefined> {
|
|
866
|
+
if (violation.columns !== undefined) return violation.columns
|
|
867
|
+
if (violation.kind === 'check') {
|
|
868
|
+
checks ??= backend.checks()
|
|
869
|
+
return (await checks).find((check) => check.table === table && check.name === violation.name)?.columns
|
|
870
|
+
}
|
|
871
|
+
return (await uniqueIndexesOf(table)).find((index) => index.name === violation.name)?.columns
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/**
|
|
875
|
+
* Inserts one row: `assigned` as given, every other column a database default leaves open filled by its slot
|
|
876
|
+
* (`columnSlot`, `referenceSlot`), each slot's first option first. When the database refuses the row for a CHECK or
|
|
877
|
+
* a unique index, the fixture tries the next combination of the options of the slots that constraint names (all of
|
|
878
|
+
* them when it names none it can read), up to `MAX_ROW_ATTEMPTS` rows; the last refusal is the `SeedLimitError`.
|
|
879
|
+
* Answers what the fixture wrote, and the row as stored (its database defaults filled). `inserted` records every row
|
|
880
|
+
* a foreign key or a file column made it insert, not the row itself. A number a unique index covers is numbered within
|
|
881
|
+
* its group without the columns in `ungrouped` (a container the row will not lie in).
|
|
590
882
|
*/
|
|
591
883
|
async function insert(
|
|
592
884
|
models: TableModels,
|
|
@@ -595,39 +887,66 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
595
887
|
markers: string[],
|
|
596
888
|
depth = 0,
|
|
597
889
|
inserted?: InsertedRow[],
|
|
890
|
+
ungrouped: ReadonlySet<string> = new Set(),
|
|
598
891
|
): Promise<{ readonly row: ReadonlyMap<string, SampleValue>; readonly stored: Readonly<Record<string, unknown>> }> {
|
|
599
892
|
const model = modelOf(models, table)
|
|
600
893
|
const columns = columnsOf(table)
|
|
601
|
-
// A column with a database default keeps it unless the fixture assigned it
|
|
894
|
+
// A column with a database default keeps it unless the fixture assigned it or fills a foreign key over it.
|
|
602
895
|
const defaulted = new Set(columns.filter((column) => column.defaulted).map((column) => column.name))
|
|
603
|
-
const
|
|
896
|
+
const slots: Slot[] = []
|
|
897
|
+
const slotted = new Set<string>()
|
|
604
898
|
for (const key of model?.foreignKeys ?? []) {
|
|
605
|
-
const open = key.columns.filter((column) => !assigned.has(column) && !
|
|
606
|
-
|
|
607
|
-
|
|
899
|
+
const open = key.columns.filter((column) => !assigned.has(column) && !slotted.has(column))
|
|
900
|
+
// A key whose columns all have defaults keeps them; one the fixture fills fills its defaulted columns too, which
|
|
901
|
+
// alone may name no row the key's other columns pick.
|
|
902
|
+
if (open.every((column) => defaulted.has(column))) continue
|
|
903
|
+
slots.push(await referenceSlot(models, table, key, open, assigned, depth, inserted))
|
|
904
|
+
for (const name of open) slotted.add(name)
|
|
608
905
|
}
|
|
609
|
-
const row = new Map<string, SampleValue>()
|
|
610
|
-
const open: SeedColumn[] = []
|
|
611
906
|
for (const column of columns) {
|
|
612
|
-
const name = column.name
|
|
613
907
|
// An assigned `null` is the fixture's value too, never a gap to fill.
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
else if (!column.defaulted) open.push(column)
|
|
908
|
+
if (assigned.has(column.name) || column.defaulted || slotted.has(column.name)) continue
|
|
909
|
+
slots.push(await columnSlot(model, table, column, markers, inserted, ungrouped))
|
|
617
910
|
}
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
911
|
+
const order = slotOrder(slots)
|
|
912
|
+
const choice = slots.map(() => 0)
|
|
913
|
+
const involved: number[] = []
|
|
914
|
+
// The refusal of the row the fixture prefers, which the error names once no other row passes.
|
|
915
|
+
let refused: SeedLimitError | undefined
|
|
916
|
+
for (let attempt = 0; attempt < MAX_ROW_ATTEMPTS; attempt++) {
|
|
917
|
+
const row = new Map(assigned)
|
|
918
|
+
let complete = true
|
|
919
|
+
for (const index of order) {
|
|
920
|
+
const slot = slots[index]
|
|
921
|
+
if (slot === undefined) continue
|
|
922
|
+
const picked = await pickOption(slot, choice, index, row)
|
|
923
|
+
if ('error' in picked) {
|
|
924
|
+
// No option of the slot is usable from its current one on: the next combination, or the reason.
|
|
925
|
+
if ((choice[index] ?? 0) === 0 || !involved.includes(index)) throw picked.error
|
|
926
|
+
refused ??= picked.error
|
|
927
|
+
complete = false
|
|
928
|
+
break
|
|
929
|
+
}
|
|
930
|
+
for (const [name, value] of picked.values) row.set(name, value)
|
|
627
931
|
}
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
932
|
+
if (complete) {
|
|
933
|
+
try {
|
|
934
|
+
return { row, stored: await backend.insert(table, row) }
|
|
935
|
+
} catch (error) {
|
|
936
|
+
if (!(error instanceof ConstraintLimitError) || error.violation.kind === 'foreign') throw error
|
|
937
|
+
refused ??= error
|
|
938
|
+
const named = await violatedColumns(table, error.violation)
|
|
939
|
+
const touched = [...slots.keys()].filter((index) => named === undefined || (slots[index]?.columns ?? []).some((name) => named.includes(name)))
|
|
940
|
+
// A constraint over the assigned columns only has nothing to try.
|
|
941
|
+
if (touched.length === 0) throw error
|
|
942
|
+
for (const index of touched) {
|
|
943
|
+
if (!involved.includes(index)) involved.push(index)
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
if (!advanceChoice(slots, choice, involved)) break
|
|
948
|
+
}
|
|
949
|
+
throw refused ?? new SeedLimitError(`the isolation fixture tried ${MAX_ROW_ATTEMPTS} rows of ${table}`)
|
|
631
950
|
}
|
|
632
951
|
|
|
633
952
|
/** The columns a model's row is placed by: its own key when it owns a dimension, and each link of its chain. */
|
|
@@ -770,7 +1089,12 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
770
1089
|
pins: Readonly<Record<string, string>>,
|
|
771
1090
|
scopes: ScopeValues,
|
|
772
1091
|
inserted: InsertedRow[],
|
|
773
|
-
): Promise<{
|
|
1092
|
+
): Promise<{
|
|
1093
|
+
readonly world: Omit<WorldRow, 'updates'>
|
|
1094
|
+
readonly row: ReadonlyMap<string, SampleValue>
|
|
1095
|
+
/** The row as stored, its defaults filled. */
|
|
1096
|
+
readonly holds: Readonly<Record<string, unknown>>
|
|
1097
|
+
}> {
|
|
774
1098
|
const markers: string[] = []
|
|
775
1099
|
const scope = model.scope
|
|
776
1100
|
if (scope.mode !== 'dimension' && scope.mode !== 'child') {
|
|
@@ -786,7 +1110,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
786
1110
|
if (own !== undefined) {
|
|
787
1111
|
values.set(own, key)
|
|
788
1112
|
}
|
|
789
|
-
const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[]) => {
|
|
1113
|
+
const worldRow = (row: ReadonlyMap<string, SampleValue>, stored: readonly string[], holds: Readonly<Record<string, unknown>> = {}) => {
|
|
790
1114
|
const chain = [
|
|
791
1115
|
...(own === undefined ? [] : [{ type: own, value: key }]),
|
|
792
1116
|
...links.flatMap((link) => {
|
|
@@ -802,7 +1126,7 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
802
1126
|
markers,
|
|
803
1127
|
stored,
|
|
804
1128
|
}
|
|
805
|
-
return { world: seeded, row }
|
|
1129
|
+
return { world: seeded, row, holds }
|
|
806
1130
|
}
|
|
807
1131
|
if (own !== undefined && stored.has(own)) {
|
|
808
1132
|
if (Object.keys(seed).length > 0 || Object.keys(pins).length > 0) {
|
|
@@ -851,16 +1175,39 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
851
1175
|
assigned.set(name, pinned)
|
|
852
1176
|
markers.push(pinned)
|
|
853
1177
|
}
|
|
854
|
-
const { row } = await insert(models, model.name, assigned, markers)
|
|
1178
|
+
const { row, stored: holds } = await insert(models, model.name, assigned, markers, 0, inserted)
|
|
855
1179
|
inserted.push({ table: model.name, match: new Map([[scope.key, key]]) })
|
|
856
|
-
return worldRow(row, [])
|
|
1180
|
+
return worldRow(row, [], holds)
|
|
1181
|
+
}
|
|
1182
|
+
|
|
1183
|
+
/** `work`, after which a failure removes the rows it recorded in `inserted` before it rethrows. */
|
|
1184
|
+
async function removedOnFailure<T>(inserted: readonly InsertedRow[], what: string, work: () => Promise<T>): Promise<T> {
|
|
1185
|
+
try {
|
|
1186
|
+
return await work()
|
|
1187
|
+
} catch (error) {
|
|
1188
|
+
try {
|
|
1189
|
+
await backend.remove(inserted)
|
|
1190
|
+
} catch (cleanup) {
|
|
1191
|
+
throw new AggregateError([error, cleanup], `the isolation fixture could not ${what}, nor remove what it had seeded`)
|
|
1192
|
+
}
|
|
1193
|
+
throw error
|
|
1194
|
+
}
|
|
857
1195
|
}
|
|
858
1196
|
|
|
859
|
-
/**
|
|
860
|
-
|
|
1197
|
+
/**
|
|
1198
|
+
* A seeded row's values of the policy's update columns, which its CHECKs accepted: as written, as stored where the
|
|
1199
|
+
* database filled the column (a default), or a sample where the stored value is no plain value.
|
|
1200
|
+
*/
|
|
1201
|
+
async function updatesOf(
|
|
1202
|
+
model: TableModel,
|
|
1203
|
+
row: ReadonlyMap<string, SampleValue>,
|
|
1204
|
+
stored: Readonly<Record<string, unknown>> = {},
|
|
1205
|
+
): Promise<Record<string, SampleValue>> {
|
|
861
1206
|
const updates: Record<string, SampleValue> = {}
|
|
862
1207
|
for (const name of namesOf(model.update)) {
|
|
863
|
-
|
|
1208
|
+
const written = row.get(name)
|
|
1209
|
+
const kept = written === undefined ? plainValue(stored[name]) : written
|
|
1210
|
+
updates[name] = kept === undefined ? await updateSample(model.name, name) : kept
|
|
864
1211
|
}
|
|
865
1212
|
return updates
|
|
866
1213
|
}
|
|
@@ -890,8 +1237,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
890
1237
|
// Sampled once both rows are written: a number a unique index covers is the next above what the table holds.
|
|
891
1238
|
return {
|
|
892
1239
|
dimension,
|
|
893
|
-
own: { ...own.world, updates: await updatesOf(model, own.row) },
|
|
894
|
-
other: { ...other.world, updates: await updatesOf(model, other.row) },
|
|
1240
|
+
own: { ...own.world, updates: await updatesOf(model, own.row, own.holds) },
|
|
1241
|
+
other: { ...other.world, updates: await updatesOf(model, other.row, other.holds) },
|
|
895
1242
|
remove: () => backend.remove(inserted),
|
|
896
1243
|
}
|
|
897
1244
|
},
|
|
@@ -899,8 +1246,8 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
899
1246
|
const { models, model } = scopedModel(tables, table)
|
|
900
1247
|
checkApplicationValues(models, { [table]: values })
|
|
901
1248
|
const markers: string[] = []
|
|
902
|
-
const { key, row } = await seedApplicationRow(models, model, values, new Map(), markers)
|
|
903
|
-
return { key, updates: await updatesOf(model, row), markers }
|
|
1249
|
+
const { key, row, stored } = await seedApplicationRow(models, model, values, new Map(), markers)
|
|
1250
|
+
return { key, updates: await updatesOf(model, row, stored), markers }
|
|
904
1251
|
},
|
|
905
1252
|
async seedApplicationRows(tables, rows) {
|
|
906
1253
|
const models = tableModels(tables)
|
|
@@ -953,35 +1300,34 @@ export function testSeeding(backend: SeedingBackend): TestSeeding {
|
|
|
953
1300
|
const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'under')
|
|
954
1301
|
const markers: string[] = []
|
|
955
1302
|
const inserted: InsertedRow[] = []
|
|
956
|
-
await insert(models, table, placement(model, values, key), markers, 0, inserted)
|
|
1303
|
+
await removedOnFailure(inserted, 'seed the row', () => insert(models, table, placement(model, values, key), markers, 0, inserted))
|
|
957
1304
|
inserted.push({ table, match: new Map([[scope.key, key]]) })
|
|
958
1305
|
return { key, markers, remove: () => backend.remove(inserted) }
|
|
959
1306
|
},
|
|
960
1307
|
async sampleInsert(tables, table, beside) {
|
|
961
1308
|
const { models, model } = scopedModel(tables, table)
|
|
962
|
-
const
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
for (const key of model.foreignKeys) {
|
|
966
|
-
const open = key.columns.filter((name) => required.some((column) => column.name === name))
|
|
967
|
-
if (open.length === 0) continue
|
|
968
|
-
for (const [name, value] of await referencedKey(models, table, key, open, 0)) values[name] = value
|
|
969
|
-
}
|
|
970
|
-
// The row as the insert will write it: in `beside`'s containers, which the handler places it in.
|
|
971
|
-
const containers = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
|
|
972
|
-
const row = new Map<string, SampleValue>()
|
|
973
|
-
for (const link of model.chain) {
|
|
974
|
-
const value = containers.get(link.dimension)
|
|
975
|
-
if (value !== undefined) row.set(link.column, value)
|
|
1309
|
+
const scope = model.scope
|
|
1310
|
+
if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
|
|
1311
|
+
throw new Error(`${table} is a ${scope.mode} table; no store inserts into it`)
|
|
976
1312
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1313
|
+
// A probe row the database judges, placed as the insert will place it (in `beside`'s containers, else in fresh
|
|
1314
|
+
// ones it removes with the probe), numbered within the containers known; its values are the sample.
|
|
1315
|
+
const values = new Map((beside?.chain ?? []).map((link) => [link.type, link.value]))
|
|
1316
|
+
const ungrouped = new Set(model.chain.filter((link) => !values.has(link.dimension)).map((link) => link.column))
|
|
1317
|
+
const placed: InsertedRow[] = []
|
|
1318
|
+
const key = scopeValue(table, scope.key, scope.mode === 'dimension' ? scope.dimension : table, 'probe')
|
|
1319
|
+
const { row } = await removedOnFailure(placed, 'insert a probe row', async () => {
|
|
1320
|
+
await placeContainers(models, model, values, 'probe', 0, placed)
|
|
1321
|
+
return insert(models, table, placement(model, values, key), [], 0, undefined, ungrouped)
|
|
982
1322
|
})
|
|
983
|
-
|
|
984
|
-
|
|
1323
|
+
await backend.remove([{ table, match: new Map([[scope.key, key]]) }, ...placed])
|
|
1324
|
+
const sample: Record<string, SampleValue> = {}
|
|
1325
|
+
for (const column of columnsOf(table)) {
|
|
1326
|
+
if (!inSet(model.insert, column.name) || !row.has(column.name)) continue
|
|
1327
|
+
// A nullable column a CHECK ties to another is written as the probe held it; any other is left to the insert.
|
|
1328
|
+
if (isRequired(column) || (await checksOn(table, column.name)).length > 0) sample[column.name] = row.get(column.name) ?? null
|
|
1329
|
+
}
|
|
1330
|
+
return sample
|
|
985
1331
|
},
|
|
986
1332
|
seededObjects: () => [...seededObjects],
|
|
987
1333
|
}
|
package/src/testing-sqlite.ts
CHANGED
|
@@ -21,6 +21,7 @@ import type { TableProbe } from './store'
|
|
|
21
21
|
import {
|
|
22
22
|
type CheckConstraint,
|
|
23
23
|
checkLimit,
|
|
24
|
+
type CheckLiteral,
|
|
24
25
|
foreignKeyLimit,
|
|
25
26
|
groupsWhere,
|
|
26
27
|
type InsertedRow,
|
|
@@ -79,21 +80,26 @@ function baseType(declared: string): string {
|
|
|
79
80
|
return declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
|
|
80
81
|
}
|
|
81
82
|
|
|
82
|
-
/**
|
|
83
|
-
|
|
83
|
+
/**
|
|
84
|
+
* A sample for a required column the test does not care about, by the declared types `@fabrika/db/codegen-sqlite`
|
|
85
|
+
* accepts; `variant` above 0 is another value of the type (`SeedColumn.sample`).
|
|
86
|
+
*/
|
|
87
|
+
function sampleOf(table: string, column: string, declared: string, variant: number): Primitive {
|
|
84
88
|
const type = baseType(declared)
|
|
85
89
|
if (type === 'UUID') return crypto.randomUUID()
|
|
86
90
|
if (TEXT_TYPES.has(type)) return `s${randomHex()}`
|
|
87
|
-
if (NUMBER_TYPES.has(type)) return 1
|
|
88
|
-
if (type === 'BOOLEAN') return
|
|
91
|
+
if (NUMBER_TYPES.has(type)) return 1 + variant
|
|
92
|
+
if (type === 'BOOLEAN') return variant % 2 === 1
|
|
89
93
|
// A day is `YYYY-MM-DD` and a timestamp ISO text in UTC: the forms the layer writes and reads on SQLite.
|
|
90
|
-
if (type === 'DATE') return new Date().toISOString().slice(0, 10)
|
|
91
|
-
if (TIMESTAMP_TYPES.has(type)) return new Date().toISOString()
|
|
94
|
+
if (type === 'DATE') return new Date(Date.now() + variant * DAY_MS).toISOString().slice(0, 10)
|
|
95
|
+
if (TIMESTAMP_TYPES.has(type)) return new Date(Date.now() + variant * 1000).toISOString()
|
|
92
96
|
// A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
|
|
93
|
-
if (type === 'JSONB') return 'sample'
|
|
97
|
+
if (type === 'JSONB') return variant === 0 ? 'sample' : `sample-${variant}`
|
|
94
98
|
throw typeLimit(table, column, declared)
|
|
95
99
|
}
|
|
96
100
|
|
|
101
|
+
const DAY_MS = 86_400_000
|
|
102
|
+
|
|
97
103
|
const tableRows = z.array(z.object({ name: z.string(), wr: z.number() }))
|
|
98
104
|
const columnRows = z.array(
|
|
99
105
|
z.object({ name: z.string(), type: z.string(), notnull: z.number(), dflt_value: z.string().nullable(), pk: z.number(), hidden: z.number() }),
|
|
@@ -123,7 +129,7 @@ function readColumns(exec: Exec): SeedColumn[] {
|
|
|
123
129
|
uuid: type === 'UUID',
|
|
124
130
|
number: NUMBER_TYPES.has(type),
|
|
125
131
|
json: type === 'JSONB',
|
|
126
|
-
sample: () => sampleOf(table.name, column.name, column.type),
|
|
132
|
+
sample: (variant) => sampleOf(table.name, column.name, column.type, variant),
|
|
127
133
|
})
|
|
128
134
|
}
|
|
129
135
|
}
|
|
@@ -234,8 +240,43 @@ function definitions(tokens: readonly Token[]): Token[][] {
|
|
|
234
240
|
|
|
235
241
|
const TABLE_CONSTRAINTS: ReadonlySet<string> = new Set(['CONSTRAINT', 'CHECK', 'PRIMARY', 'UNIQUE', 'FOREIGN'])
|
|
236
242
|
|
|
237
|
-
/** The
|
|
238
|
-
|
|
243
|
+
/** The value of a text or number literal token, a number possibly after a minus sign; `undefined` for any other token. */
|
|
244
|
+
/** The words before which a `-` is a sign, not a subtraction: the operators that take an operand after them. */
|
|
245
|
+
const OPERAND_FOLLOWS = new Set(['AND', 'OR', 'NOT', 'BETWEEN', 'IN', 'IS', 'LIKE', 'GLOB', 'CASE', 'WHEN', 'THEN', 'ELSE', 'CHECK'])
|
|
246
|
+
|
|
247
|
+
/** Whether `token` ends an operand, so a `-` after it subtracts (`a-1`) rather than signs a number (`> -1`). */
|
|
248
|
+
function endsOperand(token: Token | undefined): boolean {
|
|
249
|
+
if (token === undefined) return false
|
|
250
|
+
if (token.kind === 'name' || token.kind === 'string') return true
|
|
251
|
+
if (token.kind === 'word') return !OPERAND_FOLLOWS.has(token.text.toUpperCase())
|
|
252
|
+
return token.text === ')' || /^(?:[0-9]|\.[0-9])/.test(token.text)
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function literalOf(tokens: readonly Token[], index: number): { readonly value: CheckLiteral; readonly width: number } | undefined {
|
|
256
|
+
const token = tokens[index]
|
|
257
|
+
if (token?.kind === 'string') return { value: token.text, width: 1 }
|
|
258
|
+
const negative = isPunctuation(token, '-') && !endsOperand(tokens[index - 1])
|
|
259
|
+
const number = negative ? tokens[index + 1] : token
|
|
260
|
+
if (number?.kind !== 'other' || !/^(?:[0-9]|\.[0-9])/.test(number.text)) return undefined
|
|
261
|
+
const value = Number(number.text)
|
|
262
|
+
if (!Number.isFinite(value)) return undefined
|
|
263
|
+
return { value: negative ? -value : value, width: negative ? 2 : 1 }
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
/** Every text and number literal of a CHECK expression. */
|
|
267
|
+
function expressionLiterals(expression: readonly Token[]): CheckLiteral[] {
|
|
268
|
+
const literals: CheckLiteral[] = []
|
|
269
|
+
for (let index = 0; index < expression.length; index++) {
|
|
270
|
+
const literal = literalOf(expression, index)
|
|
271
|
+
if (literal === undefined) continue
|
|
272
|
+
literals.push(literal.value)
|
|
273
|
+
index += literal.width - 1
|
|
274
|
+
}
|
|
275
|
+
return literals
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** The values of `<column> IN ('a', 'b', …)` or `IN (1, 2, …)`, parenthesized or not, or none for any other expression. */
|
|
279
|
+
function listedValues(expression: readonly Token[], column: string): CheckLiteral[] {
|
|
239
280
|
let tokens = expression
|
|
240
281
|
while (isPunctuation(tokens[0], '(') && closing(tokens, 0) === tokens.length - 1) {
|
|
241
282
|
tokens = tokens.slice(1, -1)
|
|
@@ -252,18 +293,18 @@ function listedValues(expression: readonly Token[], column: string): string[] {
|
|
|
252
293
|
if (!named || subject.text.toLowerCase() !== column.toLowerCase() || !isWord(tokens[list], 'IN') || !isPunctuation(tokens[list + 1], '(')) return []
|
|
253
294
|
if (!isPunctuation(tokens.at(-1), ')') || closing(tokens, list + 1) !== tokens.length - 1) return []
|
|
254
295
|
const items = tokens.slice(list + 2, -1)
|
|
255
|
-
const values:
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
296
|
+
const values: CheckLiteral[] = []
|
|
297
|
+
let index = 0
|
|
298
|
+
while (index < items.length) {
|
|
299
|
+
const literal = literalOf(items, index)
|
|
300
|
+
if (literal === undefined) return []
|
|
301
|
+
values.push(literal.value)
|
|
302
|
+
index += literal.width
|
|
303
|
+
if (index === items.length) return values
|
|
304
|
+
if (!isPunctuation(items[index], ',')) return []
|
|
305
|
+
index += 1
|
|
265
306
|
}
|
|
266
|
-
return
|
|
307
|
+
return []
|
|
267
308
|
}
|
|
268
309
|
|
|
269
310
|
/** Every CHECK of a table as `sqlite_schema` stores its `CREATE TABLE`: a column's and the table's, by the columns it names. */
|
|
@@ -300,6 +341,7 @@ function tableChecks(table: string, sql: string, columns: readonly string[]): Ch
|
|
|
300
341
|
table,
|
|
301
342
|
columns: [...named],
|
|
302
343
|
values: named.size === 1 && only !== undefined ? listedValues(expression, only) : [],
|
|
344
|
+
literals: expressionLiterals(expression),
|
|
303
345
|
})
|
|
304
346
|
index = close
|
|
305
347
|
}
|
|
@@ -416,9 +458,14 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
|
|
|
416
458
|
if (check !== null) return checkLimit(check[1] ?? 'unnamed', table)
|
|
417
459
|
// SQLite names no foreign key in its error.
|
|
418
460
|
if (message.startsWith('FOREIGN KEY constraint failed')) return foreignKeyLimit('unnamed', table)
|
|
419
|
-
// SQLite names a unique index by its columns in its error
|
|
461
|
+
// SQLite names a unique index by its columns in its error, `UNIQUE constraint failed: t.a, t.b`, or one on an
|
|
462
|
+
// expression by its name, `UNIQUE constraint failed: index 'i'`.
|
|
420
463
|
const unique = /^UNIQUE constraint failed: (.*)$/s.exec(message)
|
|
421
|
-
if (unique !== null)
|
|
464
|
+
if (unique !== null) {
|
|
465
|
+
const named = unique[1] ?? 'unnamed'
|
|
466
|
+
const columns = named.startsWith('index ') ? undefined : named.split(', ').map((column) => column.slice(column.indexOf('.') + 1))
|
|
467
|
+
return uniqueValueLimit(`(${named})`, table, columns)
|
|
468
|
+
}
|
|
422
469
|
return undefined
|
|
423
470
|
}
|
|
424
471
|
|
package/src/testing.ts
CHANGED
|
@@ -26,6 +26,7 @@ import type { TableProbe } from './store'
|
|
|
26
26
|
import {
|
|
27
27
|
type CheckConstraint,
|
|
28
28
|
checkLimit,
|
|
29
|
+
type CheckLiteral,
|
|
29
30
|
foreignKeyLimit,
|
|
30
31
|
groupsWhere,
|
|
31
32
|
type InsertedRow,
|
|
@@ -90,28 +91,33 @@ function quoted(identifier: string): string {
|
|
|
90
91
|
return `"${identifier}"`
|
|
91
92
|
}
|
|
92
93
|
|
|
93
|
-
|
|
94
|
-
|
|
94
|
+
const DAY_MS = 86_400_000
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* A sample for a required column the test does not care about, by the types `@fabrika/db/codegen` accepts; `variant`
|
|
98
|
+
* above 0 is another value of the type (`SeedColumn.sample`).
|
|
99
|
+
*/
|
|
100
|
+
function sampleOf(table: string, column: CatalogColumn, variant: number): Primitive {
|
|
95
101
|
if (column.type_type === 'e') {
|
|
96
|
-
const
|
|
97
|
-
if (
|
|
98
|
-
return
|
|
102
|
+
const label = column.enum_labels[variant % Math.max(column.enum_labels.length, 1)]
|
|
103
|
+
if (label !== undefined) {
|
|
104
|
+
return label
|
|
99
105
|
}
|
|
100
106
|
}
|
|
101
107
|
const type = column.type_name
|
|
102
108
|
if (type === 'uuid') return crypto.randomUUID()
|
|
103
109
|
if (TEXT_TYPES.has(type)) return `s${randomHex()}`
|
|
104
110
|
// Bun.SQL reads an int8 and a numeric as text.
|
|
105
|
-
if (NUMBER_TYPES.has(type)) return type === 'int8' || type === 'numeric' ?
|
|
106
|
-
if (type === 'bool') return
|
|
111
|
+
if (NUMBER_TYPES.has(type)) return type === 'int8' || type === 'numeric' ? String(1 + variant) : 1 + variant
|
|
112
|
+
if (type === 'bool') return variant % 2 === 1
|
|
107
113
|
// ISO text, not a Date: the seed binds past the layer's compiler, where Bun.SQL would send Date#toString(). A day is
|
|
108
114
|
// `YYYY-MM-DD`, since the probe's insert sends it through the layer, which takes a `date` only so.
|
|
109
|
-
if (type === 'date') return new Date().toISOString().slice(0, 10)
|
|
110
|
-
if (type === 'timestamp' || type === 'timestamptz') return new Date().toISOString()
|
|
111
|
-
if (type === 'time' || type === 'timetz') return
|
|
112
|
-
if (type === 'interval') return
|
|
115
|
+
if (type === 'date') return new Date(Date.now() + variant * DAY_MS).toISOString().slice(0, 10)
|
|
116
|
+
if (type === 'timestamp' || type === 'timestamptz') return new Date(Date.now() + variant * 1000).toISOString()
|
|
117
|
+
if (type === 'time' || type === 'timetz') return `12:00:${String(variant % 60).padStart(2, '0')}`
|
|
118
|
+
if (type === 'interval') return `${1 + variant} hour`
|
|
113
119
|
// A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
|
|
114
|
-
if (type === 'jsonb') return 'sample'
|
|
120
|
+
if (type === 'jsonb') return variant === 0 ? 'sample' : `sample-${variant}`
|
|
115
121
|
throw typeLimit(table, column.column_name, type)
|
|
116
122
|
}
|
|
117
123
|
|
|
@@ -127,7 +133,7 @@ function seedColumn(column: CatalogColumn): SeedColumn {
|
|
|
127
133
|
uuid: column.type_name === 'uuid',
|
|
128
134
|
number: column.type_type !== 'e' && NUMBER_TYPES.has(column.type_name),
|
|
129
135
|
json: column.type_type === 'b' && column.type_category !== 'A' && column.type_name === 'jsonb',
|
|
130
|
-
sample: () => sampleOf(column.table_name, column),
|
|
136
|
+
sample: (variant) => sampleOf(column.table_name, column, variant),
|
|
131
137
|
}
|
|
132
138
|
}
|
|
133
139
|
|
|
@@ -203,15 +209,46 @@ const ctidRows = z.array(z.object({ ctid: z.string() }))
|
|
|
203
209
|
/** Ctids as one array literal parameter, `{"(0,1)","(0,2)"}`: the driver mis-binds a JS array. */
|
|
204
210
|
const tidArray = (ctids: Iterable<string>): string => `{${[...ctids].map((ctid) => `"${ctid}"`).join(',')}}`
|
|
205
211
|
|
|
206
|
-
/**
|
|
212
|
+
/**
|
|
213
|
+
* `CHECK ((status = ANY (ARRAY['open'::text, 'done'::text])))` or `CHECK ((rate = ANY (ARRAY[0, 12])))`, a one-column
|
|
214
|
+
* `IN` list as Postgres prints it.
|
|
215
|
+
*/
|
|
207
216
|
const IN_LIST = /^CHECK \(\(\(?"?([^"()\s]+)"?\)?(?:::[a-z ]+)? = ANY \(\(?ARRAY\[(.+)\]\)?(?:::[a-z ]+\[\])?\)\)\)$/
|
|
208
|
-
const LITERAL = /'((?:[^']|'')*)'
|
|
217
|
+
const LITERAL = /'((?:[^']|'')*)'::([a-z ]+)/g
|
|
218
|
+
const QUOTED_ITEM = /^\(?'((?:[^']|'')*)'::([a-z ]+)\)?$/
|
|
219
|
+
const LIST_NUMBER = /^\(?(-?[0-9]+(?:\.[0-9]+)?)\)?(?:::[a-z ]+)?$/
|
|
220
|
+
/** A string literal of a printed definition, or a number outside one that no name or other number touches. */
|
|
221
|
+
const DEFINITION_LITERAL = /'((?:[^']|'')*)'(?:::([a-z ]+))?|(?<![\w$."])(-?[0-9]+(?:\.[0-9]+)?)(?![\w$.])/g
|
|
222
|
+
/** Postgres prints a negative number constant quoted and cast, `'-5'::integer`. */
|
|
223
|
+
const NUMBER_CAST = /^(?:smallint|integer|bigint|numeric|real|double precision)$/
|
|
224
|
+
const NUMBER_TEXT = /^-?[0-9]+(?:\.[0-9]+)?$/
|
|
225
|
+
|
|
226
|
+
/** A quoted constant of a printed definition: a number where it is cast to a number type, else its text. */
|
|
227
|
+
function quotedValue(quoted: string, cast: string | undefined): CheckLiteral {
|
|
228
|
+
const text = quoted.replaceAll("''", "'")
|
|
229
|
+
return cast !== undefined && NUMBER_CAST.test(cast.trim()) && NUMBER_TEXT.test(text) ? Number(text) : text
|
|
230
|
+
}
|
|
209
231
|
|
|
210
232
|
/** The values of a one-column `IN` list, or none for any other CHECK. */
|
|
211
|
-
function listedValues(definition: string, columns: readonly string[]):
|
|
233
|
+
function listedValues(definition: string, columns: readonly string[]): CheckLiteral[] {
|
|
212
234
|
const listed = IN_LIST.exec(definition)
|
|
213
235
|
if (listed === null || columns.length !== 1 || listed[1] !== columns[0]) return []
|
|
214
|
-
|
|
236
|
+
const items = listed[2] ?? ''
|
|
237
|
+
const quoted = [...items.matchAll(LITERAL)]
|
|
238
|
+
// A text list is read by its literals, which may hold the separator; a number list item by item.
|
|
239
|
+
if (quoted.some((match) => !NUMBER_CAST.test((match[2] ?? '').trim()))) return quoted.map((match) => quotedValue(match[1] ?? '', match[2]))
|
|
240
|
+
const numbers = items.split(', ').map((item) => {
|
|
241
|
+
const constant = QUOTED_ITEM.exec(item)
|
|
242
|
+
if (constant !== null) return quotedValue(constant[1] ?? '', constant[2])
|
|
243
|
+
const number = LIST_NUMBER.exec(item)?.[1]
|
|
244
|
+
return number === undefined ? undefined : Number(number)
|
|
245
|
+
})
|
|
246
|
+
return numbers.every((number) => typeof number === 'number') ? numbers.filter((number) => typeof number === 'number') : []
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Every text and number literal of a CHECK as Postgres prints it. */
|
|
250
|
+
function definitionLiterals(definition: string): CheckLiteral[] {
|
|
251
|
+
return [...definition.matchAll(DEFINITION_LITERAL)].map((match) => match[1] === undefined ? Number(match[3]) : quotedValue(match[1], match[2]))
|
|
215
252
|
}
|
|
216
253
|
|
|
217
254
|
/** A CHECK or foreign key violation of a seeded row, as the generator limit it is; `undefined` for any other failure. */
|
|
@@ -396,6 +433,7 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
|
|
|
396
433
|
table: row.table_name,
|
|
397
434
|
columns: row.columns,
|
|
398
435
|
values: listedValues(row.definition, row.columns),
|
|
436
|
+
literals: definitionLiterals(row.definition),
|
|
399
437
|
})),
|
|
400
438
|
uniqueIndexes: async () =>
|
|
401
439
|
uniqueRows.parse(await lock.unsafe(UNIQUE_QUERY, [schema])).map((row) => ({
|
|
@@ -25,7 +25,7 @@ export interface WorldRow {
|
|
|
25
25
|
readonly type: string;
|
|
26
26
|
readonly value: string;
|
|
27
27
|
}[];
|
|
28
|
-
/** The row's values of the policy's update columns, as
|
|
28
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
29
29
|
readonly updates: Readonly<Record<string, SampleValue>>;
|
|
30
30
|
/**
|
|
31
31
|
* The distinct value written into every text column the fixture filled itself, in this row and in its containers.
|
|
@@ -41,7 +41,7 @@ export interface WorldRow {
|
|
|
41
41
|
/** One seeded row of an application table, which lies in no dimension. */
|
|
42
42
|
export interface ApplicationRow {
|
|
43
43
|
readonly key: string;
|
|
44
|
-
/** The row's values of the policy's update columns, as
|
|
44
|
+
/** The row's values of the policy's update columns: as seeded, or as stored where the database filled them. */
|
|
45
45
|
readonly updates: Readonly<Record<string, SampleValue>>;
|
|
46
46
|
/** The distinct value written into every text column the fixture filled itself. */
|
|
47
47
|
readonly markers: readonly string[];
|
|
@@ -65,13 +65,26 @@ export interface SeededRow {
|
|
|
65
65
|
readonly remove: () => Promise<void>;
|
|
66
66
|
}
|
|
67
67
|
/**
|
|
68
|
-
* What the isolation fixture cannot seed for a schema: a CHECK
|
|
69
|
-
*
|
|
70
|
-
* failure of the handler or the policy a case is about.
|
|
68
|
+
* What the isolation fixture cannot seed for a schema: a CHECK or a unique index no row it tries passes, a required
|
|
69
|
+
* foreign key whose referenced row it cannot seed. It is a limit of the generator, named with the constraint or the
|
|
70
|
+
* column, never a failure of the handler or the policy a case is about.
|
|
71
71
|
*/
|
|
72
72
|
export declare class SeedLimitError extends Error {
|
|
73
73
|
readonly name = "SeedLimitError";
|
|
74
74
|
}
|
|
75
|
+
/** The constraint a seeded row failed, as a backend reads it off the database's error. */
|
|
76
|
+
export interface Violation {
|
|
77
|
+
readonly kind: 'check' | 'unique' | 'foreign';
|
|
78
|
+
/** The constraint's name, or for an unnamed CHECK on SQLite its expression, as the database reports it. */
|
|
79
|
+
readonly name: string;
|
|
80
|
+
/** The columns the database names (SQLite's unique error); `undefined` where the seeding looks them up by `name`. */
|
|
81
|
+
readonly columns?: readonly string[];
|
|
82
|
+
}
|
|
83
|
+
/** A seed limit of a row the database refused, with the constraint it failed: the seeding tries another row. */
|
|
84
|
+
export declare class ConstraintLimitError extends SeedLimitError {
|
|
85
|
+
readonly violation: Violation;
|
|
86
|
+
constructor(message: string, violation: Violation);
|
|
87
|
+
}
|
|
75
88
|
/** One row of a table in each of two containment chains that share no value. */
|
|
76
89
|
export interface IsolationWorlds {
|
|
77
90
|
/**
|
|
@@ -168,8 +181,12 @@ export interface SeedColumn {
|
|
|
168
181
|
readonly number: boolean;
|
|
169
182
|
/** A JSON column (`jsonb`, `JSONB`): its value is a JSON value, bound as the layer binds it (`seedBinding`). */
|
|
170
183
|
readonly json: boolean;
|
|
171
|
-
/**
|
|
172
|
-
|
|
184
|
+
/**
|
|
185
|
+
* A sample of the column's type for a required column the test does not care about; a `SeedLimitError` for a type it
|
|
186
|
+
* cannot fill. `variant` 0 is the plain sample; a higher one differs from the lower ones where the type allows (another
|
|
187
|
+
* day, the other boolean, a larger number), for a unique index whose other columns the row cannot vary.
|
|
188
|
+
*/
|
|
189
|
+
readonly sample: (variant: number) => Primitive;
|
|
173
190
|
}
|
|
174
191
|
/** A CHECK constraint of the schema, by the columns it names. */
|
|
175
192
|
export interface CheckConstraint {
|
|
@@ -177,8 +194,12 @@ export interface CheckConstraint {
|
|
|
177
194
|
readonly table: string;
|
|
178
195
|
readonly columns: readonly string[];
|
|
179
196
|
/** The values of a one-column `IN (…)` list the fixture writes in its place, first one first; empty for any other CHECK. */
|
|
180
|
-
readonly values: readonly
|
|
197
|
+
readonly values: readonly CheckLiteral[];
|
|
198
|
+
/** Every text and number literal of the expression: what the fixture tries in the columns it names when a row fails it. */
|
|
199
|
+
readonly literals: readonly CheckLiteral[];
|
|
181
200
|
}
|
|
201
|
+
/** A literal of a CHECK expression. */
|
|
202
|
+
export type CheckLiteral = string | number;
|
|
182
203
|
/**
|
|
183
204
|
* A unique index of the schema (a primary key's or a UNIQUE constraint's included), by its key columns. Only an index of
|
|
184
205
|
* plain columns with no predicate is one: the fixture cannot tell a partial index's rows or an expression's values.
|
|
@@ -236,13 +257,13 @@ export interface SeedingBackend {
|
|
|
236
257
|
remove(rows: readonly InsertedRow[]): Promise<void>;
|
|
237
258
|
}
|
|
238
259
|
/** The seed limit of a CHECK a seeded row fails. */
|
|
239
|
-
export declare function checkLimit(constraint: string, table: string):
|
|
260
|
+
export declare function checkLimit(constraint: string, table: string): ConstraintLimitError;
|
|
240
261
|
/** The seed limit of a foreign key a seeded row breaks. */
|
|
241
|
-
export declare function foreignKeyLimit(constraint: string, table: string):
|
|
262
|
+
export declare function foreignKeyLimit(constraint: string, table: string): ConstraintLimitError;
|
|
242
263
|
/** The seed limit of a number column a unique index covers whose type holds no number above the largest of the row's group. */
|
|
243
264
|
export declare function uniqueLimit(index: string, table: string, column: string): SeedLimitError;
|
|
244
265
|
/** The seed limit of a row whose values another row of the table already holds under a unique index. */
|
|
245
|
-
export declare function uniqueValueLimit(index: string, table: string):
|
|
266
|
+
export declare function uniqueValueLimit(index: string, table: string, columns?: readonly string[]): ConstraintLimitError;
|
|
246
267
|
/** The seed limit of a required column whose type the fixture has no sample of. */
|
|
247
268
|
export declare function typeLimit(table: string, column: string, type: string): SeedLimitError;
|
|
248
269
|
/**
|