@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.5
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.
- package/package.json +34 -3
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +154 -0
- package/src/codegen.ts +59 -9
- package/src/database.ts +227 -61
- package/src/errors.ts +2 -2
- package/src/file-columns.ts +4 -1
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +9 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +64 -9
- package/src/orm-types.ts +2 -2
- package/src/orm.ts +68 -35
- package/src/policy.ts +8 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +216 -473
- package/src/sqlite-bun.ts +122 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +362 -93
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +115 -9
- package/src/testing-shared.ts +733 -0
- package/src/testing-sqlite.ts +513 -0
- package/src/testing.ts +169 -482
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/capability.d.ts +5 -0
- package/types/src/codegen-sqlite.d.ts +6 -0
- package/types/src/codegen.d.ts +30 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/errors.d.ts +2 -2
- package/types/src/framework.d.ts +11 -5
- package/types/src/index.d.ts +1 -1
- package/types/src/job-leases.d.ts +32 -4
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +1 -0
- package/types/src/nodes.d.ts +13 -2
- package/types/src/orm-types.d.ts +2 -2
- package/types/src/policy.d.ts +4 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +10 -2
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +13 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +26 -9
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +10 -0
- package/types/src/temporal.d.ts +21 -0
- package/types/src/testing-shared.d.ts +201 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +2 -93
|
@@ -0,0 +1,122 @@
|
|
|
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
|
+
function bunBinding(value: SqliteValue): SQLQueryBindings {
|
|
17
|
+
return value instanceof ArrayBuffer ? new Uint8Array(value) : value
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** A column value as workerd answers it: a BLOB is an `ArrayBuffer`. */
|
|
21
|
+
function storageValue(value: unknown): SqliteValue {
|
|
22
|
+
if (value === null || typeof value === 'string' || typeof value === 'number') {
|
|
23
|
+
return value
|
|
24
|
+
}
|
|
25
|
+
if (value instanceof Uint8Array) {
|
|
26
|
+
return value.slice().buffer
|
|
27
|
+
}
|
|
28
|
+
throw new Error('bun:sqlite answered a value a Durable Object never does')
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function storageRow(row: Record<string, unknown>): Record<string, SqliteValue> {
|
|
32
|
+
return Object.fromEntries(Object.entries(row).map(([name, value]) => [name, storageValue(value)]))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** The transaction a `transaction` callback runs in: its savepoint depth, and the queue its own nested ones wait in. */
|
|
36
|
+
interface OpenTransaction {
|
|
37
|
+
readonly depth: number
|
|
38
|
+
queue: Promise<void>
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* `database` (a fresh `:memory:` one by default) with foreign keys enforced, as a Durable Object enforces them. One
|
|
43
|
+
* `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.
|
|
46
|
+
*/
|
|
47
|
+
export function bunSqliteStorage(database: Database = new Database(':memory:')): BunSqliteStorage {
|
|
48
|
+
database.run('PRAGMA foreign_keys = ON')
|
|
49
|
+
const totalChanges = (): number => database.query<{ readonly changes: number }, []>('select total_changes() as changes').get()?.changes ?? 0
|
|
50
|
+
const root: OpenTransaction = { depth: 0, queue: Promise.resolve() }
|
|
51
|
+
const open = new AsyncLocalStorage<OpenTransaction>()
|
|
52
|
+
|
|
53
|
+
function exec(query: string, ...bindings: SqliteValue[]): SqliteCursor {
|
|
54
|
+
if (TRANSACTION_CONTROL.test(query)) {
|
|
55
|
+
throw new Error('sql.exec runs no transaction statement: use storage.transaction() or storage.transactionSync()')
|
|
56
|
+
}
|
|
57
|
+
const values = bindings.map(bunBinding)
|
|
58
|
+
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
|
+
}
|
|
70
|
+
const rowsWritten = totalChanges() - before
|
|
71
|
+
return { toArray: () => rows, rowsWritten }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
sql: { exec },
|
|
76
|
+
async transaction<T>(closure: () => Promise<T>): Promise<T> {
|
|
77
|
+
const parent = open.getStore() ?? root
|
|
78
|
+
const previous = parent.queue
|
|
79
|
+
const done = Promise.withResolvers<void>()
|
|
80
|
+
parent.queue = previous.then(() => done.promise)
|
|
81
|
+
await previous
|
|
82
|
+
const depth = parent.depth + 1
|
|
83
|
+
const savepoint = `_test_savepoint_${depth}`
|
|
84
|
+
try {
|
|
85
|
+
database.run(depth === 1 ? 'BEGIN' : `SAVEPOINT ${savepoint}`)
|
|
86
|
+
try {
|
|
87
|
+
const result = await open.run({ depth, queue: Promise.resolve() }, closure)
|
|
88
|
+
database.run(depth === 1 ? 'COMMIT' : `RELEASE ${savepoint}`)
|
|
89
|
+
return result
|
|
90
|
+
} catch (error) {
|
|
91
|
+
if (depth === 1 && database.inTransaction) {
|
|
92
|
+
database.run('ROLLBACK')
|
|
93
|
+
} else if (depth > 1) {
|
|
94
|
+
database.run(`ROLLBACK TO ${savepoint}`)
|
|
95
|
+
database.run(`RELEASE ${savepoint}`)
|
|
96
|
+
}
|
|
97
|
+
throw error
|
|
98
|
+
}
|
|
99
|
+
} finally {
|
|
100
|
+
done.resolve()
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
transactionSync<T>(fn: () => T): T {
|
|
104
|
+
// Inside an open transaction workerd nests it in a savepoint too.
|
|
105
|
+
const nested = database.inTransaction
|
|
106
|
+
database.run(nested ? 'SAVEPOINT _test_sync_savepoint' : 'BEGIN')
|
|
107
|
+
try {
|
|
108
|
+
const result = fn()
|
|
109
|
+
database.run(nested ? 'RELEASE _test_sync_savepoint' : 'COMMIT')
|
|
110
|
+
return result
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (nested) {
|
|
113
|
+
database.run('ROLLBACK TO _test_sync_savepoint')
|
|
114
|
+
database.run('RELEASE _test_sync_savepoint')
|
|
115
|
+
} else if (database.inTransaction) {
|
|
116
|
+
database.run('ROLLBACK')
|
|
117
|
+
}
|
|
118
|
+
throw error
|
|
119
|
+
}
|
|
120
|
+
},
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -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)
|