@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.21

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 (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
@@ -0,0 +1,685 @@
1
+ // @fabrika/db/testing-sqlite — the database test kit of an application on SQLite (Cloudflare, ADR-0065), for test files
2
+ // only. A test database is a fresh in-memory bun:sqlite database shaped like a Durable Object's storage, migrated by
3
+ // the object's own runner and opened with the object's engine; the isolation fixtures and the table probe are
4
+ // `@fabrika/db/testing`'s. No backend is needed, so it never skips. There is no role separation on SQLite: the fixture
5
+ // seeds through the same storage the application writes.
6
+
7
+ import { APPLICATION_MIGRATION_BUNDLE } from '@fabrika/platform-node'
8
+ import { Database as BunDatabase } from 'bun:sqlite'
9
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
10
+ import { join } from 'node:path'
11
+ import { fileURLToPath } from 'node:url'
12
+ import { z } from 'zod/v4'
13
+ import type { Primitive } from './description'
14
+ import { FILES_TABLE, FRAMEWORK_MIGRATION_BUNDLE } from './migrations'
15
+ import { SQLITE_FRAMEWORK_MIGRATIONS, SQLITE_NOW_FORMAT } from './migrations-sqlite'
16
+ import { refuseInProduction } from './production'
17
+ import { openSqlite, type SqliteValue } from './sqlite'
18
+ import { bunSqliteStorage } from './sqlite-bun'
19
+ import { migrateSqlite, type SqliteMigrationBundle } from './sqlite-migrate'
20
+ import type { TableProbe } from './store'
21
+ import {
22
+ type CheckConstraint,
23
+ checkLimit,
24
+ type CheckLiteral,
25
+ foreignKeyLimit,
26
+ groupsWhere,
27
+ type InsertedRow,
28
+ MAX_REMOVED_ROWS,
29
+ probeTable,
30
+ randomHex,
31
+ removalLimit,
32
+ type SampleValue,
33
+ seedBinding,
34
+ type SeedColumn,
35
+ type SeedingBackend,
36
+ SeedLimitError,
37
+ type TestDatabase,
38
+ testSeeding,
39
+ typeLimit,
40
+ type UniqueIndex,
41
+ uniqueValueLimit,
42
+ } from './testing-shared'
43
+
44
+ export { ChildTable, defineChildStore, defineStore, DimensionTable, type TableProbe } from './store'
45
+ export {
46
+ type ApplicationRow,
47
+ type IsolationWorlds,
48
+ type SampleValue,
49
+ type ScopeValues,
50
+ SEEDED_OBJECT_VERSION,
51
+ type SeededApplicationRows,
52
+ type SeededRow,
53
+ SeedLimitError,
54
+ type TestDatabase,
55
+ type WorldRow,
56
+ } from './testing-shared'
57
+
58
+ const MODULE = '@fabrika/db/testing-sqlite'
59
+ refuseInProduction(MODULE)
60
+ const release = process.env['FABRIKA_RELEASE']
61
+ if (release !== undefined && release !== '') {
62
+ throw new Error(`${MODULE} is a test helper and does not load in a release (FABRIKA_RELEASE is set)`)
63
+ }
64
+
65
+ export interface TestDatabaseOptions {
66
+ /** The application's `db/migrations/` directory. */
67
+ readonly migrations: string | URL
68
+ /** The test file. `@fabrika/db/testing` names it when it skips; this kit never skips. */
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
+ }
123
+ }
124
+
125
+ type Exec = (query: string, ...bindings: SqliteValue[]) => Record<string, SqliteValue>[]
126
+
127
+ const TEXT_TYPES: ReadonlySet<string> = new Set(['TEXT', 'VARCHAR', 'CHAR'])
128
+ const NUMBER_TYPES: ReadonlySet<string> = new Set(['INTEGER', 'INT', 'BIGINT', 'SMALLINT', 'REAL', 'DOUBLE', 'FLOAT'])
129
+ const TIMESTAMP_TYPES: ReadonlySet<string> = new Set(['TIMESTAMP', 'TIMESTAMPTZ', 'DATETIME'])
130
+
131
+ /** A declared type without its length or precision (`VARCHAR(80)` → `VARCHAR`), as `@fabrika/db/codegen-sqlite` reads it. */
132
+ function baseType(declared: string): string {
133
+ return declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
134
+ }
135
+
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 {
141
+ const type = baseType(declared)
142
+ if (type === 'UUID') return crypto.randomUUID()
143
+ if (TEXT_TYPES.has(type)) return `s${randomHex()}`
144
+ if (NUMBER_TYPES.has(type)) return 1 + variant
145
+ if (type === 'BOOLEAN') return variant % 2 === 1
146
+ // A day is `YYYY-MM-DD` and a timestamp ISO text in UTC: the forms the layer writes and reads on SQLite.
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}`
151
+ throw typeLimit(table, column, declared)
152
+ }
153
+
154
+ const DAY_MS = 86_400_000
155
+
156
+ const tableRows = z.array(z.object({ name: z.string(), wr: z.number() }))
157
+ const columnRows = z.array(
158
+ z.object({ name: z.string(), type: z.string(), notnull: z.number(), dflt_value: z.string().nullable(), pk: z.number(), hidden: z.number() }),
159
+ )
160
+ const schemaRows = z.array(z.object({ name: z.string(), sql: z.string() }))
161
+
162
+ /** Every column of the database's ordinary tables. */
163
+ function readColumns(exec: Exec): SeedColumn[] {
164
+ const tables = tableRows.parse(exec(`SELECT name, wr FROM pragma_table_list WHERE schema = 'main' AND type = 'table' ORDER BY name`))
165
+ .filter((table) => !table.name.startsWith('sqlite_'))
166
+ const columns: SeedColumn[] = []
167
+ for (const table of tables) {
168
+ const declared = columnRows.parse(exec('SELECT name, type, "notnull", dflt_value, pk, hidden FROM pragma_table_xinfo(?) ORDER BY cid', table.name))
169
+ const keyColumns = declared.filter((column) => column.pk > 0)
170
+ for (const column of declared) {
171
+ const type = baseType(column.type)
172
+ // An INTEGER PRIMARY KEY of a rowid table is the rowid: never null, assigned when an insert omits it.
173
+ const rowid = table.wr === 0 && keyColumns.length === 1 && column.pk === 1 && type === 'INTEGER'
174
+ columns.push({
175
+ table: table.name,
176
+ name: column.name,
177
+ type: column.type,
178
+ // SQLite lets a primary key other than the rowid hold NULL unless it says NOT NULL; a seeded row's key never does.
179
+ nullable: !rowid && column.notnull === 0 && column.pk === 0,
180
+ defaulted: rowid || column.dflt_value !== null || column.hidden === 2 || column.hidden === 3,
181
+ text: TEXT_TYPES.has(type),
182
+ uuid: type === 'UUID',
183
+ number: NUMBER_TYPES.has(type),
184
+ json: type === 'JSONB',
185
+ sample: (variant) => sampleOf(table.name, column.name, column.type, variant),
186
+ })
187
+ }
188
+ }
189
+ return columns
190
+ }
191
+
192
+ /** One token of a `CREATE TABLE` text: a bare word, a quoted name, a string literal's value, or anything else. */
193
+ interface Token {
194
+ readonly kind: 'word' | 'name' | 'string' | 'other'
195
+ readonly text: string
196
+ readonly start: number
197
+ readonly end: number
198
+ }
199
+
200
+ const QUOTE_ENDS: ReadonlyMap<string, string> = new Map([
201
+ ["'", "'"],
202
+ ['"', '"'],
203
+ ['`', '`'],
204
+ ['[', ']'],
205
+ ])
206
+ const WORD = /[A-Za-z_\u0080-￿][A-Za-z0-9_$\u0080-￿]*/y
207
+ const NUMBER = /(?:[0-9]|\.[0-9])[0-9A-Za-z_.]*/y
208
+ const SPACE = /\s+/y
209
+
210
+ /** The tokens of a statement as SQLite reads it, comments and white space dropped. */
211
+ function tokenize(sql: string): Token[] {
212
+ const tokens: Token[] = []
213
+ let index = 0
214
+ const sticky = (pattern: RegExp): string | undefined => {
215
+ pattern.lastIndex = index
216
+ return pattern.exec(sql)?.[0]
217
+ }
218
+ while (index < sql.length) {
219
+ const start = index
220
+ const char = sql.charAt(index)
221
+ const space = sticky(SPACE)
222
+ if (space !== undefined) {
223
+ index += space.length
224
+ } else if (sql.startsWith('--', index)) {
225
+ const end = sql.indexOf('\n', index)
226
+ index = end === -1 ? sql.length : end + 1
227
+ } else if (sql.startsWith('/*', index)) {
228
+ const end = sql.indexOf('*/', index + 2)
229
+ index = end === -1 ? sql.length : end + 2
230
+ } else if (QUOTE_ENDS.has(char)) {
231
+ const close = QUOTE_ENDS.get(char) ?? char
232
+ let text = ''
233
+ index += 1
234
+ for (;;) {
235
+ const end = sql.indexOf(close, index)
236
+ if (end === -1) throw new Error('an unterminated quote in the schema; SQLite stored a statement it could not have parsed')
237
+ text += sql.slice(index, end)
238
+ index = end + 1
239
+ if (close === ']' || sql.charAt(index) !== close) break
240
+ text += close
241
+ index += 1
242
+ }
243
+ tokens.push({ kind: char === "'" ? 'string' : 'name', text, start, end: index })
244
+ } else {
245
+ const word = sticky(WORD)
246
+ const number = word === undefined ? sticky(NUMBER) : undefined
247
+ const text = word ?? number ?? char
248
+ index += text.length
249
+ // `X'00'` is a blob literal, not the column x.
250
+ const blob = word !== undefined && word.toUpperCase() === 'X' && sql.charAt(index) === "'"
251
+ tokens.push({ kind: word !== undefined && !blob ? 'word' : 'other', text, start, end: index })
252
+ }
253
+ }
254
+ return tokens
255
+ }
256
+
257
+ function isWord(token: Token | undefined, keyword: string): boolean {
258
+ return token?.kind === 'word' && token.text.toUpperCase() === keyword
259
+ }
260
+
261
+ function isPunctuation(token: Token | undefined, text: string): boolean {
262
+ return token?.kind === 'other' && token.text === text
263
+ }
264
+
265
+ /** The index of the parenthesis that closes the one at `open`, or -1. */
266
+ function closing(tokens: readonly Token[], open: number): number {
267
+ let depth = 0
268
+ for (let index = open; index < tokens.length; index++) {
269
+ if (isPunctuation(tokens[index], '(')) depth++
270
+ if (isPunctuation(tokens[index], ')') && --depth === 0) return index
271
+ }
272
+ return -1
273
+ }
274
+
275
+ /** The definitions of a `CREATE TABLE` body: each column and each table constraint, as its tokens. */
276
+ function definitions(tokens: readonly Token[]): Token[][] {
277
+ const open = tokens.findIndex((token) => isPunctuation(token, '('))
278
+ const close = open === -1 ? -1 : closing(tokens, open)
279
+ if (close === -1) return []
280
+ const parts: Token[][] = [[]]
281
+ let depth = 0
282
+ for (const token of tokens.slice(open + 1, close)) {
283
+ if (isPunctuation(token, '(')) depth++
284
+ if (isPunctuation(token, ')')) depth--
285
+ if (depth === 0 && isPunctuation(token, ',')) {
286
+ parts.push([])
287
+ } else {
288
+ parts.at(-1)?.push(token)
289
+ }
290
+ }
291
+ return parts.filter((part) => part.length > 0)
292
+ }
293
+
294
+ const TABLE_CONSTRAINTS: ReadonlySet<string> = new Set(['CONSTRAINT', 'CHECK', 'PRIMARY', 'UNIQUE', 'FOREIGN'])
295
+
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[] {
333
+ let tokens = expression
334
+ while (isPunctuation(tokens[0], '(') && closing(tokens, 0) === tokens.length - 1) {
335
+ tokens = tokens.slice(1, -1)
336
+ }
337
+ // The subject may be parenthesized too: `(("status")) IN (…)`.
338
+ let depth = 0
339
+ while (isPunctuation(tokens[depth], '(')) depth++
340
+ const subject = tokens[depth]
341
+ for (let index = 1; index <= depth; index++) {
342
+ if (!isPunctuation(tokens[depth + index], ')')) return []
343
+ }
344
+ const list = depth * 2 + 1
345
+ const named = subject?.kind === 'word' || subject?.kind === 'name'
346
+ if (!named || subject.text.toLowerCase() !== column.toLowerCase() || !isWord(tokens[list], 'IN') || !isPunctuation(tokens[list + 1], '(')) return []
347
+ if (!isPunctuation(tokens.at(-1), ')') || closing(tokens, list + 1) !== tokens.length - 1) return []
348
+ const items = tokens.slice(list + 2, -1)
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
359
+ }
360
+ return []
361
+ }
362
+
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. */
364
+ function tableChecks(table: string, sql: string, columns: readonly string[]): CheckConstraint[] {
365
+ const byName = new Map(columns.map((name) => [name.toLowerCase(), name]))
366
+ const checks: CheckConstraint[] = []
367
+ for (const definition of definitions(tokenize(sql))) {
368
+ // A column definition starts with its name, which no CHECK is.
369
+ const first = definition[0]
370
+ const start = first?.kind === 'word' && TABLE_CONSTRAINTS.has(first.text.toUpperCase()) ? 0 : 1
371
+ let depth = 0
372
+ for (let index = start; index < definition.length; index++) {
373
+ const token = definition[index]
374
+ if (isPunctuation(token, '(')) depth++
375
+ if (isPunctuation(token, ')')) depth--
376
+ if (depth !== 0 || !isWord(token, 'CHECK') || !isPunctuation(definition[index + 1], '(')) continue
377
+ const close = closing(definition, index + 1)
378
+ if (close === -1) break
379
+ const expression = definition.slice(index + 2, close)
380
+ const named = new Set<string>()
381
+ expression.forEach((part, at) => {
382
+ const column = part.kind === 'name' || (part.kind === 'word' && !isPunctuation(expression[at + 1], '('))
383
+ ? byName.get(part.text.toLowerCase())
384
+ : undefined
385
+ if (column !== undefined) named.add(column)
386
+ })
387
+ const constraint = isWord(definition[index - 2], 'CONSTRAINT') ? definition[index - 1]?.text : undefined
388
+ const [only] = named
389
+ const from = expression[0]?.start ?? 0
390
+ const to = expression.at(-1)?.end ?? 0
391
+ checks.push({
392
+ // SQLite names an unnamed CHECK by its expression's text in the error it fails with.
393
+ name: constraint ?? sql.slice(from, to),
394
+ table,
395
+ columns: [...named],
396
+ values: named.size === 1 && only !== undefined ? listedValues(expression, only) : [],
397
+ literals: expressionLiterals(expression),
398
+ })
399
+ index = close
400
+ }
401
+ }
402
+ return checks
403
+ }
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
+
449
+ const foreignKeyRows = z.array(z.object({ id: z.number(), seq: z.number(), table: z.string(), from: z.string(), to: z.string().nullable() }))
450
+ const keyRows = z.array(z.object({ name: z.string(), pk: z.number() }))
451
+ const rowidRows = z.array(z.object({ id: z.number() }))
452
+
453
+ /** A foreign key of `table` and the columns of the table it references, in order. */
454
+ interface Referrer {
455
+ readonly table: string
456
+ readonly columns: readonly string[]
457
+ readonly refs: readonly string[]
458
+ }
459
+
460
+ /** Every foreign key of the database's tables, by the table it references; a key that names no columns references its primary key. */
461
+ function readReferrers(exec: Exec): ReadonlyMap<string, readonly Referrer[]> {
462
+ const tables = tableRows.parse(exec(`SELECT name, wr FROM pragma_table_list WHERE schema = 'main' AND type = 'table' ORDER BY name`))
463
+ .filter((table) => !table.name.startsWith('sqlite_'))
464
+ const referrers = new Map<string, Referrer[]>()
465
+ for (const table of tables) {
466
+ const keys = new Map<number, { table: string; columns: string[]; refs: (string | null)[] }>()
467
+ for (
468
+ const row of foreignKeyRows.parse(exec('SELECT id, seq, "table", "from", "to" FROM pragma_foreign_key_list(?) ORDER BY id, seq', table.name))
469
+ ) {
470
+ const key = keys.get(row.id) ?? { table: row.table, columns: [], refs: [] }
471
+ key.columns.push(row.from)
472
+ key.refs.push(row.to)
473
+ keys.set(row.id, key)
474
+ }
475
+ for (const key of keys.values()) {
476
+ const primary = keyRows.parse(exec('SELECT name, pk FROM pragma_table_info(?) WHERE pk > 0 ORDER BY pk', key.table)).map((column) => column.name)
477
+ const refs = key.refs.map((ref, index) => ref ?? primary[index] ?? '')
478
+ referrers.set(key.table, [...(referrers.get(key.table) ?? []), { table: table.name, columns: key.columns, refs }])
479
+ }
480
+ }
481
+ return referrers
482
+ }
483
+
484
+ /** Every CHECK constraint of the database's tables. */
485
+ function readChecks(exec: Exec, columns: readonly SeedColumn[]): CheckConstraint[] {
486
+ const tables = schemaRows.parse(exec(`SELECT name, sql FROM sqlite_schema WHERE type = 'table' AND sql IS NOT NULL ORDER BY name`))
487
+ return tables
488
+ .filter((table) => !table.name.startsWith('sqlite_'))
489
+ .flatMap((table) => tableChecks(table.name, table.sql, columns.filter((column) => column.table === table.name).map((column) => column.name)))
490
+ }
491
+
492
+ /** A value the seeding writes, as a Durable Object binds it: a boolean 0 or 1, a `Date` its ISO text. */
493
+ function binding(value: SampleValue): SqliteValue {
494
+ if (typeof value === 'boolean') return value ? 1 : 0
495
+ if (value instanceof Date) {
496
+ if (Number.isNaN(value.getTime())) throw new SeedLimitError('the isolation fixture cannot write an invalid Date')
497
+ return value.toISOString()
498
+ }
499
+ if (typeof value === 'bigint') {
500
+ const number = Number(value)
501
+ if (!Number.isSafeInteger(number)) throw new SeedLimitError('the isolation fixture cannot write a bigint outside the safe integer range on SQLite')
502
+ return number
503
+ }
504
+ return value
505
+ }
506
+
507
+ /** A CHECK or foreign key violation of a seeded row, as the generator limit it is; `undefined` for any other failure. */
508
+ function seedLimit(error: unknown, table: string): SeedLimitError | undefined {
509
+ const message = error instanceof Error ? error.message : ''
510
+ const check = /^CHECK constraint failed: (.*)$/s.exec(message)
511
+ if (check !== null) return checkLimit(check[1] ?? 'unnamed', table)
512
+ // SQLite names no foreign key in its error.
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
+ }
522
+ return undefined
523
+ }
524
+
525
+ function quoted(identifier: string): string {
526
+ return `"${identifier.replaceAll('"', '""')}"`
527
+ }
528
+
529
+ function migrationsDirectory(migrations: string | URL): string {
530
+ return migrations instanceof URL ? fileURLToPath(migrations) : migrations
531
+ }
532
+
533
+ /** The application's migrations: every `.sql` file of the directory by name, as `fabrika app build` bundles them for the object. */
534
+ function applicationMigrations(directory: string): SqliteMigrationBundle['migrations'] {
535
+ if (!existsSync(directory)) {
536
+ throw new Error(`No migrations directory at ${directory}; create the first migration with fabrika db new <slug>`)
537
+ }
538
+ const names = readdirSync(directory).filter((name) => name.endsWith('.sql')).sort((left, right) => left < right ? -1 : left > right ? 1 : 0)
539
+ return names.map((name) => ({ name, sql: readFileSync(join(directory, name), 'utf8') }))
540
+ }
541
+
542
+ /**
543
+ * A fresh in-memory database with the framework's and the application's migrations applied by the runner a Durable
544
+ * Object boots with (`@fabrika/db/sqlite-migrate`), opened with its engine (`@fabrika/db/sqlite`). Never `null`: it
545
+ * needs no backend, so it never skips; its type is still assignable to `@fabrika/db/testing`'s, so a test
546
+ * that checks for `null` compiles against both kits.
547
+ */
548
+ export async function testDatabase(options: TestDatabaseOptions): Promise<TestDatabase> {
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 }> {
557
+ const migrations = applicationMigrations(migrationsDirectory(options.migrations))
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())
565
+ }
566
+ const storage = bunSqliteStorage(sqlite)
567
+ const exec: Exec = (query, ...bindings) => storage.sql.exec(query, ...bindings).toArray()
568
+ const columns = readColumns(exec)
569
+ const withoutRowid = new Set(
570
+ tableRows.parse(exec(`SELECT name, wr FROM pragma_table_list WHERE schema = 'main' AND type = 'table' AND wr = 1`)).map((table) => table.name),
571
+ )
572
+ const referrers = readReferrers(exec)
573
+ /** A removal finds a table's rows again by their rowid; a table without one is a limit of the fixture. */
574
+ const requireRowid = (table: string): void => {
575
+ if (withoutRowid.has(table)) {
576
+ throw new SeedLimitError(`the isolation fixture cannot remove the rows of ${table}, a WITHOUT ROWID table; declare it with a rowid`)
577
+ }
578
+ }
579
+ const backend: SeedingBackend = {
580
+ columns,
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),
584
+ async insert(table, row) {
585
+ const names = [...row.keys()]
586
+ const target = quoted(table)
587
+ const statement = names.length === 0
588
+ ? `INSERT INTO ${target} DEFAULT VALUES RETURNING *`
589
+ : `INSERT INTO ${target} (${names.map(quoted).join(', ')}) VALUES (${names.map(() => '?').join(', ')}) RETURNING *`
590
+ try {
591
+ return exec(statement, ...names.map((name) => binding(seedBinding(columns, table, name, row.get(name) ?? null))))[0] ?? {}
592
+ } catch (error) {
593
+ throw seedLimit(error, table) ?? error
594
+ }
595
+ },
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]
603
+ },
604
+ async insertFile(file) {
605
+ exec(
606
+ `INSERT INTO ${quoted(FILES_TABLE)} (id, kind, status, object_key, size, sha256, content_type, name, created_at, object_version)
607
+ VALUES (?, ?, 'live', ?, 0, ?, 'application/octet-stream', 'seeded', strftime('${SQLITE_NOW_FORMAT}', 'now'), ?)`,
608
+ file.id,
609
+ file.kind,
610
+ file.objectKey,
611
+ file.sha256,
612
+ file.objectVersion,
613
+ )
614
+ },
615
+ async remove(rows: readonly InsertedRow[]) {
616
+ // One object, one writer: nothing writes between finding the rows and deleting them. The foreign keys are checked
617
+ // at the commit, so rows that refer to each other go together.
618
+ storage.transactionSync(() => {
619
+ exec('PRAGMA defer_foreign_keys = ON')
620
+ const found = new Map<string, Set<number>>()
621
+ let count = 0
622
+ let level = new Map<string, number[]>()
623
+ const add = (table: string, rowid: number): void => {
624
+ let rowids = found.get(table)
625
+ if (rowids === undefined) {
626
+ rowids = new Set()
627
+ found.set(table, rowids)
628
+ }
629
+ if (rowids.has(rowid)) return
630
+ if (++count > MAX_REMOVED_ROWS) throw removalLimit()
631
+ rowids.add(rowid)
632
+ level.set(table, [...(level.get(table) ?? []), rowid])
633
+ }
634
+ for (const row of rows) {
635
+ const where = [...row.match.keys()].map((column) => `${quoted(column)} = ?`).join(' AND ')
636
+ requireRowid(row.table)
637
+ const located = rowidRows.parse(exec(`SELECT rowid AS id FROM ${quoted(row.table)} WHERE ${where}`, ...[...row.match.values()].map(binding)))
638
+ for (const { id } of located) add(row.table, id)
639
+ }
640
+ while (level.size > 0) {
641
+ const current = level
642
+ level = new Map()
643
+ for (const [table, rowids] of current) {
644
+ for (const key of referrers.get(table) ?? []) {
645
+ requireRowid(key.table)
646
+ const on = key.columns.map((column, position) => `r.${quoted(column)} = t.${quoted(key.refs[position] ?? '')}`).join(' AND ')
647
+ const referring = rowidRows.parse(
648
+ exec(
649
+ `SELECT r.rowid AS id FROM ${quoted(key.table)} r JOIN ${quoted(table)} t ON ${on} WHERE t.rowid IN (SELECT value FROM json_each(?))`,
650
+ JSON.stringify(rowids),
651
+ ),
652
+ )
653
+ for (const referrer of referring) add(key.table, referrer.id)
654
+ }
655
+ }
656
+ }
657
+ for (const [table, rowids] of found) {
658
+ exec(`DELETE FROM ${quoted(table)} WHERE rowid IN (SELECT value FROM json_each(?))`, JSON.stringify([...rowids]))
659
+ }
660
+ })
661
+ },
662
+ }
663
+ const database = openSqlite(storage)
664
+ return {
665
+ database: {
666
+ ...testSeeding(backend),
667
+ database,
668
+ schema: 'main',
669
+ async close() {
670
+ await database.close()
671
+ sqlite.close()
672
+ },
673
+ },
674
+ sqlite,
675
+ migrations: key,
676
+ }
677
+ }
678
+
679
+ /**
680
+ * The untyped handle over one table of the data layer `scoped(tables)` created; it reaches the database once `boot`
681
+ * has bound that layer. Every runtime check of a store applies: kind, dimension, action and the request's authority.
682
+ */
683
+ export function tableProbe(layer: unknown, table: string): TableProbe {
684
+ return probeTable(MODULE, layer, table)
685
+ }