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

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
package/src/sqlite-bun.ts CHANGED
@@ -13,6 +13,44 @@ export interface BunSqliteStorage extends SqliteStorage {
13
13
  /** workerd's authorizer refuses these in `sql.exec`: a transaction runs through `transaction` or `transactionSync`. */
14
14
  const TRANSACTION_CONTROL = /(?:^|;)(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:begin|commit|end|rollback|savepoint|release)\b/i
15
15
 
16
+ /** workerd's `SQLITE_LIMIT_COLUMN` and `SQLITE_LIMIT_VARIABLE_NUMBER`, both 100. */
17
+ const WORKERD_MAX_COLUMNS = 100
18
+
19
+ /** What may follow a text's last statement: whitespace, comments and semicolons. */
20
+ const NO_STATEMENT = /^(?:\s|;|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*$/
21
+
22
+ /**
23
+ * Runs each statement of `query` in turn and answers the rows of the last one, as a Durable Object's `sql.exec` does.
24
+ * bun:sqlite's `prepare` compiles only the first statement of a text, and its column count cannot tell a migration from a
25
+ * read (`ALTER TABLE … ADD COLUMN … CHECK (…)` reports one column), so the text is split at the end of each compiled
26
+ * statement. `bindings` belong to a text of one statement. Refuses what workerd's SQLite refuses: more than 100 result
27
+ * columns or parameters in one statement.
28
+ */
29
+ export function execStatements(database: Database, query: string, bindings: readonly SQLQueryBindings[] = []): Record<string, unknown>[] {
30
+ let text = query
31
+ for (;;) {
32
+ const statement = database.prepare<Record<string, unknown>, SQLQueryBindings[]>(text)
33
+ try {
34
+ if (statement.columnNames.length > WORKERD_MAX_COLUMNS) {
35
+ throw new Error('too many columns in result set: SQLITE_ERROR')
36
+ }
37
+ if (statement.paramsCount > WORKERD_MAX_COLUMNS) {
38
+ throw new Error('too many SQL variables: SQLITE_ERROR')
39
+ }
40
+ // The compiled statement's own text, with no parameter to expand: the rest of `text` follows it verbatim.
41
+ const compiled = statement.toString()
42
+ const rest = bindings.length === 0 && text.startsWith(compiled) ? text.slice(compiled.length) : ''
43
+ const rows = statement.all(...bindings)
44
+ if (NO_STATEMENT.test(rest)) {
45
+ return rows
46
+ }
47
+ text = rest
48
+ } finally {
49
+ statement.finalize()
50
+ }
51
+ }
52
+ }
53
+
16
54
  function bunBinding(value: SqliteValue): SQLQueryBindings {
17
55
  return value instanceof ArrayBuffer ? new Uint8Array(value) : value
18
56
  }
@@ -41,8 +79,8 @@ interface OpenTransaction {
41
79
  /**
42
80
  * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
43
81
  * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
44
- * siblings wait for each other. A statement outside one runs at once. A text of several statements runs whole when its
45
- * first statement answers no rows, as a migration's does; otherwise only its first statement runs.
82
+ * siblings wait for each other. A statement outside one runs at once. A text of several statements runs each of them and
83
+ * answers the rows of the last (`execStatements`).
46
84
  */
47
85
  export function bunSqliteStorage(database: Database = new Database(':memory:')): BunSqliteStorage {
48
86
  database.run('PRAGMA foreign_keys = ON')
@@ -54,19 +92,8 @@ export function bunSqliteStorage(database: Database = new Database(':memory:')):
54
92
  if (TRANSACTION_CONTROL.test(query)) {
55
93
  throw new Error('sql.exec runs no transaction statement: use storage.transaction() or storage.transactionSync()')
56
94
  }
57
- const values = bindings.map(bunBinding)
58
95
  const before = totalChanges()
59
- const statement = database.prepare<Record<string, unknown>, SQLQueryBindings[]>(query)
60
- let rows: Record<string, SqliteValue>[] = []
61
- try {
62
- if (statement.columnNames.length > 0) {
63
- rows = statement.all(...values).map(storageRow)
64
- } else {
65
- database.run(query, values)
66
- }
67
- } finally {
68
- statement.finalize()
69
- }
96
+ const rows = execStatements(database, query, bindings.map(bunBinding)).map(storageRow)
70
97
  const rowsWritten = totalChanges() - before
71
98
  return { toArray: () => rows, rowsWritten }
72
99
  }
@@ -2,7 +2,8 @@
2
2
  // database when its Durable Object boots (ADR-0065), in a ledger in the same database. The identity and the
3
3
  // checksum rule are the Postgres runner's (ADR-0017): `(bundle, name)`, and the SHA-256 of an applied file's text.
4
4
  // Every new object instance runs it, so a bundle whose files match the digest recorded for it is not read further.
5
- // Runs inside a Worker: no Bun import.
5
+ // `migrateSqlite` commits each file on its own; `planSqliteMigrations` applies every pending file of every bundle in one
6
+ // transaction, which the migrating boot of an application's object uses (ADR-0069 §3). Runs inside a Worker: no Bun import.
6
7
 
7
8
  /** What the runner needs of the database; a Durable Object's `storage.sql.exec` and `storage.transactionSync` fit it. */
8
9
  export interface SqliteMigrationTarget {
@@ -240,3 +241,103 @@ export async function migrateSqlite(
240
241
  }
241
242
  return { applied }
242
243
  }
244
+
245
+ /** One row of the ledger, as a migration record names it: the identity and the checksum, without the time it ran. */
246
+ export interface SqliteLedgerEntry {
247
+ readonly bundle: string
248
+ readonly name: string
249
+ readonly checksum: string
250
+ }
251
+
252
+ /** The ledger's rows in `(bundle, name)` order, and their digest. */
253
+ export interface SqliteLedger {
254
+ readonly entries: readonly SqliteLedgerEntry[]
255
+ readonly digest: string
256
+ }
257
+
258
+ /** The SHA-256 of the rows' `bundle name checksum` lines in `(bundle, name)` order: neither part holds a space or a newline. */
259
+ export async function sqliteLedgerDigest(entries: readonly SqliteLedgerEntry[]): Promise<string> {
260
+ const sorted = [...entries].sort((a, b) => compareNames(a.bundle, b.bundle) || compareNames(a.name, b.name))
261
+ return await checksumOf(sorted.map((entry) => `${entry.bundle} ${entry.name} ${entry.checksum}\n`).join(''))
262
+ }
263
+
264
+ /** The ledger as it stands; empty while the table does not exist. */
265
+ export async function readSqliteLedger(target: SqliteMigrationTarget): Promise<SqliteLedger> {
266
+ const entries = [...readLedger(target)].map(([identity, checksum]): SqliteLedgerEntry => {
267
+ const slash = identity.indexOf('/')
268
+ return { bundle: identity.slice(0, slash), name: identity.slice(slash + 1), checksum }
269
+ }).sort((a, b) => compareNames(a.bundle, b.bundle) || compareNames(a.name, b.name))
270
+ return { entries, digest: await sqliteLedgerDigest(entries) }
271
+ }
272
+
273
+ /** What the database needs to reach the bundles: nothing, a digest only, or pending files. */
274
+ export interface SqliteMigrationPlan {
275
+ /** The ledger the plan starts from; `null` when every bundle matched its digest and the ledger was not read. */
276
+ readonly ledger: SqliteLedger | null
277
+ /** The files to apply, the bundles in the order given and each bundle's files in name order. */
278
+ readonly pending: readonly SqliteLedgerEntry[]
279
+ /** Whether `apply` writes anything: a pending file, or a bundle digest that is out of date. */
280
+ readonly writes: boolean
281
+ /**
282
+ * Applies every pending file with its ledger row, and records every out-of-date bundle digest, in one transaction
283
+ * that ends with `PRAGMA foreign_key_check`: a failing file or a row the check returns rolls the whole set back.
284
+ * Answers the identities it applied.
285
+ */
286
+ apply(): readonly string[]
287
+ }
288
+
289
+ /** Plans the bundles against the ledger without writing; refuses what `migrateSqlite` refuses, before anything runs. */
290
+ export async function planSqliteMigrations(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<SqliteMigrationPlan> {
291
+ const planned = await plan(bundles)
292
+ const digests = readDigests(target, planned)
293
+ const stale = planned.filter((bundle) => digests.get(bundle.bundle) !== bundle.digest)
294
+ if (stale.length === 0) {
295
+ return { ledger: null, pending: [], writes: false, apply: () => [] }
296
+ }
297
+ const ledger = await readSqliteLedger(target)
298
+ const recorded = new Map(ledger.entries.map((entry) => [`${entry.bundle}/${entry.name}`, entry.checksum]))
299
+ verify(planned, recorded)
300
+ const pending = stale.flatMap((bundle) => bundle.migrations.filter((migration) => !recorded.has(`${migration.bundle}/${migration.name}`)))
301
+ return {
302
+ ledger,
303
+ pending: pending.map(({ bundle, name, checksum }) => ({ bundle, name, checksum })),
304
+ writes: true,
305
+ apply: () => applyAtomically(target, stale, pending),
306
+ }
307
+ }
308
+
309
+ class ForeignKeyViolation extends Error {
310
+ override readonly name = 'ForeignKeyViolation'
311
+ }
312
+
313
+ function applyAtomically(target: SqliteMigrationTarget, stale: readonly PlannedBundle[], pending: readonly PlannedMigration[]): readonly string[] {
314
+ const appliedAt = new Date().toISOString()
315
+ try {
316
+ target.transactionSync(() => {
317
+ target.exec(LEDGER_DDL)
318
+ for (const migration of pending) {
319
+ target.exec(migration.sql)
320
+ target.exec(
321
+ `INSERT INTO ${LEDGER} (bundle, name, checksum, applied_at) VALUES (?, ?, ?, ?)`,
322
+ migration.bundle,
323
+ migration.name,
324
+ migration.checksum,
325
+ appliedAt,
326
+ )
327
+ }
328
+ for (const bundle of stale) recordDigest(target, bundle)
329
+ if (target.exec('PRAGMA foreign_key_check').toArray().length > 0) {
330
+ throw new ForeignKeyViolation('a row violates a foreign key')
331
+ }
332
+ })
333
+ } catch (error) {
334
+ const files = pending.map((migration) => `${migration.bundle}/${migration.name}`).join(', ')
335
+ throw new SqliteMigrationError(
336
+ error instanceof ForeignKeyViolation
337
+ ? `SQLite migrations ${files} left a row that violates a foreign key; none of them was applied`
338
+ : `SQLite migrations ${files} failed; none of them was applied`,
339
+ { cause: error },
340
+ )
341
+ }
342
+ return pending.map((migration) => `${migration.bundle}/${migration.name}`)
343
+ }
package/src/sqlite.ts CHANGED
@@ -10,6 +10,7 @@ import {
10
10
  type DialectAdapter,
11
11
  type Driver,
12
12
  Kysely,
13
+ type OperationNode,
13
14
  OperatorNode,
14
15
  type QueryResult,
15
16
  type SelectModifierNode,
@@ -17,6 +18,8 @@ import {
17
18
  SqliteAdapter,
18
19
  SqliteIntrospector,
19
20
  SqliteQueryCompiler,
21
+ ValueListNode,
22
+ ValueNode,
20
23
  } from 'kysely'
21
24
  import { Database, freezePrototypeChain, type LooseDB, type TransactionRunner } from './database'
22
25
  import { DatabaseError, QueryRefusedError } from './errors'
@@ -40,6 +43,14 @@ export interface SqliteStorage {
40
43
  transactionSync<T>(closure: () => T): T
41
44
  }
42
45
 
46
+ // Captured at load, as the compiler's prototype is frozen at load: a later patch would change what a list binds.
47
+ const stringify = JSON.stringify
48
+ const test = RegExp.prototype.test
49
+ const apply = Reflect.apply
50
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/
51
+
52
+ const MEMBERSHIP_OPERATORS: ReadonlySet<string> = new Set(['in', 'not in'])
53
+
43
54
  const LIKE_OPERATORS: ReadonlyMap<string, string> = new Map([
44
55
  ['like', 'like'],
45
56
  ['ilike', 'like'],
@@ -64,7 +75,17 @@ class SqliteCompiler extends SqliteQueryCompiler {
64
75
  }
65
76
 
66
77
  protected override visitBinaryOperation(node: BinaryOperationNode): void {
67
- const pattern = OperatorNode.is(node.operator) ? LIKE_OPERATORS.get(node.operator.operator) : undefined
78
+ const operator = OperatorNode.is(node.operator) ? node.operator.operator : undefined
79
+ const texts = operator !== undefined && MEMBERSHIP_OPERATORS.has(operator) ? jsonTexts(node.rightOperand) : undefined
80
+ if (texts !== undefined) {
81
+ // workerd binds at most 100 parameters a statement, and a Within alone carries up to MAX_WITHIN_VALUES.
82
+ this.visitNode(node.leftOperand)
83
+ this.append(` ${operator} (select value from json_each(`)
84
+ this.appendValue(texts)
85
+ this.append('))')
86
+ return
87
+ }
88
+ const pattern = operator === undefined ? undefined : LIKE_OPERATORS.get(operator)
68
89
  if (pattern === undefined) {
69
90
  super.visitBinaryOperation(node)
70
91
  return
@@ -81,6 +102,30 @@ class SqliteCompiler extends SqliteQueryCompiler {
81
102
  }
82
103
  }
83
104
 
105
+ /**
106
+ * An `in` list of bound texts as one JSON array text, or undefined when it holds anything else. Each text is serialized
107
+ * on its own (a string has no `toJSON` to consult). A text with a lone surrogate keeps its own parameter: each driver
108
+ * encodes one its own way, and json_each would not decode it to the same bytes.
109
+ */
110
+ function jsonTexts(node: OperationNode): string | undefined {
111
+ if (!ValueListNode.is(node)) {
112
+ return undefined
113
+ }
114
+ const values = node.values
115
+ let json = '['
116
+ for (let index = 0; index < values.length; index++) {
117
+ const value = values[index]
118
+ if (value === undefined || !ValueNode.is(value) || value.immediate === true || typeof value.value !== 'string') {
119
+ return undefined
120
+ }
121
+ if (apply(test, LONE_SURROGATE, [value.value])) {
122
+ return undefined
123
+ }
124
+ json += (index === 0 ? '' : ',') + stringify(value.value)
125
+ }
126
+ return `${json}]`
127
+ }
128
+
84
129
  function sqliteParameter(parameter: unknown): unknown {
85
130
  if (parameter instanceof Date) {
86
131
  if (Number.isNaN(parameter.getTime())) {