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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,
@@ -66,6 +67,59 @@ export interface TestDatabaseOptions {
66
67
  readonly migrations: string | URL
67
68
  /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
68
69
  readonly label: string
70
+ /** A database migrated and seeded once (`testDatabaseTemplate`), which this one starts as a copy of. */
71
+ readonly template?: TestDatabaseTemplate
72
+ }
73
+
74
+ /** A migrated database with its base seed, as an image every `testDatabase({ template })` copies. */
75
+ export interface TestDatabaseTemplate {
76
+ /** The migrations it was migrated with: a database of other migrations does not start from it. */
77
+ readonly migrations: string
78
+ readonly image: Uint8Array
79
+ }
80
+
81
+ /** Each migrations' image this process migrated, by the migrations: a test file copies it instead of migrating again. */
82
+ const migratedImages = new Map<string, Uint8Array>()
83
+
84
+ /** The identity of a set of migrations: every file's name and text. */
85
+ function migrationsKey(migrations: SqliteMigrationBundle['migrations']): string {
86
+ return JSON.stringify(migrations.map((migration) => [migration.name, migration.sql]))
87
+ }
88
+
89
+ /** A fresh in-memory database with the framework's and the application's migrations applied, or a copy of `image`. */
90
+ async function migratedDatabase(migrations: SqliteMigrationBundle['migrations'], image: Uint8Array | undefined): Promise<BunDatabase> {
91
+ if (image !== undefined) {
92
+ return BunDatabase.deserialize(image)
93
+ }
94
+ const sqlite = new BunDatabase(':memory:')
95
+ const storage = bunSqliteStorage(sqlite)
96
+ try {
97
+ await migrateSqlite({ exec: storage.sql.exec, transactionSync: (fn) => storage.transactionSync(fn) }, [
98
+ { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
99
+ { bundle: APPLICATION_MIGRATION_BUNDLE, migrations },
100
+ ])
101
+ } catch (error) {
102
+ sqlite.close()
103
+ throw error
104
+ }
105
+ return sqlite
106
+ }
107
+
108
+ /**
109
+ * Migrates a database once, runs `seed` in it, and keeps it as the image each `testDatabase({ template })` starts as a
110
+ * copy of: in milliseconds, without migrating or seeding again.
111
+ */
112
+ export async function testDatabaseTemplate(
113
+ options: Omit<TestDatabaseOptions, 'template'> & { readonly seed?: (database: TestDatabase) => Promise<void> },
114
+ ): Promise<TestDatabaseTemplate> {
115
+ refuseInProduction(MODULE)
116
+ const { database, sqlite, migrations } = await openTestDatabase({ migrations: options.migrations, label: options.label })
117
+ try {
118
+ await options.seed?.(database)
119
+ return Object.freeze({ migrations, image: sqlite.serialize() })
120
+ } finally {
121
+ await database.close()
122
+ }
69
123
  }
70
124
 
71
125
  type Exec = (query: string, ...bindings: SqliteValue[]) => Record<string, SqliteValue>[]
@@ -79,21 +133,26 @@ function baseType(declared: string): string {
79
133
  return declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
80
134
  }
81
135
 
82
- /** A sample for a required column the test does not care about, by the declared types `@fabrika/db/codegen-sqlite` accepts. */
83
- function sampleOf(table: string, column: string, declared: string): Primitive {
136
+ /**
137
+ * A sample for a required column the test does not care about, by the declared types `@fabrika/db/codegen-sqlite`
138
+ * accepts; `variant` above 0 is another value of the type (`SeedColumn.sample`).
139
+ */
140
+ function sampleOf(table: string, column: string, declared: string, variant: number): Primitive {
84
141
  const type = baseType(declared)
85
142
  if (type === 'UUID') return crypto.randomUUID()
86
143
  if (TEXT_TYPES.has(type)) return `s${randomHex()}`
87
- if (NUMBER_TYPES.has(type)) return 1
88
- if (type === 'BOOLEAN') return false
144
+ if (NUMBER_TYPES.has(type)) return 1 + variant
145
+ if (type === 'BOOLEAN') return variant % 2 === 1
89
146
  // 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()
147
+ if (type === 'DATE') return new Date(Date.now() + variant * DAY_MS).toISOString().slice(0, 10)
148
+ if (TIMESTAMP_TYPES.has(type)) return new Date(Date.now() + variant * 1000).toISOString()
92
149
  // A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
93
- if (type === 'JSONB') return 'sample'
150
+ if (type === 'JSONB') return variant === 0 ? 'sample' : `sample-${variant}`
94
151
  throw typeLimit(table, column, declared)
95
152
  }
96
153
 
154
+ const DAY_MS = 86_400_000
155
+
97
156
  const tableRows = z.array(z.object({ name: z.string(), wr: z.number() }))
98
157
  const columnRows = z.array(
99
158
  z.object({ name: z.string(), type: z.string(), notnull: z.number(), dflt_value: z.string().nullable(), pk: z.number(), hidden: z.number() }),
@@ -123,7 +182,7 @@ function readColumns(exec: Exec): SeedColumn[] {
123
182
  uuid: type === 'UUID',
124
183
  number: NUMBER_TYPES.has(type),
125
184
  json: type === 'JSONB',
126
- sample: () => sampleOf(table.name, column.name, column.type),
185
+ sample: (variant) => sampleOf(table.name, column.name, column.type, variant),
127
186
  })
128
187
  }
129
188
  }
@@ -234,8 +293,43 @@ function definitions(tokens: readonly Token[]): Token[][] {
234
293
 
235
294
  const TABLE_CONSTRAINTS: ReadonlySet<string> = new Set(['CONSTRAINT', 'CHECK', 'PRIMARY', 'UNIQUE', 'FOREIGN'])
236
295
 
237
- /** The values of `<column> IN ('a', 'b', …)`, parenthesized or not, or none for any other expression. */
238
- function listedValues(expression: readonly Token[], column: string): string[] {
296
+ /** The value of a text or number literal token, a number possibly after a minus sign; `undefined` for any other token. */
297
+ /** The words before which a `-` is a sign, not a subtraction: the operators that take an operand after them. */
298
+ const OPERAND_FOLLOWS = new Set(['AND', 'OR', 'NOT', 'BETWEEN', 'IN', 'IS', 'LIKE', 'GLOB', 'CASE', 'WHEN', 'THEN', 'ELSE', 'CHECK'])
299
+
300
+ /** Whether `token` ends an operand, so a `-` after it subtracts (`a-1`) rather than signs a number (`> -1`). */
301
+ function endsOperand(token: Token | undefined): boolean {
302
+ if (token === undefined) return false
303
+ if (token.kind === 'name' || token.kind === 'string') return true
304
+ if (token.kind === 'word') return !OPERAND_FOLLOWS.has(token.text.toUpperCase())
305
+ return token.text === ')' || /^(?:[0-9]|\.[0-9])/.test(token.text)
306
+ }
307
+
308
+ function literalOf(tokens: readonly Token[], index: number): { readonly value: CheckLiteral; readonly width: number } | undefined {
309
+ const token = tokens[index]
310
+ if (token?.kind === 'string') return { value: token.text, width: 1 }
311
+ const negative = isPunctuation(token, '-') && !endsOperand(tokens[index - 1])
312
+ const number = negative ? tokens[index + 1] : token
313
+ if (number?.kind !== 'other' || !/^(?:[0-9]|\.[0-9])/.test(number.text)) return undefined
314
+ const value = Number(number.text)
315
+ if (!Number.isFinite(value)) return undefined
316
+ return { value: negative ? -value : value, width: negative ? 2 : 1 }
317
+ }
318
+
319
+ /** Every text and number literal of a CHECK expression. */
320
+ function expressionLiterals(expression: readonly Token[]): CheckLiteral[] {
321
+ const literals: CheckLiteral[] = []
322
+ for (let index = 0; index < expression.length; index++) {
323
+ const literal = literalOf(expression, index)
324
+ if (literal === undefined) continue
325
+ literals.push(literal.value)
326
+ index += literal.width - 1
327
+ }
328
+ return literals
329
+ }
330
+
331
+ /** The values of `<column> IN ('a', 'b', …)` or `IN (1, 2, …)`, parenthesized or not, or none for any other expression. */
332
+ function listedValues(expression: readonly Token[], column: string): CheckLiteral[] {
239
333
  let tokens = expression
240
334
  while (isPunctuation(tokens[0], '(') && closing(tokens, 0) === tokens.length - 1) {
241
335
  tokens = tokens.slice(1, -1)
@@ -252,18 +346,18 @@ function listedValues(expression: readonly Token[], column: string): string[] {
252
346
  if (!named || subject.text.toLowerCase() !== column.toLowerCase() || !isWord(tokens[list], 'IN') || !isPunctuation(tokens[list + 1], '(')) return []
253
347
  if (!isPunctuation(tokens.at(-1), ')') || closing(tokens, list + 1) !== tokens.length - 1) return []
254
348
  const items = tokens.slice(list + 2, -1)
255
- const values: string[] = []
256
- for (let index = 0; index < items.length; index++) {
257
- const item = items[index]
258
- if (index % 2 === 1) {
259
- if (!isPunctuation(item, ',')) return []
260
- } else if (item?.kind === 'string') {
261
- values.push(item.text)
262
- } else {
263
- return []
264
- }
349
+ const values: CheckLiteral[] = []
350
+ let index = 0
351
+ while (index < items.length) {
352
+ const literal = literalOf(items, index)
353
+ if (literal === undefined) return []
354
+ values.push(literal.value)
355
+ index += literal.width
356
+ if (index === items.length) return values
357
+ if (!isPunctuation(items[index], ',')) return []
358
+ index += 1
265
359
  }
266
- return items.length % 2 === 1 ? values : []
360
+ return []
267
361
  }
268
362
 
269
363
  /** 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 +394,7 @@ function tableChecks(table: string, sql: string, columns: readonly string[]): Ch
300
394
  table,
301
395
  columns: [...named],
302
396
  values: named.size === 1 && only !== undefined ? listedValues(expression, only) : [],
397
+ literals: expressionLiterals(expression),
303
398
  })
304
399
  index = close
305
400
  }
@@ -416,9 +511,14 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
416
511
  if (check !== null) return checkLimit(check[1] ?? 'unnamed', table)
417
512
  // SQLite names no foreign key in its error.
418
513
  if (message.startsWith('FOREIGN KEY constraint failed')) return foreignKeyLimit('unnamed', table)
419
- // SQLite names a unique index by its columns in its error: `UNIQUE constraint failed: t.a, t.b`.
514
+ // SQLite names a unique index by its columns in its error, `UNIQUE constraint failed: t.a, t.b`, or one on an
515
+ // expression by its name, `UNIQUE constraint failed: index 'i'`.
420
516
  const unique = /^UNIQUE constraint failed: (.*)$/s.exec(message)
421
- if (unique !== null) return uniqueValueLimit(`(${unique[1] ?? 'unnamed'})`, table)
517
+ if (unique !== null) {
518
+ const named = unique[1] ?? 'unnamed'
519
+ const columns = named.startsWith('index ') ? undefined : named.split(', ').map((column) => column.slice(column.indexOf('.') + 1))
520
+ return uniqueValueLimit(`(${named})`, table, columns)
521
+ }
422
522
  return undefined
423
523
  }
424
524
 
@@ -447,18 +547,23 @@ function applicationMigrations(directory: string): SqliteMigrationBundle['migrat
447
547
  */
448
548
  export async function testDatabase(options: TestDatabaseOptions): Promise<TestDatabase> {
449
549
  refuseInProduction(MODULE)
550
+ return (await openTestDatabase(options)).database
551
+ }
552
+
553
+ /** The test database of `options`, with its bun:sqlite database and the key of its migrations. */
554
+ async function openTestDatabase(
555
+ options: TestDatabaseOptions,
556
+ ): Promise<{ readonly database: TestDatabase; readonly sqlite: BunDatabase; readonly migrations: string }> {
450
557
  const migrations = applicationMigrations(migrationsDirectory(options.migrations))
451
- const sqlite = new BunDatabase(':memory:')
452
- const storage = bunSqliteStorage(sqlite)
453
- try {
454
- await migrateSqlite({ exec: storage.sql.exec, transactionSync: (fn) => storage.transactionSync(fn) }, [
455
- { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
456
- { bundle: APPLICATION_MIGRATION_BUNDLE, migrations },
457
- ])
458
- } catch (error) {
459
- sqlite.close()
460
- throw error
558
+ const key = migrationsKey(migrations)
559
+ if (options.template !== undefined && options.template.migrations !== key) {
560
+ throw new Error(`${options.label}: the template was migrated with other migrations than ${String(options.migrations)}; build it again`)
561
+ }
562
+ const sqlite = await migratedDatabase(migrations, options.template?.image ?? migratedImages.get(key))
563
+ if (options.template === undefined && !migratedImages.has(key)) {
564
+ migratedImages.set(key, sqlite.serialize())
461
565
  }
566
+ const storage = bunSqliteStorage(sqlite)
462
567
  const exec: Exec = (query, ...bindings) => storage.sql.exec(query, ...bindings).toArray()
463
568
  const columns = readColumns(exec)
464
569
  const withoutRowid = new Set(
@@ -557,13 +662,17 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
557
662
  }
558
663
  const database = openSqlite(storage)
559
664
  return {
560
- ...testSeeding(backend),
561
- database,
562
- schema: 'main',
563
- async close() {
564
- await database.close()
565
- sqlite.close()
665
+ database: {
666
+ ...testSeeding(backend),
667
+ database,
668
+ schema: 'main',
669
+ async close() {
670
+ await database.close()
671
+ sqlite.close()
672
+ },
566
673
  },
674
+ sqlite,
675
+ migrations: key,
567
676
  }
568
677
  }
569
678
 
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
- /** A sample for a required column the test does not care about, by the types `@fabrika/db/codegen` accepts. */
94
- function sampleOf(table: string, column: CatalogColumn): Primitive {
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 [first] = column.enum_labels
97
- if (first !== undefined) {
98
- return first
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' ? '1' : 1
106
- if (type === 'bool') return false
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 '12:00:00'
112
- if (type === 'interval') return '1 hour'
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
- /** `CHECK ((status = ANY (ARRAY['open'::text, 'done'::text])))`, a one-column `IN` list as Postgres prints it. */
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 = /'((?:[^']|'')*)'::/g
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[]): 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
- return [...(listed[2] ?? '').matchAll(LITERAL)].map((match) => (match[1] ?? '').replaceAll("''", "'"))
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. */
@@ -229,7 +266,7 @@ const TEST_SCHEMA = /^app_test_[0-9a-f]{16}$/
229
266
  const TEST_ROLE = /^(?:app|run)_(test_[0-9a-f]{16})$/
230
267
  /**
231
268
  * Why an abandoned family is left alone: `DROP ROLE` of a role that still owns something in another database of the
232
- * cluster, and a family another provisioner created (a `test-isolation` run's), which only it administers.
269
+ * cluster, and a family another provisioner created, which only it administers.
233
270
  */
234
271
  const LEFT_TO_ITS_OWNER: ReadonlySet<unknown> = new Set(['2BP01', '42501'])
235
272
 
@@ -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 seeded. */
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 seeded. */
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 its values fail, a required foreign key to a scoped table
69
- * outside the containment chain. It is a limit of the generator, named with the constraint or the column, never a
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
- /** 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. */
172
- readonly sample: () => Primitive;
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 string[];
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): SeedLimitError;
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): SeedLimitError;
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): SeedLimitError;
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
  /**
@@ -7,7 +7,22 @@ export interface TestDatabaseOptions {
7
7
  readonly migrations: string | URL;
8
8
  /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
9
9
  readonly label: string;
10
+ /** A database migrated and seeded once (`testDatabaseTemplate`), which this one starts as a copy of. */
11
+ readonly template?: TestDatabaseTemplate;
10
12
  }
13
+ /** A migrated database with its base seed, as an image every `testDatabase({ template })` copies. */
14
+ export interface TestDatabaseTemplate {
15
+ /** The migrations it was migrated with: a database of other migrations does not start from it. */
16
+ readonly migrations: string;
17
+ readonly image: Uint8Array;
18
+ }
19
+ /**
20
+ * Migrates a database once, runs `seed` in it, and keeps it as the image each `testDatabase({ template })` starts as a
21
+ * copy of: in milliseconds, without migrating or seeding again.
22
+ */
23
+ export declare function testDatabaseTemplate(options: Omit<TestDatabaseOptions, 'template'> & {
24
+ readonly seed?: (database: TestDatabase) => Promise<void>;
25
+ }): Promise<TestDatabaseTemplate>;
11
26
  /**
12
27
  * A fresh in-memory database with the framework's and the application's migrations applied by the runner a Durable
13
28
  * Object boots with (`@fabrika/db/sqlite-migrate`), opened with its engine (`@fabrika/db/sqlite`). Never `null`: it