@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.41
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 +39 -4
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +56 -2
- package/src/codegen-sqlite.ts +194 -0
- package/src/codegen.ts +230 -41
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/database.ts +227 -61
- package/src/description.ts +37 -8
- package/src/errors.ts +10 -6
- package/src/file-columns.ts +56 -11
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +15 -5
- package/src/guard.ts +373 -15
- package/src/index.ts +17 -1
- package/src/job-leases.ts +228 -55
- package/src/job-wakes.ts +600 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +210 -0
- package/src/migrations.ts +73 -0
- package/src/nodes.ts +84 -14
- package/src/orm-types.ts +206 -71
- package/src/orm.ts +425 -170
- package/src/policy.ts +1979 -141
- package/src/postgres.ts +26 -0
- package/src/registry.ts +55 -3
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +247 -476
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +269 -0
- package/src/store.ts +2292 -239
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +172 -6
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +1351 -0
- package/src/testing-sqlite.ts +685 -0
- package/src/testing.ts +310 -494
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +55 -2
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +79 -5
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/database.d.ts +81 -20
- package/types/src/description.d.ts +26 -8
- package/types/src/errors.d.ts +9 -6
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +12 -5
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +5 -4
- package/types/src/job-leases.d.ts +40 -5
- package/types/src/job-wakes.d.ts +124 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +4 -0
- package/types/src/nodes.d.ts +17 -2
- package/types/src/orm-types.d.ts +163 -71
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +351 -23
- package/types/src/postgres.d.ts +12 -0
- package/types/src/registry.d.ts +40 -3
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +29 -21
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +143 -34
- package/types/src/stored-files.d.ts +6 -2
- package/types/src/tables.d.ts +18 -2
- package/types/src/temporal.d.ts +24 -0
- package/types/src/testing-shared.d.ts +290 -0
- package/types/src/testing-sqlite.d.ts +37 -0
- package/types/src/testing.d.ts +2 -93
- package/types/src/vocabulary-tables.d.ts +169 -22
package/src/database.ts
CHANGED
|
@@ -1,12 +1,46 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { CompiledQuery, createQueryId, type Dialect, Kysely, PostgresQueryCompiler, type RootOperationNode, type TransactionBuilder } from 'kysely'
|
|
3
|
-
import { PostgresJSDialect } from 'kysely-postgres-js'
|
|
1
|
+
import { CompiledQuery, createQueryId, type Dialect, Kysely, PostgresQueryCompiler, type QueryCompiler, type RootOperationNode } from 'kysely'
|
|
4
2
|
import { databaseError, QueryRefusedError } from './errors'
|
|
5
3
|
import { assertAllowedTree, type GuardContext } from './guard'
|
|
6
4
|
import { isPlainIdentifier } from './identifier'
|
|
7
5
|
|
|
8
|
-
type LooseDB = Record<string, Record<string, unknown>>
|
|
9
|
-
|
|
6
|
+
export type LooseDB = Record<string, Record<string, unknown>>
|
|
7
|
+
/** What a statement runs on: the database's own executor, or the one of the transaction it runs in. */
|
|
8
|
+
export type Executor = Pick<Kysely<LooseDB>, 'executeQuery'>
|
|
9
|
+
|
|
10
|
+
/** The SQL a database speaks: Postgres on Bun, SQLite in a Cloudflare Durable Object (ADR-0065). */
|
|
11
|
+
export type SqlDialect = 'postgres' | 'sqlite'
|
|
12
|
+
|
|
13
|
+
export interface TransactionOptions {
|
|
14
|
+
/**
|
|
15
|
+
* A `READ ONLY` transaction on Postgres. SQLite opens none: each statement runs in a transaction of its own, which
|
|
16
|
+
* rolls back a statement that wrote. A read-only session refuses writes either way.
|
|
17
|
+
*/
|
|
18
|
+
readonly readOnly: boolean
|
|
19
|
+
/** How long the transaction may sit idle before the database ends it; a database without the setting ignores it. */
|
|
20
|
+
readonly idleTimeoutMs?: number
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Runs `body` in one transaction, on the executor it hands it: commits when `body` resolves, rolls back when it
|
|
25
|
+
* rejects, and rejects with `body`'s error. Its BEGIN, COMMIT and ROLLBACK failures reject with the driver's error.
|
|
26
|
+
*/
|
|
27
|
+
export type TransactionRunner = <T>(options: TransactionOptions, body: (executor: Executor) => Promise<T>) => Promise<T>
|
|
28
|
+
|
|
29
|
+
/** What a `Database` runs on: the driver, the compiler of its dialect, and how it opens a transaction. */
|
|
30
|
+
export interface DatabaseEngine {
|
|
31
|
+
readonly dialect: SqlDialect
|
|
32
|
+
readonly kysely: Kysely<LooseDB>
|
|
33
|
+
/** Compiles every guarded tree; frozen, since a patch to it after the guard ran would bypass the guard. */
|
|
34
|
+
readonly compiler: QueryCompiler
|
|
35
|
+
readonly transaction: TransactionRunner
|
|
36
|
+
/** The application's schema, the connection's `search_path`; `undefined` where the database has none. */
|
|
37
|
+
readonly schema?: string
|
|
38
|
+
/**
|
|
39
|
+
* SQLite's: runs each statement in a transaction of its own (a savepoint inside an open one) and refuses, rolling it
|
|
40
|
+
* back, one that wrote. A `ctx.sql` site that declares `'read'` runs on it in a writable invocation too.
|
|
41
|
+
*/
|
|
42
|
+
readonly reads?: Executor
|
|
43
|
+
}
|
|
10
44
|
|
|
11
45
|
/**
|
|
12
46
|
* With `prepare: false`, Bun.SQL sends every parameter as text and a Date as `Date#toString()`, which Postgres
|
|
@@ -25,14 +59,14 @@ function timestampText(date: Date): string {
|
|
|
25
59
|
return date.toISOString()
|
|
26
60
|
}
|
|
27
61
|
|
|
28
|
-
const
|
|
29
|
-
freezePrototypeChain(
|
|
62
|
+
const postgresCompiler = new ParameterCompiler()
|
|
63
|
+
freezePrototypeChain(postgresCompiler)
|
|
30
64
|
|
|
31
65
|
/**
|
|
32
66
|
* The compiler turns the guarded tree into SQL, so a patch to it after the guard ran would bypass the guard.
|
|
33
67
|
* Freezing it when this module loads, before application modules, makes such a patch throw instead.
|
|
34
68
|
*/
|
|
35
|
-
function freezePrototypeChain(object: object): void {
|
|
69
|
+
export function freezePrototypeChain(object: object): void {
|
|
36
70
|
let current: object | null = object
|
|
37
71
|
while (current !== null && current !== Object.prototype) {
|
|
38
72
|
Object.freeze(current)
|
|
@@ -56,63 +90,73 @@ export function applicationSchema(appId: string): string {
|
|
|
56
90
|
return `app_${appId.replaceAll('-', '_')}`
|
|
57
91
|
}
|
|
58
92
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
93
|
+
const SQL_IDLE_TIMEOUT = "select set_config('idle_in_transaction_session_timeout', $1, true)"
|
|
94
|
+
|
|
95
|
+
/** Postgres over Kysely's own transaction builder. */
|
|
96
|
+
function postgresTransaction(kysely: Kysely<LooseDB>): TransactionRunner {
|
|
97
|
+
return (options, body) => {
|
|
98
|
+
const builder = kysely.transaction()
|
|
99
|
+
return (options.readOnly ? builder.setAccessMode('read only') : builder).execute(async (transaction) => {
|
|
100
|
+
if (options.idleTimeoutMs !== undefined) {
|
|
101
|
+
await transaction.executeQuery(CompiledQuery.raw(SQL_IDLE_TIMEOUT, [String(options.idleTimeoutMs)]))
|
|
102
|
+
}
|
|
103
|
+
return body(transaction)
|
|
104
|
+
})
|
|
105
|
+
}
|
|
64
106
|
}
|
|
65
107
|
|
|
66
108
|
let openSession: (database: Database, readOnly: boolean) => Session
|
|
67
|
-
let
|
|
109
|
+
let engineOf: (database: Database) => DatabaseEngine
|
|
68
110
|
let firstConnection: (database: Database) => Promise<void>
|
|
69
111
|
|
|
70
112
|
/** The connection the data layer runs on. It has no public query method: everything goes through a store. */
|
|
71
113
|
export class Database {
|
|
72
|
-
readonly #
|
|
73
|
-
readonly #schema: string | undefined
|
|
114
|
+
readonly #engine: DatabaseEngine
|
|
74
115
|
|
|
75
|
-
private constructor(
|
|
76
|
-
|
|
77
|
-
|
|
116
|
+
private constructor(engine: DatabaseEngine) {
|
|
117
|
+
if (engine.schema !== undefined && !isPlainIdentifier(engine.schema)) {
|
|
118
|
+
throw new QueryRefusedError('invalid_name', 'the schema must match ^[a-z_][a-z0-9_]*$')
|
|
119
|
+
}
|
|
120
|
+
this.#engine = Object.freeze({ ...engine })
|
|
78
121
|
Object.freeze(this)
|
|
79
122
|
}
|
|
80
123
|
|
|
81
124
|
static {
|
|
82
|
-
openSession = (database, readOnly) => new Session(database.#kysely, database.#
|
|
83
|
-
|
|
125
|
+
openSession = (database, readOnly) => new Session(database.#engine.kysely, database.#engine, false, readOnly)
|
|
126
|
+
engineOf = (database) => database.#engine
|
|
84
127
|
firstConnection = async (database) => {
|
|
85
|
-
await database.#kysely.executeQuery(CompiledQuery.raw('SELECT 1'))
|
|
128
|
+
await database.#engine.kysely.executeQuery(CompiledQuery.raw('SELECT 1'))
|
|
86
129
|
}
|
|
87
130
|
}
|
|
88
131
|
|
|
89
132
|
/**
|
|
90
|
-
*
|
|
91
|
-
*
|
|
133
|
+
* Any Kysely Postgres dialect: `@fabrika/db/postgres` opens Bun.SQL through it, tests use one that records statements
|
|
134
|
+
* instead of sending them.
|
|
92
135
|
*/
|
|
93
|
-
static
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
}
|
|
97
|
-
const pool = new SQL({ url: options.url, adapter: 'postgres', prepare: false, max: options.max ?? 10, connection: { search_path: options.schema } })
|
|
98
|
-
return new Database(new Kysely<LooseDB>({ dialect: new PostgresJSDialect({ postgres: pool }) }), options.schema)
|
|
136
|
+
static fromDialect(dialect: Dialect, options: { readonly schema?: string } = {}): Database {
|
|
137
|
+
const kysely = new Kysely<LooseDB>({ dialect })
|
|
138
|
+
return new Database({ dialect: 'postgres', kysely, compiler: postgresCompiler, transaction: postgresTransaction(kysely), schema: options.schema })
|
|
99
139
|
}
|
|
100
140
|
|
|
101
|
-
/**
|
|
102
|
-
static
|
|
103
|
-
return new Database(
|
|
141
|
+
/** A database of another dialect (`@fabrika/db/sqlite`), with its own frozen compiler and transaction runner. */
|
|
142
|
+
static fromEngine(engine: DatabaseEngine): Database {
|
|
143
|
+
return new Database(engine)
|
|
104
144
|
}
|
|
105
145
|
|
|
106
|
-
|
|
146
|
+
get dialect(): SqlDialect {
|
|
147
|
+
return this.#engine.dialect
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The application's schema, the connection's `search_path`; `undefined` over a bare dialect and on SQLite. */
|
|
107
151
|
get schema(): string | undefined {
|
|
108
|
-
return this.#schema
|
|
152
|
+
return this.#engine.schema
|
|
109
153
|
}
|
|
110
154
|
|
|
111
155
|
async close(): Promise<void> {
|
|
112
|
-
await this.#kysely.destroy()
|
|
156
|
+
await this.#engine.kysely.destroy()
|
|
113
157
|
}
|
|
114
158
|
}
|
|
115
|
-
// Application modules load after this one: a replaced
|
|
159
|
+
// Application modules load after this one: a replaced opener would receive the database's connection.
|
|
116
160
|
Object.freeze(Database)
|
|
117
161
|
Object.freeze(Database.prototype)
|
|
118
162
|
|
|
@@ -141,6 +185,7 @@ export function sessionOf(source: SessionSource): Session {
|
|
|
141
185
|
}
|
|
142
186
|
|
|
143
187
|
let executeFixed: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
|
|
188
|
+
let executeRead: (session: Session, compiled: CompiledQuery) => Promise<readonly unknown[]>
|
|
144
189
|
|
|
145
190
|
/** What a session reports to, and asks, the transaction it runs in. */
|
|
146
191
|
interface SessionHooks {
|
|
@@ -171,13 +216,15 @@ function untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Pro
|
|
|
171
216
|
*/
|
|
172
217
|
export class Session {
|
|
173
218
|
readonly #executor: Executor
|
|
174
|
-
readonly #
|
|
219
|
+
readonly #engine: DatabaseEngine
|
|
220
|
+
readonly #inTransaction: boolean
|
|
175
221
|
readonly #readOnly: boolean
|
|
176
222
|
readonly #hooks: SessionHooks
|
|
177
223
|
|
|
178
|
-
constructor(executor: Executor,
|
|
224
|
+
constructor(executor: Executor, engine: DatabaseEngine, inTransaction: boolean, readOnly: boolean, hooks: SessionHooks = {}) {
|
|
179
225
|
this.#executor = executor
|
|
180
|
-
this.#
|
|
226
|
+
this.#engine = engine
|
|
227
|
+
this.#inTransaction = inTransaction
|
|
181
228
|
this.#readOnly = readOnly
|
|
182
229
|
this.#hooks = hooks
|
|
183
230
|
Object.freeze(this)
|
|
@@ -185,23 +232,29 @@ export class Session {
|
|
|
185
232
|
|
|
186
233
|
static {
|
|
187
234
|
executeFixed = async (session, compiled) => (await session.#execute(compiled)).rows
|
|
235
|
+
executeRead = async (session, compiled) => (await session.#execute(compiled, session.#engine.reads ?? session.#executor)).rows
|
|
188
236
|
}
|
|
189
237
|
|
|
190
238
|
get readOnly(): boolean {
|
|
191
239
|
return this.#readOnly
|
|
192
240
|
}
|
|
193
241
|
|
|
242
|
+
/** The dialect of the database this session runs on: a framework statement picks its text by it. */
|
|
243
|
+
get dialect(): SqlDialect {
|
|
244
|
+
return this.#engine.dialect
|
|
245
|
+
}
|
|
246
|
+
|
|
194
247
|
/** Fails the transaction this session runs in, so it commits nothing: a statement refused before it was sent. */
|
|
195
248
|
fail(): void {
|
|
196
249
|
this.#hooks.failed?.()
|
|
197
250
|
}
|
|
198
251
|
|
|
199
|
-
async #execute<O>(compiled: CompiledQuery<O
|
|
252
|
+
async #execute<O>(compiled: CompiledQuery<O>, executor: Executor = this.#executor): Promise<{ readonly rows: O[] }> {
|
|
200
253
|
if (this.#hooks.open?.() === false) {
|
|
201
254
|
throw new QueryRefusedError('ended', 'the transaction of this session has ended; it runs nothing more')
|
|
202
255
|
}
|
|
203
256
|
try {
|
|
204
|
-
return await
|
|
257
|
+
return await executor.executeQuery(compiled)
|
|
205
258
|
} catch (error) {
|
|
206
259
|
this.#hooks.failed?.()
|
|
207
260
|
throw databaseError(error)
|
|
@@ -214,11 +267,10 @@ export class Session {
|
|
|
214
267
|
throw new QueryRefusedError('read_only', 'this request is read-only: it reads, and no operation may write or lock a row')
|
|
215
268
|
}
|
|
216
269
|
// CompiledQuery's row type is a phantom: this is the one place where generated row types meet the wire.
|
|
217
|
-
const compiled: CompiledQuery<O> = compiler.compileQuery(node, createQueryId())
|
|
218
|
-
|
|
219
|
-
if (this.#readOnly && kysely !== undefined) {
|
|
270
|
+
const compiled: CompiledQuery<O> = this.#engine.compiler.compileQuery(node, createQueryId())
|
|
271
|
+
if (this.#readOnly && !this.#inTransaction) {
|
|
220
272
|
try {
|
|
221
|
-
const result = await
|
|
273
|
+
const result = await this.#engine.transaction({ readOnly: true }, (executor) => executor.executeQuery(compiled))
|
|
222
274
|
return result.rows
|
|
223
275
|
} catch (error) {
|
|
224
276
|
throw databaseError(error)
|
|
@@ -234,15 +286,14 @@ export class Session {
|
|
|
234
286
|
* `work` returned or not; its session then runs nothing more.
|
|
235
287
|
*/
|
|
236
288
|
async transaction<T>(work: (session: Session) => Promise<T>, signal?: AbortSignal): Promise<T> {
|
|
237
|
-
if (this.#
|
|
289
|
+
if (this.#inTransaction) {
|
|
238
290
|
return work(this)
|
|
239
291
|
}
|
|
240
|
-
const builder = this.#kysely.transaction()
|
|
241
292
|
let open = true
|
|
242
293
|
let failed = false
|
|
243
294
|
let failure: { readonly error: unknown } | undefined
|
|
244
295
|
try {
|
|
245
|
-
return await
|
|
296
|
+
return await this.#engine.transaction({ readOnly: this.#readOnly }, async (executor) => {
|
|
246
297
|
try {
|
|
247
298
|
const hooks: SessionHooks = {
|
|
248
299
|
open: () => open,
|
|
@@ -250,7 +301,7 @@ export class Session {
|
|
|
250
301
|
failed = true
|
|
251
302
|
},
|
|
252
303
|
}
|
|
253
|
-
const result = await untilAborted(work(new Session(
|
|
304
|
+
const result = await untilAborted(work(new Session(executor, this.#engine, true, this.#readOnly, hooks)), signal)
|
|
254
305
|
// A failure the work caught: Postgres would answer the COMMIT of an aborted transaction with a silent ROLLBACK.
|
|
255
306
|
if (failed) {
|
|
256
307
|
throw new QueryRefusedError('statement_failed', 'a statement of this transaction failed, so nothing it wrote commits')
|
|
@@ -274,11 +325,43 @@ Object.freeze(Session.prototype)
|
|
|
274
325
|
/** How long an invocation's transaction may sit idle before Postgres ends it, and its connection with it. */
|
|
275
326
|
export const INVOCATION_IDLE_TIMEOUT_MS = 30_000
|
|
276
327
|
|
|
277
|
-
const SQL_IDLE_TIMEOUT = "select set_config('idle_in_transaction_session_timeout', $1, true)"
|
|
278
|
-
|
|
279
328
|
/** What the invocation's transaction body throws to roll back; never seen outside this module. */
|
|
280
329
|
class RolledBack extends Error {}
|
|
281
330
|
|
|
331
|
+
/** A writing invocation that holds its object's storage transaction longer than this logs one line. */
|
|
332
|
+
export const TRANSACTION_HELD_LOG_MS = 1_000
|
|
333
|
+
/** A writing invocation that holds its object's storage transaction longer than this is also reported. */
|
|
334
|
+
export const TRANSACTION_HELD_REPORT_MS = 5_000
|
|
335
|
+
|
|
336
|
+
/** Where an enclosure tells how long it held its object: every other event of the object waited that long. */
|
|
337
|
+
export interface HoldWatch {
|
|
338
|
+
/** The site the invocation serves, which the log line names. */
|
|
339
|
+
readonly site: string
|
|
340
|
+
/** Hears a hold longer than `TRANSACTION_HELD_REPORT_MS`, in whole ms. */
|
|
341
|
+
readonly held: (heldMs: number) => void
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Runs once the transaction settled, so it never throws: a failed log or report must not turn a committed invocation
|
|
346
|
+
* into a failed one. Each has its own guard; the line names the site and the ms only, never a value or a statement.
|
|
347
|
+
*/
|
|
348
|
+
function reportHold(watch: HoldWatch, heldMs: number): void {
|
|
349
|
+
try {
|
|
350
|
+
if (heldMs > TRANSACTION_HELD_LOG_MS) {
|
|
351
|
+
console.warn(`fabrika: ${watch.site}: held its object's transaction for ${heldMs} ms`)
|
|
352
|
+
}
|
|
353
|
+
} catch {
|
|
354
|
+
// The report below still goes out.
|
|
355
|
+
}
|
|
356
|
+
try {
|
|
357
|
+
if (heldMs > TRANSACTION_HELD_REPORT_MS) {
|
|
358
|
+
watch.held(heldMs)
|
|
359
|
+
}
|
|
360
|
+
} catch {
|
|
361
|
+
// The hold was logged; the invocation's own outcome stands.
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
|
|
282
365
|
/**
|
|
283
366
|
* The one transaction of an invocation (a request, a webhook delivery): opened by its first statement, then ended
|
|
284
367
|
* once by the framework — committed after the handler returned and its output passed validation, rolled back
|
|
@@ -289,6 +372,7 @@ class RolledBack extends Error {}
|
|
|
289
372
|
export class InvocationTransaction {
|
|
290
373
|
readonly #database: Database
|
|
291
374
|
readonly #readOnly: boolean
|
|
375
|
+
readonly #now: () => number
|
|
292
376
|
readonly #decision = Promise.withResolvers<'commit' | 'rollback'>()
|
|
293
377
|
#opened: Promise<Session> | undefined
|
|
294
378
|
#run: Promise<void> | undefined
|
|
@@ -296,10 +380,15 @@ export class InvocationTransaction {
|
|
|
296
380
|
#isReleased = true
|
|
297
381
|
#ended = false
|
|
298
382
|
#failed = false
|
|
383
|
+
/** Inside `enclose` on SQLite: `commit()` and `rollback()` only decide, and the enclosure ends the transaction. */
|
|
384
|
+
#enclosed = false
|
|
385
|
+
#decided: 'commit' | 'rollback' | undefined
|
|
299
386
|
|
|
300
|
-
|
|
387
|
+
/** `now` is the clock an enclosure's hold is measured by. */
|
|
388
|
+
constructor(database: Database, readOnly: boolean, now: () => number = Date.now) {
|
|
301
389
|
this.#database = database
|
|
302
390
|
this.#readOnly = readOnly
|
|
391
|
+
this.#now = now
|
|
303
392
|
}
|
|
304
393
|
|
|
305
394
|
/** A `READ ONLY` transaction: a query's or an export's. */
|
|
@@ -327,6 +416,65 @@ export class InvocationTransaction {
|
|
|
327
416
|
return this.#isReleased
|
|
328
417
|
}
|
|
329
418
|
|
|
419
|
+
/**
|
|
420
|
+
* Runs `work`: the invocation from its handler to its `commit()`. On SQLite a writing invocation's transaction
|
|
421
|
+
* encloses `work`, opened before it: a Durable Object's transaction holds back every other event, the answers to the
|
|
422
|
+
* object's own I/O included, until its callback ends, so the handler runs inside it. There `commit()` and `rollback()`
|
|
423
|
+
* decide, the COMMIT runs once `work` returned, and a failed COMMIT rejects with a `DatabaseError`. A read-only
|
|
424
|
+
* invocation, and every invocation elsewhere, runs `work` as is: a read-only one on SQLite holds no storage
|
|
425
|
+
* transaction, so the object serves other events while it awaits.
|
|
426
|
+
*
|
|
427
|
+
* Only the SQLite enclosure is measured for `watch`, from entering the transaction until it settled: it holds the
|
|
428
|
+
* whole object, where a Postgres transaction holds one pooled connection and other requests go on.
|
|
429
|
+
*/
|
|
430
|
+
async enclose<T>(work: () => Promise<T>, watch: HoldWatch): Promise<T> {
|
|
431
|
+
const engine = engineOf(this.#database)
|
|
432
|
+
if (engine.dialect !== 'sqlite' || this.#readOnly) {
|
|
433
|
+
return work()
|
|
434
|
+
}
|
|
435
|
+
if (this.#opened !== undefined || this.#ended) {
|
|
436
|
+
throw new QueryRefusedError('ended', 'an invocation encloses its work before its first statement')
|
|
437
|
+
}
|
|
438
|
+
this.#enclosed = true
|
|
439
|
+
this.#isReleased = false
|
|
440
|
+
let result: { readonly value: T } | undefined
|
|
441
|
+
let entered: number | undefined
|
|
442
|
+
try {
|
|
443
|
+
await engine.transaction({ readOnly: this.#readOnly }, async (executor) => {
|
|
444
|
+
entered = this.#now()
|
|
445
|
+
const session = new Session(executor, engine, true, this.#readOnly, {
|
|
446
|
+
failed: () => {
|
|
447
|
+
this.#failed = true
|
|
448
|
+
},
|
|
449
|
+
open: () => !this.#ended,
|
|
450
|
+
})
|
|
451
|
+
this.#opened = Promise.resolve(session)
|
|
452
|
+
result = { value: await work() }
|
|
453
|
+
this.#ended = true
|
|
454
|
+
if (this.#decided !== 'commit') {
|
|
455
|
+
throw new RolledBack()
|
|
456
|
+
}
|
|
457
|
+
})
|
|
458
|
+
} catch (error) {
|
|
459
|
+
if (result === undefined) {
|
|
460
|
+
throw error
|
|
461
|
+
}
|
|
462
|
+
if (!(error instanceof RolledBack)) {
|
|
463
|
+
throw databaseError(error)
|
|
464
|
+
}
|
|
465
|
+
} finally {
|
|
466
|
+
this.#ended = true
|
|
467
|
+
this.#isReleased = true
|
|
468
|
+
if (entered !== undefined) {
|
|
469
|
+
reportHold(watch, Math.round(this.#now() - entered))
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
if (result === undefined) {
|
|
473
|
+
throw new QueryRefusedError('ended', 'the transaction ended before the invocation answered')
|
|
474
|
+
}
|
|
475
|
+
return result.value
|
|
476
|
+
}
|
|
477
|
+
|
|
330
478
|
/** The session the invocation's statements run in; the first call opens the transaction. */
|
|
331
479
|
session(): Promise<Session> {
|
|
332
480
|
if (this.#ended) {
|
|
@@ -339,15 +487,15 @@ export class InvocationTransaction {
|
|
|
339
487
|
#open(): Promise<Session> {
|
|
340
488
|
const ready = Promise.withResolvers<Session>()
|
|
341
489
|
this.#isReleased = false
|
|
342
|
-
const
|
|
343
|
-
const
|
|
344
|
-
|
|
490
|
+
const engine = engineOf(this.#database)
|
|
491
|
+
const options: TransactionOptions = { readOnly: this.#readOnly, idleTimeoutMs: INVOCATION_IDLE_TIMEOUT_MS }
|
|
492
|
+
const run = engine.transaction(options, async (executor) => {
|
|
493
|
+
const session = new Session(executor, engine, true, this.#readOnly, {
|
|
345
494
|
failed: () => {
|
|
346
495
|
this.#failed = true
|
|
347
496
|
},
|
|
348
497
|
open: () => !this.#ended,
|
|
349
498
|
})
|
|
350
|
-
await executeFixed(session, CompiledQuery.raw(SQL_IDLE_TIMEOUT, [String(INVOCATION_IDLE_TIMEOUT_MS)]))
|
|
351
499
|
ready.resolve(session)
|
|
352
500
|
if ((await this.#decision.promise) === 'rollback') {
|
|
353
501
|
throw new RolledBack()
|
|
@@ -371,6 +519,13 @@ export class InvocationTransaction {
|
|
|
371
519
|
throw new QueryRefusedError('ended', 'this invocation has already ended')
|
|
372
520
|
}
|
|
373
521
|
this.#ended = true
|
|
522
|
+
if (this.#enclosed) {
|
|
523
|
+
this.#decided = this.#failed ? 'rollback' : 'commit'
|
|
524
|
+
if (this.#failed) {
|
|
525
|
+
throw new QueryRefusedError('statement_failed', 'a statement of this invocation failed, so nothing it wrote commits')
|
|
526
|
+
}
|
|
527
|
+
return
|
|
528
|
+
}
|
|
374
529
|
const run = this.#run
|
|
375
530
|
if (this.#failed) {
|
|
376
531
|
this.#decision.resolve('rollback')
|
|
@@ -390,9 +545,13 @@ export class InvocationTransaction {
|
|
|
390
545
|
}
|
|
391
546
|
}
|
|
392
547
|
|
|
393
|
-
/** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back. */
|
|
548
|
+
/** Discards what the invocation wrote; idempotent, never throws, and returns once the connection is back (inside `enclose`, it only decides). */
|
|
394
549
|
async rollback(): Promise<void> {
|
|
395
550
|
this.#ended = true
|
|
551
|
+
if (this.#enclosed) {
|
|
552
|
+
this.#decided ??= 'rollback'
|
|
553
|
+
return
|
|
554
|
+
}
|
|
396
555
|
this.#decision.resolve('rollback')
|
|
397
556
|
await this.#released
|
|
398
557
|
}
|
|
@@ -419,8 +578,15 @@ export type SqlParameter = string | number | boolean | bigint | null
|
|
|
419
578
|
|
|
420
579
|
/**
|
|
421
580
|
* One `ctx.sql` statement, whose text `sql.ts` classified and whose values are bound parameters only. It runs through the
|
|
422
|
-
* session's one path to the connection, so a statement the database refuses fails the invocation it runs in.
|
|
581
|
+
* session's one path to the connection, so a statement the database refuses fails the invocation it runs in. A `'read'`
|
|
582
|
+
* statement runs on the engine's `reads` where it has one (SQLite), so one that wrote is refused and rolled back.
|
|
423
583
|
*/
|
|
424
|
-
export function runApplicationStatement(
|
|
425
|
-
|
|
584
|
+
export function runApplicationStatement(
|
|
585
|
+
session: Session,
|
|
586
|
+
text: string,
|
|
587
|
+
parameters: readonly SqlParameter[],
|
|
588
|
+
mode: 'read' | 'write',
|
|
589
|
+
): Promise<readonly unknown[]> {
|
|
590
|
+
const compiled = CompiledQuery.raw(text, [...parameters])
|
|
591
|
+
return mode === 'read' ? executeRead(session, compiled) : executeFixed(session, compiled)
|
|
426
592
|
}
|
package/src/description.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { OperationNode } from 'kysely'
|
|
1
2
|
import { inSet, isSafeInteger, type NameSet, nameSet, namesOf, ownEntry, ownKeys, parseList } from './builtins'
|
|
2
3
|
import { QueryRefusedError } from './errors'
|
|
3
4
|
import { isPlainIdentifier } from './identifier'
|
|
@@ -59,6 +60,8 @@ export interface TableShape {
|
|
|
59
60
|
readonly joinable: Readonly<Record<string, JoinShape>>
|
|
60
61
|
/** The `date` columns, which a read answers as `YYYY-MM-DD` text. */
|
|
61
62
|
readonly dates: NameSet
|
|
63
|
+
/** The JSON columns, which a query selects but never compares or orders by. */
|
|
64
|
+
readonly json: NameSet
|
|
62
65
|
}
|
|
63
66
|
|
|
64
67
|
export interface JoinShape {
|
|
@@ -72,6 +75,8 @@ export interface JoinShape {
|
|
|
72
75
|
export interface JoinState {
|
|
73
76
|
readonly join: JoinShape
|
|
74
77
|
readonly select: SelectState
|
|
78
|
+
/** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
|
|
79
|
+
readonly condition?: OperationNode
|
|
75
80
|
}
|
|
76
81
|
|
|
77
82
|
export interface SelectState {
|
|
@@ -88,14 +93,22 @@ export interface SelectState {
|
|
|
88
93
|
|
|
89
94
|
type Comparable<V> = Exclude<V, null | undefined>
|
|
90
95
|
type Columns<Row> = keyof Row & string
|
|
96
|
+
/** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
|
|
97
|
+
export type ComparableColumn<Row> = { [K in Columns<Row>]: unknown extends Row[K] ? never : K }[Columns<Row>]
|
|
91
98
|
type StringColumn<Row> = { [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never }[Columns<Row>]
|
|
92
|
-
type NullableColumn<Row> = { [K in
|
|
99
|
+
type NullableColumn<Row> = { [K in ComparableColumn<Row>]: null extends Row[K] ? K : never }[ComparableColumn<Row>]
|
|
93
100
|
|
|
101
|
+
/**
|
|
102
|
+
* A `[column, operator, value]` condition on `Row`'s columns. A null test (`is`, `is not`) takes a nullable column only;
|
|
103
|
+
* the runtime knows no column's nullability, so an untyped condition that tests a column never null runs and matches no
|
|
104
|
+
* row (`is`) or every row (`is not`).
|
|
105
|
+
*/
|
|
94
106
|
export type ConditionTuple<Row> =
|
|
95
107
|
| {
|
|
96
|
-
[K in
|
|
97
|
-
}[
|
|
108
|
+
[K in ComparableColumn<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
|
|
109
|
+
}[ComparableColumn<Row>]
|
|
98
110
|
| { [K in StringColumn<Row>]: readonly [K, PatternOperator | 'contains', string] }[StringColumn<Row>]
|
|
111
|
+
| { [K in NullableColumn<Row>]: readonly [K, NullOperator, null] }[NullableColumn<Row>]
|
|
99
112
|
|
|
100
113
|
type Prefixed<C extends string, J> = { [K in keyof J & string as `${C}.${K}`]: J[K] }
|
|
101
114
|
export type NoColumns = Record<never, never>
|
|
@@ -137,8 +150,12 @@ export class ScopedSelect<Row, Selected, Children> {
|
|
|
137
150
|
return this.#next({ columns: names })
|
|
138
151
|
}
|
|
139
152
|
|
|
140
|
-
where<C extends
|
|
141
|
-
where<C extends
|
|
153
|
+
where<C extends ComparableColumn<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
|
|
154
|
+
where<C extends ComparableColumn<Row>>(
|
|
155
|
+
column: C,
|
|
156
|
+
operator: ListOperator,
|
|
157
|
+
values: readonly Comparable<Row[C]>[],
|
|
158
|
+
): ScopedSelect<Row, Selected, Children>
|
|
142
159
|
where<C extends StringColumn<Row>>(column: C, operator: PatternOperator, pattern: string): ScopedSelect<Row, Selected, Children>
|
|
143
160
|
where<C extends NullableColumn<Row>>(column: C, operator: NullOperator, value: null): ScopedSelect<Row, Selected, Children>
|
|
144
161
|
where(column: string, operator: string, value: unknown): ScopedSelect<Row, Selected, Children> {
|
|
@@ -166,11 +183,11 @@ export class ScopedSelect<Row, Selected, Children> {
|
|
|
166
183
|
return this.#withCondition(this.#parseCondition(column, 'contains', text))
|
|
167
184
|
}
|
|
168
185
|
|
|
169
|
-
orderBy(column:
|
|
186
|
+
orderBy(column: ComparableColumn<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
|
|
170
187
|
if (direction !== 'asc' && direction !== 'desc') {
|
|
171
188
|
throw new QueryRefusedError('list_page', `orderBy direction must be 'asc' or 'desc'`)
|
|
172
189
|
}
|
|
173
|
-
return this.#next({ orderBy: [...this.#state.orderBy, { column: this.#column
|
|
190
|
+
return this.#next({ orderBy: [...this.#state.orderBy, { column: comparableColumnOf(this.#shape, column, 'orders by'), direction }] })
|
|
174
191
|
}
|
|
175
192
|
|
|
176
193
|
limit(limit: number): ScopedSelect<Row, Selected, Children> {
|
|
@@ -233,9 +250,21 @@ export function columnOf(shape: TableShape, name: unknown): string {
|
|
|
233
250
|
return name
|
|
234
251
|
}
|
|
235
252
|
|
|
253
|
+
/** A column the shape lets a query compare, order or aggregate by: `columnOf`, and never a JSON column. */
|
|
254
|
+
export function comparableColumnOf(shape: TableShape, name: unknown, use: string): string {
|
|
255
|
+
const column = columnOf(shape, name)
|
|
256
|
+
if (inSet(shape.json, column)) {
|
|
257
|
+
throw new QueryRefusedError(
|
|
258
|
+
'invalid_argument',
|
|
259
|
+
`${column} of ${shape.table} is a JSON column, which the data layer never ${use}; read a path of it with ctx.sql (->>)`,
|
|
260
|
+
)
|
|
261
|
+
}
|
|
262
|
+
return column
|
|
263
|
+
}
|
|
264
|
+
|
|
236
265
|
/** One `[column, operator, value]` condition over a caller's values, checked before anything reads it further. */
|
|
237
266
|
export function parseCondition(shape: TableShape, column: unknown, operator: unknown, value: unknown): Compare | Contains {
|
|
238
|
-
const name =
|
|
267
|
+
const name = comparableColumnOf(shape, column, 'compares')
|
|
239
268
|
if (operator === 'contains') {
|
|
240
269
|
if (typeof value !== 'string') {
|
|
241
270
|
throw new QueryRefusedError('invalid_argument', 'contains takes a string')
|
package/src/errors.ts
CHANGED
|
@@ -29,11 +29,13 @@ export class CapabilityError extends Error {
|
|
|
29
29
|
|
|
30
30
|
/**
|
|
31
31
|
* Why the layer refused, as a closed catalog: a server log names the reason and its fixed text, never the message,
|
|
32
|
-
* which can quote a value the request sent.
|
|
32
|
+
* which can quote a value the request sent. Each text is one string literal, however long: a concatenation keeps the
|
|
33
|
+
* whole catalog in an SPA bundle that imports this module (`web/__tests__/bundle.test.ts`).
|
|
33
34
|
*/
|
|
34
35
|
export const QUERY_REFUSALS = {
|
|
35
36
|
invalid_argument: 'a data-layer call took an argument of another shape than its type declares',
|
|
36
|
-
invalid_value:
|
|
37
|
+
invalid_value:
|
|
38
|
+
'a value cannot be bound: undefined, a function, symbol or object of a kind the database does not bind, a list item other than a string or finite number, a date or timestamp that is neither a valid Date nor well-formed text or lies out of range, a non-finite number, or on SQLite a bigint outside the safe integer range',
|
|
37
39
|
invalid_name: 'a configured name (application, schema, table or file column) breaks its naming rule',
|
|
38
40
|
unknown_column: 'a column the table does not declare, or one this operation may not set',
|
|
39
41
|
unknown_table: 'a table src/db/tables.ts does not declare, or one no store, join or locator reaches',
|
|
@@ -46,19 +48,21 @@ export const QUERY_REFUSALS = {
|
|
|
46
48
|
unexpected_row: 'the database answered a row in another shape than its migration declares',
|
|
47
49
|
statement_shape: 'the compiled statement has a form the guard does not admit',
|
|
48
50
|
scope_predicate: 'the scope predicate is missing or is not a top-level conjunct',
|
|
49
|
-
list_page: 'a list limit
|
|
51
|
+
list_page: 'a list limit or order outside what a page admits',
|
|
52
|
+
list_cursor: "a list's after is not the next cursor of a page of this same list: undecodable, unsigned or edited, of another shape, table or order",
|
|
53
|
+
too_many_rows: 'all() matched more rows than its cap (MAX_ALL_ROWS); it refuses rather than truncate',
|
|
50
54
|
undeclared_reach: 'the site reaches data it did not declare (sql or unscoped, or their mode)',
|
|
51
55
|
sql_template: 'ctx.sql was not called as one tagged template whose values are interpolated whole',
|
|
52
56
|
sql_statement: 'ctx.sql runs one statement of an admitted kind, and none inside another',
|
|
53
57
|
sql_read_only: "sql: 'read' runs queries only; declare sql: 'write' on a mutation, a job or a webhook",
|
|
54
|
-
sql_name: 'ctx.sql names a framework, catalog or foreign-schema object, or writes a name in U& form',
|
|
58
|
+
sql_name: 'ctx.sql names a framework (fabrika_*), catalog (pg_*, sqlite_*) or foreign-schema object, or writes a name in U& form',
|
|
55
59
|
sql_function: 'ctx.sql calls a function that is not a reviewed built-in',
|
|
56
60
|
sql_outside_transaction: 'a job runs ctx.sql only inside ctx.transaction((tx) => …), as tx.sql',
|
|
57
|
-
sql_scope: 'ctx.sql.scope(…)
|
|
61
|
+
sql_scope: 'ctx.sql.scope(…) is interpolated at code level in a statement of its own invocation and site',
|
|
58
62
|
file_scan: "a scan verdict outside the scan job's lease",
|
|
59
63
|
claim_site: 'claim leases rows in a transaction of its own: a job calls it on ctx.db, never inside ctx.transaction or a request',
|
|
60
64
|
on_conflict: "an insert's onConflict names no column of the table, a column the insert leaves empty, or another action",
|
|
61
|
-
public_reach: "a public procedure updates, removes, locks or claims no row, and an insert's conflict writes nothing",
|
|
65
|
+
public_reach: "a public procedure updates, removes, locks or claims no row, reads none with all(), and an insert's conflict writes nothing",
|
|
62
66
|
file_value:
|
|
63
67
|
"a file column takes a file reference this request holds and may read (an incoming file, a put, or a read under the table's read action) of the column's kind, or null",
|
|
64
68
|
file_scope: 'a file is referenced from another top-level scope than the one its first reference set',
|