@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.51

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -21,19 +21,24 @@ import type { TableProbe } from './store'
21
21
  import {
22
22
  type CheckConstraint,
23
23
  checkLimit,
24
+ type CheckLiteral,
24
25
  foreignKeyLimit,
26
+ groupsWhere,
25
27
  type InsertedRow,
26
28
  MAX_REMOVED_ROWS,
27
29
  probeTable,
28
30
  randomHex,
29
31
  removalLimit,
30
32
  type SampleValue,
33
+ seedBinding,
31
34
  type SeedColumn,
32
35
  type SeedingBackend,
33
36
  SeedLimitError,
34
37
  type TestDatabase,
35
38
  testSeeding,
36
39
  typeLimit,
40
+ type UniqueIndex,
41
+ uniqueValueLimit,
37
42
  } from './testing-shared'
38
43
 
39
44
  export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
@@ -41,6 +46,7 @@ export {
41
46
  type ApplicationRow,
42
47
  type IsolationWorlds,
43
48
  type SampleValue,
49
+ type ScopeValues,
44
50
  SEEDED_OBJECT_VERSION,
45
51
  type SeededApplicationRows,
46
52
  type SeededRow,
@@ -61,6 +67,59 @@ export interface TestDatabaseOptions {
61
67
  readonly migrations: string | URL
62
68
  /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
63
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
+ }
64
123
  }
65
124
 
66
125
  type Exec = (query: string, ...bindings: SqliteValue[]) => Record<string, SqliteValue>[]
@@ -74,19 +133,26 @@ function baseType(declared: string): string {
74
133
  return declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
75
134
  }
76
135
 
77
- /** A sample for a required column the test does not care about, by the declared types `@fabrika/db/codegen-sqlite` accepts. */
78
- 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 {
79
141
  const type = baseType(declared)
80
142
  if (type === 'UUID') return crypto.randomUUID()
81
143
  if (TEXT_TYPES.has(type)) return `s${randomHex()}`
82
- if (NUMBER_TYPES.has(type)) return 1
83
- if (type === 'BOOLEAN') return false
144
+ if (NUMBER_TYPES.has(type)) return 1 + variant
145
+ if (type === 'BOOLEAN') return variant % 2 === 1
84
146
  // A day is `YYYY-MM-DD` and a timestamp ISO text in UTC: the forms the layer writes and reads on SQLite.
85
- if (type === 'DATE') return new Date().toISOString().slice(0, 10)
86
- 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()
149
+ // A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
150
+ if (type === 'JSONB') return variant === 0 ? 'sample' : `sample-${variant}`
87
151
  throw typeLimit(table, column, declared)
88
152
  }
89
153
 
154
+ const DAY_MS = 86_400_000
155
+
90
156
  const tableRows = z.array(z.object({ name: z.string(), wr: z.number() }))
91
157
  const columnRows = z.array(
92
158
  z.object({ name: z.string(), type: z.string(), notnull: z.number(), dflt_value: z.string().nullable(), pk: z.number(), hidden: z.number() }),
@@ -114,7 +180,9 @@ function readColumns(exec: Exec): SeedColumn[] {
114
180
  defaulted: rowid || column.dflt_value !== null || column.hidden === 2 || column.hidden === 3,
115
181
  text: TEXT_TYPES.has(type),
116
182
  uuid: type === 'UUID',
117
- sample: () => sampleOf(table.name, column.name, column.type),
183
+ number: NUMBER_TYPES.has(type),
184
+ json: type === 'JSONB',
185
+ sample: (variant) => sampleOf(table.name, column.name, column.type, variant),
118
186
  })
119
187
  }
120
188
  }
@@ -225,8 +293,43 @@ function definitions(tokens: readonly Token[]): Token[][] {
225
293
 
226
294
  const TABLE_CONSTRAINTS: ReadonlySet<string> = new Set(['CONSTRAINT', 'CHECK', 'PRIMARY', 'UNIQUE', 'FOREIGN'])
227
295
 
228
- /** The values of `<column> IN ('a', 'b', …)`, parenthesized or not, or none for any other expression. */
229
- 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[] {
230
333
  let tokens = expression
231
334
  while (isPunctuation(tokens[0], '(') && closing(tokens, 0) === tokens.length - 1) {
232
335
  tokens = tokens.slice(1, -1)
@@ -243,18 +346,18 @@ function listedValues(expression: readonly Token[], column: string): string[] {
243
346
  if (!named || subject.text.toLowerCase() !== column.toLowerCase() || !isWord(tokens[list], 'IN') || !isPunctuation(tokens[list + 1], '(')) return []
244
347
  if (!isPunctuation(tokens.at(-1), ')') || closing(tokens, list + 1) !== tokens.length - 1) return []
245
348
  const items = tokens.slice(list + 2, -1)
246
- const values: string[] = []
247
- for (let index = 0; index < items.length; index++) {
248
- const item = items[index]
249
- if (index % 2 === 1) {
250
- if (!isPunctuation(item, ',')) return []
251
- } else if (item?.kind === 'string') {
252
- values.push(item.text)
253
- } else {
254
- return []
255
- }
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
256
359
  }
257
- return items.length % 2 === 1 ? values : []
360
+ return []
258
361
  }
259
362
 
260
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. */
@@ -291,6 +394,7 @@ function tableChecks(table: string, sql: string, columns: readonly string[]): Ch
291
394
  table,
292
395
  columns: [...named],
293
396
  values: named.size === 1 && only !== undefined ? listedValues(expression, only) : [],
397
+ literals: expressionLiterals(expression),
294
398
  })
295
399
  index = close
296
400
  }
@@ -298,6 +402,50 @@ function tableChecks(table: string, sql: string, columns: readonly string[]): Ch
298
402
  return checks
299
403
  }
300
404
 
405
+ const indexRows = z.array(z.object({ name: z.string(), partial: z.number(), column: z.string().nullable() }))
406
+ const maxRows = z.array(z.object({ largest: z.unknown() }))
407
+
408
+ /**
409
+ * Every unique index of the tables (a primary key's and a UNIQUE constraint's are one) whose key columns are all plain
410
+ * columns and that has no predicate, with its key columns (`pragma_index_info` lists no others). An index on an
411
+ * expression (a key column with no name) or a partial one is left out. SQLite has no `NULLS NOT DISTINCT`.
412
+ */
413
+ function readUniqueIndexes(exec: Exec, tables: readonly string[]): UniqueIndex[] {
414
+ const indexes: UniqueIndex[] = []
415
+ for (const table of tables) {
416
+ const covered = new Map<string, (string | null)[]>()
417
+ const rows = indexRows.parse(
418
+ exec(
419
+ 'SELECT l.name AS name, l.partial AS partial, i.name AS "column" FROM pragma_index_list(?) l, pragma_index_info(l.name) i WHERE l."unique" = 1 ORDER BY l.name, i.seqno',
420
+ table,
421
+ ),
422
+ )
423
+ for (const row of rows) {
424
+ if (row.partial === 0) covered.set(row.name, [...(covered.get(row.name) ?? []), row.column])
425
+ }
426
+ for (const [name, columns] of covered) {
427
+ const plain = columns.flatMap((column) => column ?? [])
428
+ if (plain.length === columns.length) indexes.push({ name, table, columns: plain, nullsNotDistinct: false })
429
+ }
430
+ }
431
+ return indexes
432
+ }
433
+
434
+ /**
435
+ * The smallest whole number above every value of the column in the rows that match one of `groups`, and at least 1;
436
+ * `undefined` past the safe integers, or where the largest is no finite number.
437
+ */
438
+ function readNextNumber(exec: Exec, table: string, column: string, groups: readonly ReadonlyMap<string, SampleValue>[]): number | undefined {
439
+ const { where, values } = groupsWhere(groups, quoted, () => '?')
440
+ const [found] = maxRows.parse(exec(`SELECT max(${quoted(column)}) AS largest FROM ${quoted(table)} WHERE ${where}`, ...values.map(binding)))
441
+ const largest = found?.largest ?? null
442
+ if (largest === null) return 1
443
+ const value = typeof largest === 'bigint' ? Number(largest) : largest
444
+ if (typeof value !== 'number') return undefined
445
+ const next = Math.max(Math.floor(value) + 1, 1)
446
+ return Number.isSafeInteger(next) ? next : undefined
447
+ }
448
+
301
449
  const foreignKeyRows = z.array(z.object({ id: z.number(), seq: z.number(), table: z.string(), from: z.string(), to: z.string().nullable() }))
302
450
  const keyRows = z.array(z.object({ name: z.string(), pk: z.number() }))
303
451
  const rowidRows = z.array(z.object({ id: z.number() }))
@@ -363,6 +511,14 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
363
511
  if (check !== null) return checkLimit(check[1] ?? 'unnamed', table)
364
512
  // SQLite names no foreign key in its error.
365
513
  if (message.startsWith('FOREIGN KEY constraint failed')) return foreignKeyLimit('unnamed', table)
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'`.
516
+ const unique = /^UNIQUE constraint failed: (.*)$/s.exec(message)
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
+ }
366
522
  return undefined
367
523
  }
368
524
 
@@ -386,23 +542,28 @@ function applicationMigrations(directory: string): SqliteMigrationBundle['migrat
386
542
  /**
387
543
  * A fresh in-memory database with the framework's and the application's migrations applied by the runner a Durable
388
544
  * Object boots with (`@fabrika/db/sqlite-migrate`), opened with its engine (`@fabrika/db/sqlite`). Never `null`: it
389
- * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a generated test
545
+ * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a test
390
546
  * that checks for `null` compiles against both kits.
391
547
  */
392
548
  export async function testDatabase(options: TestDatabaseOptions): Promise<TestDatabase> {
393
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 }> {
394
557
  const migrations = applicationMigrations(migrationsDirectory(options.migrations))
395
- const sqlite = new BunDatabase(':memory:')
396
- const storage = bunSqliteStorage(sqlite)
397
- try {
398
- await migrateSqlite({ exec: storage.sql.exec, transactionSync: (fn) => storage.transactionSync(fn) }, [
399
- { bundle: FRAMEWORK_MIGRATION_BUNDLE, migrations: SQLITE_FRAMEWORK_MIGRATIONS },
400
- { bundle: APPLICATION_MIGRATION_BUNDLE, migrations },
401
- ])
402
- } catch (error) {
403
- sqlite.close()
404
- 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`)
405
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())
565
+ }
566
+ const storage = bunSqliteStorage(sqlite)
406
567
  const exec: Exec = (query, ...bindings) => storage.sql.exec(query, ...bindings).toArray()
407
568
  const columns = readColumns(exec)
408
569
  const withoutRowid = new Set(
@@ -418,6 +579,8 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
418
579
  const backend: SeedingBackend = {
419
580
  columns,
420
581
  checks: async () => readChecks(exec, columns),
582
+ uniqueIndexes: async () => readUniqueIndexes(exec, [...new Set(columns.map((column) => column.table))]),
583
+ nextNumber: async (table, column, groups) => readNextNumber(exec, table, column, groups),
421
584
  async insert(table, row) {
422
585
  const names = [...row.keys()]
423
586
  const target = quoted(table)
@@ -425,13 +588,18 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
425
588
  ? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
426
589
  : `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${names.map(() => '?').join(', ')}) RETURNING *`
427
590
  try {
428
- return exec(statement, ...names.map((name) => binding(row.get(name) ?? null)))[0] ?? {}
591
+ return exec(statement, ...names.map((name) => binding(seedBinding(columns, table, name, row.get(name) ?? null))))[0] ?? {}
429
592
  } catch (error) {
430
593
  throw seedLimit(error, table) ?? error
431
594
  }
432
595
  },
433
- async firstRow(table, selected) {
434
- return exec(`SELECT ${selected.map(quoted).join(', ')} FROM ${quoted(table)} LIMIT 1`)[0]
596
+ async firstRow(table, selected, where = new Map()) {
597
+ const names = [...where.keys()]
598
+ const condition = names.length === 0 ? '' : ` WHERE ${names.map((name) => `${quoted(name)} = ?`).join(' AND ')}`
599
+ return exec(
600
+ `SELECT ${selected.map(quoted).join(', ')} FROM ${quoted(table)}${condition} LIMIT 1`,
601
+ ...names.map((name) => binding(where.get(name) ?? null)),
602
+ )[0]
435
603
  },
436
604
  async insertFile(file) {
437
605
  exec(
@@ -494,13 +662,17 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
494
662
  }
495
663
  const database = openSqlite(storage)
496
664
  return {
497
- ...testSeeding(backend),
498
- database,
499
- schema: 'main',
500
- async close() {
501
- await database.close()
502
- sqlite.close()
665
+ database: {
666
+ ...testSeeding(backend),
667
+ database,
668
+ schema: 'main',
669
+ async close() {
670
+ await database.close()
671
+ sqlite.close()
672
+ },
503
673
  },
674
+ sqlite,
675
+ migrations: key,
504
676
  }
505
677
  }
506
678
 
package/src/testing.ts CHANGED
@@ -26,18 +26,22 @@ import type { TableProbe } from './store'
26
26
  import {
27
27
  type CheckConstraint,
28
28
  checkLimit,
29
+ type CheckLiteral,
29
30
  foreignKeyLimit,
31
+ groupsWhere,
30
32
  type InsertedRow,
31
33
  MAX_REMOVED_ROWS,
32
34
  probeTable,
33
35
  randomHex,
34
36
  removalLimit,
37
+ seedBinding,
35
38
  type SeedColumn,
36
39
  type SeedingBackend,
37
40
  type SeedLimitError,
38
41
  type TestDatabase,
39
42
  testSeeding,
40
43
  typeLimit,
44
+ uniqueValueLimit,
41
45
  } from './testing-shared'
42
46
 
43
47
  export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
@@ -45,6 +49,7 @@ export {
45
49
  type ApplicationRow,
46
50
  type IsolationWorlds,
47
51
  type SampleValue,
52
+ type ScopeValues,
48
53
  SEEDED_OBJECT_VERSION,
49
54
  type SeededApplicationRows,
50
55
  type SeededRow,
@@ -80,31 +85,39 @@ export interface TestDatabaseOptions {
80
85
  let capacityExhausted: ConnectionCapacityError | undefined
81
86
 
82
87
  const TEXT_TYPES: ReadonlySet<string> = new Set(['text', 'varchar', 'bpchar'])
88
+ const NUMBER_TYPES: ReadonlySet<string> = new Set(['int2', 'int4', 'int8', 'float4', 'float8', 'numeric'])
83
89
 
84
90
  function quoted(identifier: string): string {
85
91
  return `"${identifier}"`
86
92
  }
87
93
 
88
- /** A sample for a required column the test does not care about, by the types `@fabrika/db/codegen` accepts. */
89
- 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 {
90
101
  if (column.type_type === 'e') {
91
- const [first] = column.enum_labels
92
- if (first !== undefined) {
93
- return first
102
+ const label = column.enum_labels[variant % Math.max(column.enum_labels.length, 1)]
103
+ if (label !== undefined) {
104
+ return label
94
105
  }
95
106
  }
96
107
  const type = column.type_name
97
108
  if (type === 'uuid') return crypto.randomUUID()
98
109
  if (TEXT_TYPES.has(type)) return `s${randomHex()}`
99
- if (type === 'int2' || type === 'int4' || type === 'float4' || type === 'float8') return 1
100
- if (type === 'int8' || type === 'numeric') return '1'
101
- if (type === 'bool') return false
110
+ // Bun.SQL reads an int8 and a numeric as text.
111
+ if (NUMBER_TYPES.has(type)) return type === 'int8' || type === 'numeric' ? String(1 + variant) : 1 + variant
112
+ if (type === 'bool') return variant % 2 === 1
102
113
  // ISO text, not a Date: the seed binds past the layer's compiler, where Bun.SQL would send Date#toString(). A day is
103
114
  // `YYYY-MM-DD`, since the probe's insert sends it through the layer, which takes a `date` only so.
104
- if (type === 'date') return new Date().toISOString().slice(0, 10)
105
- if (type === 'timestamp' || type === 'timestamptz') return new Date().toISOString()
106
- if (type === 'time' || type === 'timetz') return '12:00:00'
107
- 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`
119
+ // A JSON string: a seed value has no object form, and `seedBinding` writes it as the layer would.
120
+ if (type === 'jsonb') return variant === 0 ? 'sample' : `sample-${variant}`
108
121
  throw typeLimit(table, column.column_name, type)
109
122
  }
110
123
 
@@ -118,7 +131,9 @@ function seedColumn(column: CatalogColumn): SeedColumn {
118
131
  defaulted: column.generated !== 'no',
119
132
  text: column.type_type !== 'e' && TEXT_TYPES.has(column.type_name),
120
133
  uuid: column.type_name === 'uuid',
121
- sample: () => sampleOf(column.table_name, column),
134
+ number: column.type_type !== 'e' && NUMBER_TYPES.has(column.type_name),
135
+ json: column.type_type === 'b' && column.type_category !== 'A' && column.type_name === 'jsonb',
136
+ sample: (variant) => sampleOf(column.table_name, column, variant),
122
137
  }
123
138
  }
124
139
 
@@ -135,6 +150,44 @@ WHERE n.nspname = $1 AND c.contype = 'c'
135
150
  ORDER BY r.relname, c.conname
136
151
  `
137
152
 
153
+ const uniqueRows = z.array(z.object({ name: z.string(), table_name: z.string(), columns: z.array(z.string()), nulls_not_distinct: z.boolean() }))
154
+
155
+ /**
156
+ * Every unique index of the schema's tables (a primary key's and a UNIQUE constraint's are one) whose key columns are all
157
+ * plain columns and that has no predicate, with its key columns: the first `indnkeyatts` of `indkey`, never an `INCLUDE`
158
+ * column. An index on an expression (`indexprs`) or a partial one (`indpred`) is left out.
159
+ */
160
+ const UNIQUE_QUERY = `
161
+ SELECT i.relname::text AS name, r.relname::text AS table_name, x.indnullsnotdistinct AS nulls_not_distinct,
162
+ ARRAY(
163
+ SELECT a.attname::text FROM pg_attribute a
164
+ WHERE a.attrelid = x.indrelid AND a.attnum = ANY ((x.indkey::int2[])[0:x.indnkeyatts - 1])
165
+ ORDER BY a.attnum
166
+ ) AS columns
167
+ FROM pg_index x
168
+ JOIN pg_class i ON i.oid = x.indexrelid
169
+ JOIN pg_class r ON r.oid = x.indrelid
170
+ JOIN pg_namespace n ON n.oid = r.relnamespace
171
+ WHERE n.nspname = $1 AND x.indisunique AND x.indexprs IS NULL AND x.indpred IS NULL
172
+ ORDER BY r.relname, i.relname
173
+ `
174
+
175
+ const typeRows = z.array(z.object({ table_name: z.string(), column_name: z.string(), type: z.string() }))
176
+
177
+ /** Every column of the schema's tables with its type as Postgres writes it (`smallint`, `numeric(3,0)`): a cast keeps its range and scale. */
178
+ const TYPE_QUERY = `
179
+ SELECT r.relname::text AS table_name, a.attname::text AS column_name, format_type(a.atttypid, a.atttypmod) AS type
180
+ FROM pg_attribute a
181
+ JOIN pg_class r ON r.oid = a.attrelid
182
+ JOIN pg_namespace n ON n.oid = r.relnamespace
183
+ WHERE n.nspname = $1 AND r.relkind IN ('r', 'p') AND a.attnum > 0 AND NOT a.attisdropped
184
+ `
185
+
186
+ const nextRows = z.array(z.object({ next: z.union([z.number(), z.string(), z.bigint()]).nullable() }))
187
+
188
+ /** SQLSTATE `numeric_value_out_of_range`: the column's type holds no such number. */
189
+ const OUT_OF_RANGE = '22003'
190
+
138
191
  const referrerRows = z.array(z.object({ table_name: z.string(), columns: z.array(z.string()), refs: z.array(z.string()) }))
139
192
 
140
193
  /** Every foreign key of the schema's tables that references the table `$2`, with its columns and the ones it references, in order. */
@@ -156,15 +209,46 @@ const ctidRows = z.array(z.object({ ctid: z.string() }))
156
209
  /** Ctids as one array literal parameter, `{"(0,1)","(0,2)"}`: the driver mis-binds a JS array. */
157
210
  const tidArray = (ctids: Iterable<string>): string => `{${[...ctids].map((ctid) => `"${ctid}"`).join(',')}}`
158
211
 
159
- /** `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
+ */
160
216
  const IN_LIST = /^CHECK \(\(\(?"?([^"()\s]+)"?\)?(?:::[a-z ]+)? = ANY \(\(?ARRAY\[(.+)\]\)?(?:::[a-z ]+\[\])?\)\)\)$/
161
- 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
+ }
162
231
 
163
232
  /** The values of a one-column `IN` list, or none for any other CHECK. */
164
- function listedValues(definition: string, columns: readonly string[]): string[] {
233
+ function listedValues(definition: string, columns: readonly string[]): CheckLiteral[] {
165
234
  const listed = IN_LIST.exec(definition)
166
235
  if (listed === null || columns.length !== 1 || listed[1] !== columns[0]) return []
167
- 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]))
168
252
  }
169
253
 
170
254
  /** A CHECK or foreign key violation of a seeded row, as the generator limit it is; `undefined` for any other failure. */
@@ -173,6 +257,7 @@ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
173
257
  const constraint = error.constraint ?? 'unnamed'
174
258
  if (error.errno === '23514') return checkLimit(constraint, table)
175
259
  if (error.errno === '23503') return foreignKeyLimit(constraint, table)
260
+ if (error.errno === '23505') return uniqueValueLimit(constraint, table)
176
261
  return undefined
177
262
  }
178
263
 
@@ -181,7 +266,7 @@ const TEST_SCHEMA = /^app_test_[0-9a-f]{16}$/
181
266
  const TEST_ROLE = /^(?:app|run)_(test_[0-9a-f]{16})$/
182
267
  /**
183
268
  * Why an abandoned family is left alone: `DROP ROLE` of a role that still owns something in another database of the
184
- * 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.
185
270
  */
186
271
  const LEFT_TO_ITS_OWNER: ReadonlySet<unknown> = new Set(['2BP01', '42501'])
187
272
 
@@ -338,15 +423,54 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
338
423
  )
339
424
  await tx.unsafe(`WITH ${deletes.join(', ')} SELECT 1`, tables.map(([, ctids]) => tidArray(ctids)))
340
425
  }
426
+ let types: Promise<ReadonlyMap<string, string>> | undefined
427
+ const seedColumns = catalog.map(seedColumn)
341
428
  const backend: SeedingBackend = {
342
- columns: catalog.map(seedColumn),
429
+ columns: seedColumns,
343
430
  checks: async () =>
344
431
  checkRows.parse(await lock.unsafe(CHECK_QUERY, [schema])).map((row): CheckConstraint => ({
345
432
  name: row.name,
346
433
  table: row.table_name,
347
434
  columns: row.columns,
348
435
  values: listedValues(row.definition, row.columns),
436
+ literals: definitionLiterals(row.definition),
437
+ })),
438
+ uniqueIndexes: async () =>
439
+ uniqueRows.parse(await lock.unsafe(UNIQUE_QUERY, [schema])).map((row) => ({
440
+ name: row.name,
441
+ table: row.table_name,
442
+ columns: row.columns,
443
+ nullsNotDistinct: row.nulls_not_distinct,
349
444
  })),
445
+ async nextNumber(table, column, groups) {
446
+ // A read that failed is read again on the next call, never answered from the cache.
447
+ types ??= lock.unsafe(TYPE_QUERY, [schema]).then(
448
+ (rows: unknown) => new Map(typeRows.parse(rows).map((row) => [`${row.table_name}.${row.column_name}`, row.type])),
449
+ (error: unknown) => {
450
+ types = undefined
451
+ throw error
452
+ },
453
+ )
454
+ const type = (await types).get(`${table}.${column}`)
455
+ if (type === undefined) {
456
+ throw new Error(`${table}.${column} is not a column of the migrated schema`)
457
+ }
458
+ const { where, values: bindings } = groupsWhere(groups, quoted, (position) => `$${position}`)
459
+ const largest = `(SELECT max(${quoted(column)}) FROM ${quoted(schema)}.${quoted(table)} WHERE ${where})`
460
+ // A float's NaN or Infinity has no next number; the cast refuses one the type cannot hold (22003).
461
+ const statement = `SELECT CASE WHEN largest IS NULL THEN 1::${type} WHEN largest::text IN ('NaN', 'Infinity', '-Infinity') THEN NULL
462
+ ELSE GREATEST(floor(largest::numeric) + 1, 1)::${type} END AS next FROM ${largest} AS m (largest)`
463
+ let next: unknown
464
+ try {
465
+ next = await seeder.unsafe(statement, bindings)
466
+ } catch (error) {
467
+ if (error instanceof SQL.PostgresError && error.errno === OUT_OF_RANGE) return undefined
468
+ throw error
469
+ }
470
+ const [found] = nextRows.parse(next)
471
+ if (found === undefined || found.next === null) return undefined
472
+ return typeof found.next === 'bigint' ? String(found.next) : found.next
473
+ },
350
474
  async insert(table, row) {
351
475
  const names = [...row.keys()]
352
476
  const placeholders = names.map((_, index) => `$${index + 1}`)
@@ -356,15 +480,20 @@ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDa
356
480
  : `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${placeholders.join(', ')}) RETURNING *`
357
481
  let stored: unknown
358
482
  try {
359
- stored = await seeder.unsafe(statement, names.map((name) => row.get(name) ?? null))
483
+ stored = await seeder.unsafe(statement, names.map((name) => seedBinding(seedColumns, table, name, row.get(name) ?? null)))
360
484
  } catch (error) {
361
485
  throw seedLimit(error, table) ?? error
362
486
  }
363
487
  const [returned] = z.array(z.record(z.string(), z.unknown())).parse(stored)
364
488
  return returned ?? {}
365
489
  },
366
- async firstRow(table, columns) {
367
- const selected: unknown = await seeder.unsafe(`SELECT ${columns.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(table)} LIMIT 1`)
490
+ async firstRow(table, columns, where = new Map()) {
491
+ const names = [...where.keys()]
492
+ const condition = names.length === 0 ? '' : ` WHERE ${names.map((name, index) => `${quoted(name)} = $${index + 1}`).join(' AND ')}`
493
+ const selected: unknown = await seeder.unsafe(
494
+ `SELECT ${columns.map(quoted).join(', ')} FROM ${quoted(schema)}.${quoted(table)}${condition} LIMIT 1`,
495
+ names.map((name) => where.get(name) ?? null),
496
+ )
368
497
  return z.array(z.record(z.string(), z.unknown())).parse(selected)[0]
369
498
  },
370
499
  async insertFile(file) {