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

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 (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +146 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +149 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +21 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
@@ -0,0 +1,149 @@
1
+ // A `bun:sqlite` database shaped like a Durable Object's storage, for the tests and the SQLite test kit. Not a subpath:
2
+ // a Worker never loads it.
3
+
4
+ import { Database, type SQLQueryBindings } from 'bun:sqlite'
5
+ import { AsyncLocalStorage } from 'node:async_hooks'
6
+ import type { SqliteCursor, SqliteStorage, SqliteValue } from './sqlite'
7
+
8
+ export interface BunSqliteStorage extends SqliteStorage {
9
+ /** Runs `fn` in one transaction of its own, as a Durable Object's `storage.transactionSync` does. */
10
+ transactionSync<T>(fn: () => T): T
11
+ }
12
+
13
+ /** workerd's authorizer refuses these in `sql.exec`: a transaction runs through `transaction` or `transactionSync`. */
14
+ const TRANSACTION_CONTROL = /(?:^|;)(?:\s|--[^\n]*(?:\n|$)|\/\*[\s\S]*?\*\/)*(?:begin|commit|end|rollback|savepoint|release)\b/i
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
+
54
+ function bunBinding(value: SqliteValue): SQLQueryBindings {
55
+ return value instanceof ArrayBuffer ? new Uint8Array(value) : value
56
+ }
57
+
58
+ /** A column value as workerd answers it: a BLOB is an `ArrayBuffer`. */
59
+ function storageValue(value: unknown): SqliteValue {
60
+ if (value === null || typeof value === 'string' || typeof value === 'number') {
61
+ return value
62
+ }
63
+ if (value instanceof Uint8Array) {
64
+ return value.slice().buffer
65
+ }
66
+ throw new Error('bun:sqlite answered a value a Durable Object never does')
67
+ }
68
+
69
+ function storageRow(row: Record<string, unknown>): Record<string, SqliteValue> {
70
+ return Object.fromEntries(Object.entries(row).map(([name, value]) => [name, storageValue(value)]))
71
+ }
72
+
73
+ /** The transaction a `transaction` callback runs in: its savepoint depth, and the queue its own nested ones wait in. */
74
+ interface OpenTransaction {
75
+ readonly depth: number
76
+ queue: Promise<void>
77
+ }
78
+
79
+ /**
80
+ * `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
81
+ * `transaction` runs at a time; one started inside a callback nests in a savepoint, as workerd nests it, and its
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`).
84
+ */
85
+ export function bunSqliteStorage(database: Database = new Database(':memory:')): BunSqliteStorage {
86
+ database.run('PRAGMA foreign_keys = ON')
87
+ const totalChanges = (): number => database.query<{ readonly changes: number }, []>('select total_changes() as changes').get()?.changes ?? 0
88
+ const root: OpenTransaction = { depth: 0, queue: Promise.resolve() }
89
+ const open = new AsyncLocalStorage<OpenTransaction>()
90
+
91
+ function exec(query: string, ...bindings: SqliteValue[]): SqliteCursor {
92
+ if (TRANSACTION_CONTROL.test(query)) {
93
+ throw new Error('sql.exec runs no transaction statement: use storage.transaction() or storage.transactionSync()')
94
+ }
95
+ const before = totalChanges()
96
+ const rows = execStatements(database, query, bindings.map(bunBinding)).map(storageRow)
97
+ const rowsWritten = totalChanges() - before
98
+ return { toArray: () => rows, rowsWritten }
99
+ }
100
+
101
+ return {
102
+ sql: { exec },
103
+ async transaction<T>(closure: () => Promise<T>): Promise<T> {
104
+ const parent = open.getStore() ?? root
105
+ const previous = parent.queue
106
+ const done = Promise.withResolvers<void>()
107
+ parent.queue = previous.then(() => done.promise)
108
+ await previous
109
+ const depth = parent.depth + 1
110
+ const savepoint = `_test_savepoint_${depth}`
111
+ try {
112
+ database.run(depth === 1 ? 'BEGIN' : `SAVEPOINT ${savepoint}`)
113
+ try {
114
+ const result = await open.run({ depth, queue: Promise.resolve() }, closure)
115
+ database.run(depth === 1 ? 'COMMIT' : `RELEASE ${savepoint}`)
116
+ return result
117
+ } catch (error) {
118
+ if (depth === 1 && database.inTransaction) {
119
+ database.run('ROLLBACK')
120
+ } else if (depth > 1) {
121
+ database.run(`ROLLBACK TO ${savepoint}`)
122
+ database.run(`RELEASE ${savepoint}`)
123
+ }
124
+ throw error
125
+ }
126
+ } finally {
127
+ done.resolve()
128
+ }
129
+ },
130
+ transactionSync<T>(fn: () => T): T {
131
+ // Inside an open transaction workerd nests it in a savepoint too.
132
+ const nested = database.inTransaction
133
+ database.run(nested ? 'SAVEPOINT _test_sync_savepoint' : 'BEGIN')
134
+ try {
135
+ const result = fn()
136
+ database.run(nested ? 'RELEASE _test_sync_savepoint' : 'COMMIT')
137
+ return result
138
+ } catch (error) {
139
+ if (nested) {
140
+ database.run('ROLLBACK TO _test_sync_savepoint')
141
+ database.run('RELEASE _test_sync_savepoint')
142
+ } else if (database.inTransaction) {
143
+ database.run('ROLLBACK')
144
+ }
145
+ throw error
146
+ }
147
+ },
148
+ }
149
+ }
@@ -0,0 +1,242 @@
1
+ // @fabrika/db/sqlite-migrate — applies the framework's and the application's migrations to an application's SQLite
2
+ // database when its Durable Object boots (ADR-0065), in a ledger in the same database. The identity and the
3
+ // checksum rule are the Postgres runner's (ADR-0017): `(bundle, name)`, and the SHA-256 of an applied file's text.
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.
6
+
7
+ /** What the runner needs of the database; a Durable Object's `storage.sql.exec` and `storage.transactionSync` fit it. */
8
+ export interface SqliteMigrationTarget {
9
+ /** Runs `query`, which may hold several statements, and answers the rows of the last one. */
10
+ exec(query: string, ...bindings: (string | number | null)[]): { toArray(): Record<string, unknown>[] }
11
+ /** Runs `fn` in one transaction: commits when it returns, rolls back when it throws. */
12
+ transactionSync<T>(fn: () => T): T
13
+ }
14
+
15
+ export interface SqliteMigrationBundle {
16
+ readonly bundle: string
17
+ readonly migrations: readonly { readonly name: string; readonly sql: string }[]
18
+ }
19
+
20
+ export class SqliteMigrationError extends Error {
21
+ override readonly name = 'SqliteMigrationError'
22
+ }
23
+
24
+ const LEDGER = 'fabrika_migrations'
25
+ const DIGESTS = 'fabrika_migration_bundles'
26
+ const BUNDLE_NAME = /^[a-z][a-z0-9-]*$/
27
+ const MIGRATION_NAME = /^[a-zA-Z0-9][a-zA-Z0-9._-]*\.sql$/
28
+
29
+ const LEDGER_DDL = `CREATE TABLE IF NOT EXISTS ${LEDGER} (
30
+ bundle TEXT NOT NULL,
31
+ name TEXT NOT NULL,
32
+ checksum TEXT NOT NULL,
33
+ applied_at TEXT NOT NULL,
34
+ PRIMARY KEY (bundle, name)
35
+ ) STRICT`
36
+
37
+ /** A bundle's digest: the SHA-256 of its ordered file names and checksums, written with the last of its files applied. */
38
+ const DIGESTS_DDL = `CREATE TABLE IF NOT EXISTS ${DIGESTS} (
39
+ bundle TEXT PRIMARY KEY,
40
+ digest TEXT NOT NULL
41
+ ) STRICT`
42
+
43
+ interface HashedMigration {
44
+ readonly name: string
45
+ readonly sql: string
46
+ readonly checksum: string
47
+ }
48
+
49
+ interface PlannedMigration extends HashedMigration {
50
+ readonly bundle: string
51
+ }
52
+
53
+ interface PlannedBundle {
54
+ readonly bundle: string
55
+ readonly digest: string
56
+ readonly migrations: readonly PlannedMigration[]
57
+ }
58
+
59
+ interface HashedFiles {
60
+ readonly digest: string
61
+ readonly migrations: readonly HashedMigration[]
62
+ }
63
+
64
+ /** The files an array held when it was hashed, and their hashes: reused while the array still holds the same files. */
65
+ interface HashedEntry {
66
+ readonly snapshot: readonly { readonly name: string; readonly sql: string }[]
67
+ readonly files: Promise<HashedFiles>
68
+ }
69
+
70
+ /** The migration arrays are module values, hashed once per isolate; an array mutated since is hashed again. */
71
+ const hashedFiles = new WeakMap<SqliteMigrationBundle['migrations'], HashedEntry>()
72
+
73
+ /** The SHA-256 hex of the file's UTF-8 text: the Postgres runner's `migrationChecksum`, so both ledgers agree. */
74
+ async function checksumOf(sql: string): Promise<string> {
75
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(sql))
76
+ return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, '0')).join('')
77
+ }
78
+
79
+ function compareNames(a: string, b: string): number {
80
+ return a < b ? -1 : a > b ? 1 : 0
81
+ }
82
+
83
+ /** Refuses a malformed bundle before anything is hashed or run. */
84
+ function check(bundles: readonly SqliteMigrationBundle[]): void {
85
+ const bundleNames = new Set<string>()
86
+ for (const bundle of bundles) {
87
+ if (!BUNDLE_NAME.test(bundle.bundle)) throw new SqliteMigrationError(`Invalid SQLite migration bundle name: ${bundle.bundle}`)
88
+ if (bundleNames.has(bundle.bundle)) throw new SqliteMigrationError(`Duplicate SQLite migration bundle ${bundle.bundle}`)
89
+ bundleNames.add(bundle.bundle)
90
+ const names = new Set<string>()
91
+ for (const migration of bundle.migrations) {
92
+ const identity = `${bundle.bundle}/${migration.name}`
93
+ if (!MIGRATION_NAME.test(migration.name)) throw new SqliteMigrationError(`Invalid SQLite migration filename: ${identity}`)
94
+ if (names.has(migration.name)) throw new SqliteMigrationError(`Duplicate SQLite migration ${identity}`)
95
+ if (migration.sql.trim() === '') throw new SqliteMigrationError(`SQLite migration ${identity} is empty`)
96
+ names.add(migration.name)
97
+ }
98
+ }
99
+ }
100
+
101
+ /** A bundle's files in name order with their checksums, and its digest: the SHA-256 of the ordered names and checksums. */
102
+ async function hash(files: SqliteMigrationBundle['migrations']): Promise<HashedFiles> {
103
+ const migrations: HashedMigration[] = []
104
+ for (const { name, sql } of [...files].sort((a, b) => compareNames(a.name, b.name))) {
105
+ migrations.push({ name, sql, checksum: await checksumOf(sql) })
106
+ }
107
+ // A filename holds no space or newline, so each line is unambiguous.
108
+ const digest = await checksumOf(migrations.map((migration) => `${migration.name} ${migration.checksum}\n`).join(''))
109
+ return { digest, migrations }
110
+ }
111
+
112
+ function holdsSnapshot(files: SqliteMigrationBundle['migrations'], snapshot: HashedEntry['snapshot']): boolean {
113
+ return files.length === snapshot.length && files.every((file, index) => file.name === snapshot[index]?.name && file.sql === snapshot[index]?.sql)
114
+ }
115
+
116
+ /** Each bundle's migrations in name order, the bundles in the order given; refuses a malformed bundle before any SQL runs. */
117
+ async function plan(bundles: readonly SqliteMigrationBundle[]): Promise<readonly PlannedBundle[]> {
118
+ check(bundles)
119
+ const planned: PlannedBundle[] = []
120
+ for (const bundle of bundles) {
121
+ let entry = hashedFiles.get(bundle.migrations)
122
+ if (entry === undefined || !holdsSnapshot(bundle.migrations, entry.snapshot)) {
123
+ entry = { snapshot: bundle.migrations.map(({ name, sql }) => ({ name, sql })), files: hash(bundle.migrations) }
124
+ hashedFiles.set(bundle.migrations, entry)
125
+ }
126
+ const { digest, migrations } = await entry.files
127
+ planned.push({ bundle: bundle.bundle, digest, migrations: migrations.map((migration) => ({ ...migration, bundle: bundle.bundle })) })
128
+ }
129
+ return planned
130
+ }
131
+
132
+ /** The digest recorded for each bundle that has one; empty while the table does not exist, as before its first run. */
133
+ function readDigests(target: SqliteMigrationTarget, planned: readonly PlannedBundle[]): Map<string, string> {
134
+ const recorded = new Map<string, string>()
135
+ if (target.exec(`SELECT 1 AS present FROM sqlite_schema WHERE type = 'table' AND name = ?`, DIGESTS).toArray().length === 0) return recorded
136
+ for (const { bundle } of planned) {
137
+ const [row] = target.exec(`SELECT digest FROM ${DIGESTS} WHERE bundle = ?`, bundle).toArray()
138
+ if (row === undefined) continue
139
+ const { digest } = row
140
+ if (typeof digest !== 'string') throw new SqliteMigrationError(`SQLite migration table ${DIGESTS} holds a malformed row`)
141
+ recorded.set(bundle, digest)
142
+ }
143
+ return recorded
144
+ }
145
+
146
+ function recordDigest(target: SqliteMigrationTarget, bundle: PlannedBundle): void {
147
+ target.exec(DIGESTS_DDL)
148
+ target.exec(
149
+ `INSERT INTO ${DIGESTS} (bundle, digest) VALUES (?, ?) ON CONFLICT (bundle) DO UPDATE SET digest = excluded.digest`,
150
+ bundle.bundle,
151
+ bundle.digest,
152
+ )
153
+ }
154
+
155
+ /** Recorded checksums by `bundle/name`; empty while the ledger does not exist, so a fresh database is checked first. */
156
+ function readLedger(target: SqliteMigrationTarget): Map<string, string> {
157
+ const present = target.exec(`SELECT 1 AS present FROM sqlite_schema WHERE type = 'table' AND name = ?`, LEDGER).toArray()
158
+ const applied = new Map<string, string>()
159
+ if (present.length === 0) return applied
160
+ for (const row of target.exec(`SELECT bundle, name, checksum FROM ${LEDGER}`).toArray()) {
161
+ const { bundle, name, checksum } = row
162
+ if (typeof bundle !== 'string' || typeof name !== 'string' || typeof checksum !== 'string') {
163
+ throw new SqliteMigrationError(`SQLite migration ledger ${LEDGER} holds a malformed row`)
164
+ }
165
+ applied.set(`${bundle}/${name}`, checksum)
166
+ }
167
+ return applied
168
+ }
169
+
170
+ /**
171
+ * Refuses, before anything is applied: an applied file whose text changed, and a new file that sorts before the last
172
+ * applied one of its bundle, which would run after the files it precedes. A ledger row without a file is the database
173
+ * ahead of the code after a rollback, which is tolerated, as on Postgres.
174
+ */
175
+ function verify(planned: readonly PlannedBundle[], applied: ReadonlyMap<string, string>): void {
176
+ for (const { migrations } of planned) {
177
+ let lastApplied: string | undefined
178
+ for (const migration of migrations) {
179
+ const identity = `${migration.bundle}/${migration.name}`
180
+ const recorded = applied.get(identity)
181
+ if (recorded === undefined) continue
182
+ if (recorded !== migration.checksum) {
183
+ throw new SqliteMigrationError(
184
+ `SQLite migration ${identity} changed after it was applied; an applied migration is immutable, so write the change as a new migration`,
185
+ )
186
+ }
187
+ lastApplied = migration.name
188
+ }
189
+ for (const migration of migrations) {
190
+ if (lastApplied === undefined || compareNames(migration.name, lastApplied) >= 0) break
191
+ if (!applied.has(`${migration.bundle}/${migration.name}`)) {
192
+ throw new SqliteMigrationError(
193
+ `SQLite migration ${migration.bundle}/${migration.name} sorts before ${migration.bundle}/${lastApplied}, which is already applied; rename it to sort after it`,
194
+ )
195
+ }
196
+ }
197
+ }
198
+ }
199
+
200
+ /**
201
+ * Applies every migration the ledger does not record, each in its own transaction together with its ledger row, so a
202
+ * failing one leaves nothing of itself and keeps the ones before it. A bundle's digest is recorded in the transaction
203
+ * of its last file, or alone when nothing of it was pending; while every bundle matches its digest, the ledger is not
204
+ * read. Answers the identities it applied.
205
+ */
206
+ export async function migrateSqlite(
207
+ target: SqliteMigrationTarget,
208
+ bundles: readonly SqliteMigrationBundle[],
209
+ ): Promise<{ readonly applied: readonly string[] }> {
210
+ const planned = await plan(bundles)
211
+ const digests = readDigests(target, planned)
212
+ if (planned.every((bundle) => digests.get(bundle.bundle) === bundle.digest)) return { applied: [] }
213
+ const recorded = readLedger(target)
214
+ verify(planned, recorded)
215
+ target.exec(LEDGER_DDL)
216
+ const applied: string[] = []
217
+ for (const bundle of planned) {
218
+ if (digests.get(bundle.bundle) === bundle.digest) continue
219
+ const pending = bundle.migrations.filter((migration) => !recorded.has(`${migration.bundle}/${migration.name}`))
220
+ if (pending.length === 0) target.transactionSync(() => recordDigest(target, bundle))
221
+ for (const [index, migration] of pending.entries()) {
222
+ const identity = `${migration.bundle}/${migration.name}`
223
+ try {
224
+ target.transactionSync(() => {
225
+ target.exec(migration.sql)
226
+ target.exec(
227
+ `INSERT INTO ${LEDGER} (bundle, name, checksum, applied_at) VALUES (?, ?, ?, ?)`,
228
+ migration.bundle,
229
+ migration.name,
230
+ migration.checksum,
231
+ new Date().toISOString(),
232
+ )
233
+ if (index === pending.length - 1) recordDigest(target, bundle)
234
+ })
235
+ } catch (error) {
236
+ throw new SqliteMigrationError(`SQLite migration ${identity} failed`, { cause: error })
237
+ }
238
+ applied.push(identity)
239
+ }
240
+ }
241
+ return { applied }
242
+ }
package/src/sqlite.ts ADDED
@@ -0,0 +1,224 @@
1
+ // @fabrika/db/sqlite — the data layer's engine over a Cloudflare Durable Object's SQLite (ADR-0065). Worker-safe: no
2
+ // Bun import. `sqlite-bun.ts` gives the tests a `bun:sqlite` database of the same shape.
3
+
4
+ import {
5
+ type BinaryOperationNode,
6
+ type CompiledQuery,
7
+ type DatabaseConnection,
8
+ type DatabaseIntrospector,
9
+ type Dialect,
10
+ type DialectAdapter,
11
+ type Driver,
12
+ Kysely,
13
+ OperatorNode,
14
+ type QueryResult,
15
+ type SelectModifierNode,
16
+ type SelectQueryNode,
17
+ SqliteAdapter,
18
+ SqliteIntrospector,
19
+ SqliteQueryCompiler,
20
+ } from 'kysely'
21
+ import { Database, freezePrototypeChain, type LooseDB, type TransactionRunner } from './database'
22
+ import { DatabaseError, QueryRefusedError } from './errors'
23
+
24
+ /** A value `sql.exec` binds and answers; a Durable Object's `SqlStorageValue`. */
25
+ export type SqliteValue = ArrayBuffer | string | number | null
26
+
27
+ export interface SqliteCursor {
28
+ toArray(): Record<string, SqliteValue>[]
29
+ readonly rowsWritten: number
30
+ }
31
+
32
+ /** What the engine needs of a Durable Object's `ctx.storage`; `DurableObjectStorage` is assignable to it. */
33
+ export interface SqliteStorage {
34
+ readonly sql: {
35
+ exec(query: string, ...bindings: SqliteValue[]): SqliteCursor
36
+ }
37
+ /** Commits when `closure` resolves, rolls back when it rejects; the object serves no other event meanwhile. */
38
+ transaction<T>(closure: () => Promise<T>): Promise<T>
39
+ /** Runs `closure` in one transaction of its own, nested in a savepoint inside an open one; rolls back when it throws. */
40
+ transactionSync<T>(closure: () => T): T
41
+ }
42
+
43
+ const LIKE_OPERATORS: ReadonlyMap<string, string> = new Map([
44
+ ['like', 'like'],
45
+ ['ilike', 'like'],
46
+ ['not like', 'not like'],
47
+ ['not ilike', 'not like'],
48
+ ])
49
+
50
+ /** The modifiers a Durable Object needs none of: while a transaction is open it serves no other event. */
51
+ const LOCK_MODIFIERS: ReadonlySet<string> = new Set(['ForUpdate', 'ForShare', 'ForKeyShare', 'ForNoKeyUpdate', 'NoWait', 'SkipLocked'])
52
+
53
+ function isLockModifier(modifier: SelectModifierNode): boolean {
54
+ return modifier.modifier !== undefined && LOCK_MODIFIERS.has(modifier.modifier)
55
+ }
56
+
57
+ /**
58
+ * SQLite's forms of what the layer binds and builds. LIKE takes `\` as its escape character only when told, so every
59
+ * pattern gets `escape '\'`, as Postgres has by default; `ilike` is `like`, case-insensitive for ASCII only.
60
+ */
61
+ class SqliteCompiler extends SqliteQueryCompiler {
62
+ protected override addParameter(parameter: unknown): void {
63
+ super.addParameter(sqliteParameter(parameter))
64
+ }
65
+
66
+ protected override visitBinaryOperation(node: BinaryOperationNode): void {
67
+ const pattern = OperatorNode.is(node.operator) ? LIKE_OPERATORS.get(node.operator.operator) : undefined
68
+ if (pattern === undefined) {
69
+ super.visitBinaryOperation(node)
70
+ return
71
+ }
72
+ this.visitNode(node.leftOperand)
73
+ this.append(` ${pattern} `)
74
+ this.visitNode(node.rightOperand)
75
+ this.append(" escape '\\'")
76
+ }
77
+
78
+ protected override visitSelectQuery(node: SelectQueryNode): void {
79
+ const modifiers = node.endModifiers?.filter((modifier) => !isLockModifier(modifier))
80
+ super.visitSelectQuery({ ...node, endModifiers: modifiers === undefined || modifiers.length === 0 ? undefined : modifiers })
81
+ }
82
+ }
83
+
84
+ function sqliteParameter(parameter: unknown): unknown {
85
+ if (parameter instanceof Date) {
86
+ if (Number.isNaN(parameter.getTime())) {
87
+ throw new QueryRefusedError('invalid_value', 'an invalid Date cannot be bound')
88
+ }
89
+ return parameter.toISOString()
90
+ }
91
+ if (typeof parameter === 'boolean') {
92
+ return parameter ? 1 : 0
93
+ }
94
+ if (typeof parameter === 'bigint') {
95
+ const value = Number(parameter)
96
+ if (!Number.isSafeInteger(value)) {
97
+ throw new QueryRefusedError('invalid_value', 'a bigint outside the safe integer range cannot be bound on SQLite')
98
+ }
99
+ return value
100
+ }
101
+ return parameter
102
+ }
103
+
104
+ const sqliteCompiler = new SqliteCompiler()
105
+ freezePrototypeChain(sqliteCompiler)
106
+
107
+ function binding(value: unknown): SqliteValue {
108
+ if (value === null || typeof value === 'string' || typeof value === 'number' || value instanceof ArrayBuffer) {
109
+ return value
110
+ }
111
+ throw new QueryRefusedError('invalid_value', 'a value SQLite cannot bind: string, number, ArrayBuffer or null')
112
+ }
113
+
114
+ /** The SQLSTATE of each constraint failure, by the start of the message workerd and bun:sqlite both give. */
115
+ const CONSTRAINT_STATES: readonly (readonly [string, string])[] = Object.freeze([
116
+ ['UNIQUE constraint failed', '23505'],
117
+ ['FOREIGN KEY constraint failed', '23503'],
118
+ ['CHECK constraint failed', '23514'],
119
+ ['NOT NULL constraint failed', '23502'],
120
+ ])
121
+
122
+ /** The driver's failure as a `DatabaseError`; its message can quote row values, so none of it is kept. */
123
+ function sqliteError(error: unknown): DatabaseError {
124
+ if (error instanceof DatabaseError) {
125
+ return error
126
+ }
127
+ const message = error instanceof Error ? error.message : ''
128
+ const match = CONSTRAINT_STATES.find(([prefix]) => message.startsWith(prefix))
129
+ return new DatabaseError(match === undefined ? null : match[1])
130
+ }
131
+
132
+ /** Postgres's SQLSTATE for a write in a `READ ONLY` transaction, which the backstop answers too. */
133
+ const READ_ONLY_TRANSACTION = '25006'
134
+
135
+ /**
136
+ * A read-only statement's rows, run in a `transactionSync` of its own that holds nothing across an await. A statement
137
+ * that wrote throws, which rolls back what it wrote: the backstop below the layer's refusal of a write node.
138
+ */
139
+ function readRows(storage: SqliteStorage, query: string, bindings: SqliteValue[]): Record<string, SqliteValue>[] {
140
+ return storage.transactionSync(() => {
141
+ const cursor = storage.sql.exec(query, ...bindings)
142
+ // workerd counts `rowsWritten` as the cursor is read: only a consumed cursor reports the whole statement.
143
+ const rows = cursor.toArray()
144
+ if (cursor.rowsWritten > 0) {
145
+ throw new DatabaseError(READ_ONLY_TRANSACTION)
146
+ }
147
+ return rows
148
+ })
149
+ }
150
+
151
+ function connectionOf(storage: SqliteStorage, readOnly: boolean): DatabaseConnection {
152
+ return {
153
+ async executeQuery<R>(compiled: CompiledQuery): Promise<QueryResult<R>> {
154
+ const bindings = compiled.parameters.map(binding)
155
+ let rows: Record<string, SqliteValue>[]
156
+ try {
157
+ rows = readOnly ? readRows(storage, compiled.sql, bindings) : storage.sql.exec(compiled.sql, ...bindings).toArray()
158
+ } catch (error) {
159
+ throw sqliteError(error)
160
+ }
161
+ // Untyped rows become the caller's row type, as Bun.SQL's `any` rows do on Postgres.
162
+ return { rows: rows as R[] }
163
+ },
164
+ streamQuery<R>(): AsyncIterableIterator<QueryResult<R>> {
165
+ throw new QueryRefusedError('statement_shape', 'a SQLite database does not stream a query')
166
+ },
167
+ }
168
+ }
169
+
170
+ function refuseKyselyTransaction(): Promise<never> {
171
+ return Promise.reject(new QueryRefusedError('statement_shape', "a SQLite transaction runs through the storage's transaction, never Kysely's"))
172
+ }
173
+
174
+ class SqliteDialect implements Dialect {
175
+ readonly #storage: SqliteStorage
176
+ readonly #readOnly: boolean
177
+
178
+ constructor(storage: SqliteStorage, readOnly: boolean) {
179
+ this.#storage = storage
180
+ this.#readOnly = readOnly
181
+ }
182
+
183
+ createAdapter(): DialectAdapter {
184
+ return new SqliteAdapter()
185
+ }
186
+
187
+ createDriver(): Driver {
188
+ const connection = connectionOf(this.#storage, this.#readOnly)
189
+ return {
190
+ async init() {},
191
+ async acquireConnection() {
192
+ return connection
193
+ },
194
+ beginTransaction: refuseKyselyTransaction,
195
+ commitTransaction: refuseKyselyTransaction,
196
+ rollbackTransaction: refuseKyselyTransaction,
197
+ async releaseConnection() {},
198
+ async destroy() {},
199
+ }
200
+ }
201
+
202
+ createQueryCompiler(): SqliteQueryCompiler {
203
+ return sqliteCompiler
204
+ }
205
+
206
+ createIntrospector(db: Kysely<LooseDB>): DatabaseIntrospector {
207
+ return new SqliteIntrospector(db)
208
+ }
209
+ }
210
+
211
+ /**
212
+ * The data layer's database over a Durable Object's storage. A read-only transaction opens no storage transaction,
213
+ * which would hold back every other event of the object across the work's awaits: each of its statements runs in one
214
+ * of its own, so two of them may see different committed states, as under Postgres's READ COMMITTED. The idle timeout
215
+ * has no SQLite form.
216
+ */
217
+ export function openSqlite(storage: SqliteStorage): Database {
218
+ const kysely = new Kysely<LooseDB>({ dialect: new SqliteDialect(storage, false) })
219
+ const reads = new Kysely<LooseDB>({ dialect: new SqliteDialect(storage, true) })
220
+ const transaction: TransactionRunner = (options, body) => options.readOnly ? body(reads) : storage.transaction(() => body(kysely))
221
+ return Database.fromEngine({ dialect: 'sqlite', kysely, compiler: sqliteCompiler, transaction, reads })
222
+ }
223
+ // Application modules load after this one: a replaced opener would receive the object's storage.
224
+ Object.freeze(openSqlite)