@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.60

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 (73) 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 +59 -11
  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 +55 -9
  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 +369 -147
  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-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1933 -168
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +8 -1
  35. package/src/testing-shared.ts +758 -140
  36. package/src/testing-sqlite.ts +212 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +159 -27
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +31 -9
  47. package/types/src/errors.d.ts +7 -4
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +18 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +4 -0
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +165 -73
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +347 -23
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +4 -1
  70. package/types/src/testing-shared.d.ts +112 -23
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -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())) {