@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +9 -5
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +51 -2
- package/src/codegen-sqlite.ts +59 -11
- package/src/codegen.ts +181 -42
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/description.ts +55 -9
- package/src/errors.ts +8 -4
- package/src/file-columns.ts +52 -10
- package/src/framework.ts +5 -2
- package/src/guard.ts +365 -15
- package/src/index.ts +8 -0
- package/src/job-leases.ts +19 -2
- package/src/job-wakes.ts +183 -33
- package/src/json.ts +124 -0
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +93 -0
- package/src/migrations.ts +99 -0
- package/src/nodes.ts +21 -6
- package/src/notifications.ts +152 -0
- package/src/orm-types.ts +208 -74
- package/src/orm.ts +369 -147
- package/src/policy.ts +1973 -141
- package/src/push-subscriptions.ts +287 -0
- package/src/registry.ts +50 -1
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +39 -11
- package/src/sqlite-migrate.ts +102 -1
- package/src/sqlite.ts +46 -1
- package/src/store.ts +1933 -168
- package/src/tables.ts +156 -6
- package/src/temporal.ts +8 -1
- package/src/testing-shared.ts +758 -140
- package/src/testing-sqlite.ts +212 -40
- package/src/testing.ts +151 -22
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +50 -2
- package/types/src/codegen-sqlite.d.ts +8 -1
- package/types/src/codegen.d.ts +54 -10
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/description.d.ts +31 -9
- package/types/src/errors.d.ts +7 -4
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +5 -2
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +4 -3
- package/types/src/job-leases.d.ts +8 -1
- package/types/src/job-wakes.d.ts +28 -5
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations.d.ts +5 -0
- package/types/src/nodes.d.ts +4 -0
- package/types/src/notifications.d.ts +37 -0
- package/types/src/orm-types.d.ts +165 -73
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +347 -23
- package/types/src/push-subscriptions.d.ts +49 -0
- package/types/src/registry.d.ts +36 -1
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/sqlite-migrate.d.ts +32 -0
- package/types/src/store.d.ts +118 -31
- package/types/src/tables.d.ts +8 -2
- package/types/src/temporal.d.ts +4 -1
- package/types/src/testing-shared.d.ts +112 -23
- package/types/src/testing-sqlite.d.ts +17 -2
- package/types/src/testing.d.ts +1 -1
- package/types/src/vocabulary-tables.d.ts +169 -22
package/src/orm.ts
CHANGED
|
@@ -6,15 +6,25 @@
|
|
|
6
6
|
import { uuidv7 } from '@fabrika/platform'
|
|
7
7
|
import type { OperationNode } from 'kysely'
|
|
8
8
|
import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
|
|
9
|
+
import { refScope } from './authority'
|
|
9
10
|
import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
|
|
10
11
|
import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
|
|
11
12
|
import type { InvocationTransaction, Session } from './database'
|
|
12
|
-
import {
|
|
13
|
+
import {
|
|
14
|
+
columnOf,
|
|
15
|
+
comparableColumnOf,
|
|
16
|
+
type Compare,
|
|
17
|
+
type Contains,
|
|
18
|
+
parseCondition,
|
|
19
|
+
type Primitive,
|
|
20
|
+
type SelectState,
|
|
21
|
+
type TableShape,
|
|
22
|
+
} from './description'
|
|
13
23
|
import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
|
|
14
24
|
import { answerFiles, type FileBinding } from './file-columns'
|
|
15
25
|
import { databaseNow } from './job-leases'
|
|
16
26
|
import { rearmClaim } from './job-wakes'
|
|
17
|
-
import {
|
|
27
|
+
import { cursorKey, type CursorValue, openCursor, signCursor } from './list-cursor'
|
|
18
28
|
import {
|
|
19
29
|
aggregateNode,
|
|
20
30
|
allOf,
|
|
@@ -33,17 +43,33 @@ import {
|
|
|
33
43
|
withCursorColumns,
|
|
34
44
|
} from './nodes'
|
|
35
45
|
import type { DataKind, TargetForm, UnscopedMode } from './orm-types'
|
|
36
|
-
import {
|
|
46
|
+
import {
|
|
47
|
+
accessTablesOf,
|
|
48
|
+
delegates,
|
|
49
|
+
modelOf,
|
|
50
|
+
namesAction,
|
|
51
|
+
type ReadReach,
|
|
52
|
+
soleReach,
|
|
53
|
+
type TableModels,
|
|
54
|
+
updatableBy,
|
|
55
|
+
visibleFor,
|
|
56
|
+
visibleThrough,
|
|
57
|
+
} from './policy'
|
|
37
58
|
import { type SqlSite, type SqlTag, sqlTag } from './sql'
|
|
38
59
|
import {
|
|
39
60
|
actionShape,
|
|
40
61
|
aggregateRows,
|
|
41
62
|
type AggregateSpec,
|
|
42
63
|
answer,
|
|
64
|
+
appGetScope,
|
|
43
65
|
appKeyPredicate,
|
|
66
|
+
appKeyScope,
|
|
44
67
|
appListPredicate,
|
|
45
|
-
|
|
68
|
+
appListRead,
|
|
69
|
+
type AppRead,
|
|
70
|
+
appRecordRead,
|
|
46
71
|
appRowPredicate,
|
|
72
|
+
appUpdate,
|
|
47
73
|
boundTerms,
|
|
48
74
|
boundValues,
|
|
49
75
|
childObjectPredicate,
|
|
@@ -62,7 +88,7 @@ import {
|
|
|
62
88
|
prepareApplicationInsert,
|
|
63
89
|
prepareChildInsert,
|
|
64
90
|
prepareDimensionInsert,
|
|
65
|
-
|
|
91
|
+
reachedBy,
|
|
66
92
|
reachPredicate,
|
|
67
93
|
readValues,
|
|
68
94
|
removeRow,
|
|
@@ -75,7 +101,6 @@ import {
|
|
|
75
101
|
selfLinks,
|
|
76
102
|
type TableContext,
|
|
77
103
|
updateRow,
|
|
78
|
-
updatingApp,
|
|
79
104
|
updatingRef,
|
|
80
105
|
versionArgument,
|
|
81
106
|
} from './store'
|
|
@@ -84,6 +109,12 @@ import { answerRows, timestampInput } from './temporal'
|
|
|
84
109
|
/** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
|
|
85
110
|
export const DEFAULT_LIST_LIMIT = 50
|
|
86
111
|
export const MAX_LIST_LIMIT = 500
|
|
112
|
+
/**
|
|
113
|
+
* The most rows `all()` answers; past it, it refuses instead of truncating. It bounds rows, not bytes: 10 000 rows of
|
|
114
|
+
* ~1 KB, held two or three times over (driver, answer, response), is tens of MB of the one 128 MB Durable Object
|
|
115
|
+
* isolate every concurrent invocation of the environment shares. Wide rows or a growing set page with `list`.
|
|
116
|
+
*/
|
|
117
|
+
export const MAX_ALL_ROWS = 10_000
|
|
87
118
|
|
|
88
119
|
/** The framework's own tables; no declaration reaches one. */
|
|
89
120
|
const FRAMEWORK_PREFIX = 'fabrika_'
|
|
@@ -109,6 +140,11 @@ export interface DataSite {
|
|
|
109
140
|
* only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
|
|
110
141
|
*/
|
|
111
142
|
readonly files?: FileBinding
|
|
143
|
+
/**
|
|
144
|
+
* The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
|
|
145
|
+
* answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
|
|
146
|
+
*/
|
|
147
|
+
readonly holds?: readonly string[]
|
|
112
148
|
/** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
|
|
113
149
|
readonly carried?: ReadonlySet<string>
|
|
114
150
|
/** Throws unless the work running now is the invocation these handles were made for. */
|
|
@@ -133,6 +169,11 @@ export interface DataHandles {
|
|
|
133
169
|
readonly reference: object
|
|
134
170
|
/** `ctx.db.unscoped`, or `undefined` for a site that declares none. */
|
|
135
171
|
readonly unscoped: object | undefined
|
|
172
|
+
/**
|
|
173
|
+
* At most two rows of `table` whose `column` holds `value`, as an unscoped read answers them: the framework's read of
|
|
174
|
+
* the caller's own row (`ctx.caller` of `@fabrika/app`). No handle of an application reaches it.
|
|
175
|
+
*/
|
|
176
|
+
rowsNaming(table: string, column: string, value: string): Promise<readonly Readonly<Record<string, unknown>>[]>
|
|
136
177
|
}
|
|
137
178
|
|
|
138
179
|
/** The data side of one bound layer, which only the framework reaches (`@fabrika/db/framework`). */
|
|
@@ -176,6 +217,7 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
|
|
|
176
217
|
}
|
|
177
218
|
return scopeTerms(parts.contextOf(table), capability, use)
|
|
178
219
|
},
|
|
220
|
+
accessTablesOf(parts.models),
|
|
179
221
|
)
|
|
180
222
|
},
|
|
181
223
|
})
|
|
@@ -263,6 +305,24 @@ function handlesOf(parts: DataLayerParts, site: DataSite): DataHandles {
|
|
|
263
305
|
},
|
|
264
306
|
reference: referenceTables(parts, site, run),
|
|
265
307
|
unscoped,
|
|
308
|
+
rowsNaming: async (table: string, column: string, value: string) => {
|
|
309
|
+
site.check()
|
|
310
|
+
const model = table.startsWith(FRAMEWORK_PREFIX) ? undefined : modelOf(parts.models, table)
|
|
311
|
+
if (model === undefined) {
|
|
312
|
+
throw new QueryRefusedError('unknown_table', `the caller's table ${table} is not a table of src/db/tables.ts`)
|
|
313
|
+
}
|
|
314
|
+
const keyed = model.scope.mode === 'dimension' || model.scope.mode === 'child' || model.scope.mode === 'app'
|
|
315
|
+
const page = await listRows(
|
|
316
|
+
parts.contextOf(table),
|
|
317
|
+
run,
|
|
318
|
+
everything(),
|
|
319
|
+
model.visible,
|
|
320
|
+
{ where: [[column, '=', value]], limit: 2 },
|
|
321
|
+
keyed ? [keyOf(model)] : model.visible,
|
|
322
|
+
soleReach(model.actions.read[0] ?? ''),
|
|
323
|
+
)
|
|
324
|
+
return page.items
|
|
325
|
+
},
|
|
266
326
|
})
|
|
267
327
|
}
|
|
268
328
|
|
|
@@ -313,7 +373,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
|
|
|
313
373
|
|
|
314
374
|
/** The predicate of the target object, over the whole chain its `Ref` carries. */
|
|
315
375
|
function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
|
|
316
|
-
return
|
|
376
|
+
return refScope(context, context.model, selfLinks(context.model), grant, new Date())
|
|
317
377
|
}
|
|
318
378
|
|
|
319
379
|
function targetRow(
|
|
@@ -327,19 +387,26 @@ function targetRow(
|
|
|
327
387
|
const onOnly = (operation: string) => `${operation} acts on one object: declare access with on`
|
|
328
388
|
const get = bound(site, async () => {
|
|
329
389
|
const grant = namedRef(context, capability, dimension)
|
|
330
|
-
return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), grant.action)
|
|
390
|
+
return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), soleReach(grant.action))
|
|
331
391
|
})
|
|
332
392
|
const lock = bound(site, async () => {
|
|
333
393
|
const grant = namedRef(context, capability, dimension)
|
|
334
394
|
const scope = targetPredicate(context, grant)
|
|
335
395
|
const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
|
|
336
396
|
const session = await run.read()
|
|
337
|
-
const rows = await session.run(node, {
|
|
397
|
+
const rows = await session.run(node, {
|
|
398
|
+
root: 'SelectQueryNode',
|
|
399
|
+
table: context.model.name,
|
|
400
|
+
joins: {},
|
|
401
|
+
scope,
|
|
402
|
+
lock: 'update',
|
|
403
|
+
subqueries: context.subqueries,
|
|
404
|
+
})
|
|
338
405
|
const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
|
|
339
406
|
if (row === undefined) {
|
|
340
407
|
throw new NotFoundError(`${context.model.name} not found`)
|
|
341
408
|
}
|
|
342
|
-
await answerFiles(context.model, run.files, session, [row], grant.action)
|
|
409
|
+
await answerFiles(context.model, run.files, session, [row], soleReach(grant.action))
|
|
343
410
|
return row
|
|
344
411
|
})
|
|
345
412
|
const getForUpdate = site.kind === 'job'
|
|
@@ -372,15 +439,18 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
|
|
|
372
439
|
return freeze({
|
|
373
440
|
list: bound(site, async (options?: unknown) => {
|
|
374
441
|
const grant = namedRef(context, capability, parent)
|
|
375
|
-
return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], grant.action)
|
|
442
|
+
return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
|
|
443
|
+
}),
|
|
444
|
+
all: bound(site, async (options?: unknown) => {
|
|
445
|
+
const grant = namedRef(context, capability, parent)
|
|
446
|
+
return allRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
|
|
376
447
|
}),
|
|
377
448
|
get: bound(site, async (id: unknown) => {
|
|
378
449
|
const grant = namedRef(context, capability, parent)
|
|
379
450
|
if (typeof id !== 'string' || id.length === 0) {
|
|
380
451
|
throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its ${key}, a non-empty string`)
|
|
381
452
|
}
|
|
382
|
-
|
|
383
|
-
return selectOne(context, run, scope, visibleFor(context.model, grant.action), grant.action)
|
|
453
|
+
return selectOne(context, run, parentPredicate(context, grant, id), visibleFor(context.model, grant.action), soleReach(grant.action))
|
|
384
454
|
}),
|
|
385
455
|
insert: writing(
|
|
386
456
|
site,
|
|
@@ -393,8 +463,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
|
|
|
393
463
|
}
|
|
394
464
|
const grant = updatingRef(context, capability, parent)
|
|
395
465
|
const changes = readValues(values, updatableBy(context.model, grant.action), 'update', context.model)
|
|
396
|
-
|
|
397
|
-
return updateRow(context, run, { scope }, changes, versionArgument(context, options))
|
|
466
|
+
return updateRow(context, run, { scope: parentPredicate(context, grant, id) }, changes, versionArgument(context, options))
|
|
398
467
|
}),
|
|
399
468
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
400
469
|
await removeRow(context, run, { scope: childObjectPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
|
|
@@ -407,8 +476,13 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
|
|
|
407
476
|
return freeze({
|
|
408
477
|
list: bound(site, async (options?: unknown) => {
|
|
409
478
|
const grant = namedRef(context, capability, dimension)
|
|
410
|
-
const scope =
|
|
411
|
-
return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
|
|
479
|
+
const scope = refScope(context, context.model, context.model.chain, grant, new Date())
|
|
480
|
+
return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
|
|
481
|
+
}),
|
|
482
|
+
all: bound(site, async (options?: unknown) => {
|
|
483
|
+
const grant = namedRef(context, capability, dimension)
|
|
484
|
+
const scope = refScope(context, context.model, context.model.chain, grant, new Date())
|
|
485
|
+
return allRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
|
|
412
486
|
}),
|
|
413
487
|
insert: writing(
|
|
414
488
|
site,
|
|
@@ -439,9 +513,9 @@ function withinTables(parts: DataLayerParts, site: DataSite, run: Runner, capabi
|
|
|
439
513
|
for (let index = 0; index < tables.length; index++) {
|
|
440
514
|
const model = modelOf(parts.models, tables[index] ?? '')
|
|
441
515
|
const listable = model?.scope.mode === 'dimension' || model?.scope.mode === 'child'
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
setOwn(handle, model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
|
|
516
|
+
const context = model !== undefined && listable ? parts.contextOf(model.name) : undefined
|
|
517
|
+
if (context !== undefined && reachedBy(context, grant.dimension)) {
|
|
518
|
+
setOwn(handle, context.model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
|
|
445
519
|
}
|
|
446
520
|
}
|
|
447
521
|
return freeze(handle)
|
|
@@ -465,7 +539,11 @@ function listedRows(
|
|
|
465
539
|
claim: claiming(parts, context, site, capability),
|
|
466
540
|
list: bound(site, async (options?: unknown) => {
|
|
467
541
|
const predicate = scope()
|
|
468
|
-
return listRows(context, run, predicate, visible(), options, key, heldAction(context, capability))
|
|
542
|
+
return listRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
|
|
543
|
+
}),
|
|
544
|
+
all: bound(site, async (options?: unknown) => {
|
|
545
|
+
const predicate = scope()
|
|
546
|
+
return allRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
|
|
469
547
|
}),
|
|
470
548
|
count: bound(site, async (options?: unknown) => {
|
|
471
549
|
const predicate = scope()
|
|
@@ -495,31 +573,37 @@ function applicationTables(parts: DataLayerParts, site: DataSite, run: Runner, c
|
|
|
495
573
|
const rows = applicationRows(parts, context, site, run, capability)
|
|
496
574
|
setOwn(handle, model.name, site.public === true ? publicApplicationRows(context, site, run, capability, rows) : freeze(rows))
|
|
497
575
|
} else if (site.public !== true && (model.scope.mode === 'dimension' || model.scope.mode === 'child')) {
|
|
498
|
-
setOwn(handle, model.name, appRecordRows(context, site, run, capability
|
|
576
|
+
setOwn(handle, model.name, appRecordRows(context, site, run, capability))
|
|
499
577
|
}
|
|
500
578
|
}
|
|
501
579
|
return freeze(handle)
|
|
502
580
|
}
|
|
503
581
|
|
|
504
582
|
/**
|
|
505
|
-
* A dimension or child table under an `app` capability
|
|
506
|
-
*
|
|
583
|
+
* A dimension or child table under an `app` capability, read-only and every row, with the columns its reaching actions
|
|
584
|
+
* read alone (`visibleThrough`): listed and aggregated with its read action or an action of its `appRead`, counted with
|
|
507
585
|
* those or an action of its `appCount`.
|
|
508
586
|
*/
|
|
509
|
-
function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown
|
|
510
|
-
const
|
|
511
|
-
const
|
|
512
|
-
const key = [keyOf(context.model)]
|
|
587
|
+
function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown): object {
|
|
588
|
+
const model = context.model
|
|
589
|
+
const key = [keyOf(model)]
|
|
513
590
|
return freeze({
|
|
514
|
-
list: bound(
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
),
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
)
|
|
591
|
+
list: bound(site, async (options?: unknown) => {
|
|
592
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
593
|
+
return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
594
|
+
}),
|
|
595
|
+
all: bound(site, async (options?: unknown) => {
|
|
596
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
597
|
+
return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
598
|
+
}),
|
|
599
|
+
count: bound(site, async (options?: unknown) => {
|
|
600
|
+
const { predicate, reach } = appRecordRead(context, capability, 'counts')
|
|
601
|
+
return countRows(context, run, predicate, visibleThrough(model, reach), options)
|
|
602
|
+
}),
|
|
603
|
+
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
|
|
604
|
+
const { predicate, reach } = appRecordRead(context, capability, 'rows')
|
|
605
|
+
return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
|
|
606
|
+
}),
|
|
523
607
|
})
|
|
524
608
|
}
|
|
525
609
|
|
|
@@ -543,30 +627,55 @@ function scopedApplicationRows(context: TableContext, site: DataSite, run: Runne
|
|
|
543
627
|
const key = [keyOf(model)]
|
|
544
628
|
const scope = () => scopedApplicationRead(context, capability)
|
|
545
629
|
return freeze({
|
|
546
|
-
list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, heldAction(context, capability))),
|
|
630
|
+
list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
|
|
631
|
+
all: bound(site, async (options?: unknown) => allRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
|
|
547
632
|
count: bound(site, async (options?: unknown) => countRows(context, run, scope(), visible, options)),
|
|
548
633
|
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, scope(), context.shape, spec)),
|
|
549
|
-
get: bound(
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
634
|
+
get: bound(
|
|
635
|
+
site,
|
|
636
|
+
async (id: unknown) =>
|
|
637
|
+
selectOne(
|
|
638
|
+
context,
|
|
639
|
+
run,
|
|
640
|
+
scopedApplicationRead(context, capability, appKeyPredicate(model, id)),
|
|
641
|
+
visible,
|
|
642
|
+
soleReach(heldAction(context, capability)),
|
|
643
|
+
),
|
|
644
|
+
),
|
|
553
645
|
})
|
|
554
646
|
}
|
|
555
647
|
|
|
556
|
-
/**
|
|
557
|
-
|
|
648
|
+
/**
|
|
649
|
+
* The row `key` names, for an `app` capability with an action the application table names, or any but a public
|
|
650
|
+
* procedure's on a table read with `'any'`: within the conditions of the actions it holds that the table names, any one
|
|
651
|
+
* admitting the row, and with the columns they read alone (`visibleThrough`).
|
|
652
|
+
*/
|
|
653
|
+
function namedAppRead(context: TableContext, capability: unknown, key: unknown): AppRead {
|
|
558
654
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
559
|
-
const
|
|
655
|
+
const model = context.model
|
|
656
|
+
const table = model.name
|
|
560
657
|
if (grant.kind !== 'app') {
|
|
561
658
|
throw new CapabilityError('wrong_capability', `a read of ${table} here needs the capability of an app endpoint, got ${describeGrant(grant)}`)
|
|
562
659
|
}
|
|
563
|
-
if (
|
|
660
|
+
if (model.actions.readAny) {
|
|
661
|
+
// Refuses a public procedure's grant, which reads no table read with 'any'.
|
|
662
|
+
appListPredicate(context, capability)
|
|
663
|
+
return { predicate: appGetScope(model, grant.actions, key), reach: freeze({ actions: grant.actions, narrowed: false }) }
|
|
664
|
+
}
|
|
665
|
+
const named: string[] = []
|
|
666
|
+
for (let index = 0; index < grant.actions.length; index++) {
|
|
667
|
+
const action = grant.actions[index]
|
|
668
|
+
if (action !== undefined && namesAction(model, action)) {
|
|
669
|
+
named[named.length] = action
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
if (named.length === 0) {
|
|
564
673
|
throw new CapabilityError(
|
|
565
674
|
'wrong_action',
|
|
566
|
-
`${table} does not name the action '${grant.
|
|
675
|
+
`${table} does not name the action '${grant.actions.join("', '")}': read it from an app endpoint whose action ${table} names`,
|
|
567
676
|
)
|
|
568
677
|
}
|
|
569
|
-
return
|
|
678
|
+
return { predicate: appGetScope(model, named, key), reach: freeze({ actions: named, narrowed: true }) }
|
|
570
679
|
}
|
|
571
680
|
|
|
572
681
|
/**
|
|
@@ -582,39 +691,43 @@ function applicationRows(
|
|
|
582
691
|
): Readonly<Record<string, unknown>> {
|
|
583
692
|
const model = context.model
|
|
584
693
|
const table = model.name
|
|
585
|
-
const visible = () => visibleFor(model, heldAction(context, capability))
|
|
586
694
|
const key = [keyOf(model)]
|
|
587
695
|
const getForUpdate = site.kind === 'job'
|
|
588
696
|
? refused(site, 'read_only', 'a job writes inside ctx.transaction((tx) => …): use tx.db there')
|
|
589
697
|
: site.kind === 'query'
|
|
590
698
|
? refused(site, 'read_only', 'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation')
|
|
591
699
|
: bound(site, async (id: unknown) => {
|
|
592
|
-
const scope =
|
|
593
|
-
const
|
|
594
|
-
const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
|
|
700
|
+
const { predicate: scope, reach } = namedAppRead(context, capability, id)
|
|
701
|
+
const node = lockedSelectNode(table, visibleThrough(model, reach), scope, model.dates)
|
|
595
702
|
const session = await run.read()
|
|
596
|
-
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
|
|
703
|
+
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update', subqueries: context.subqueries })
|
|
597
704
|
const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
|
|
598
705
|
if (row === undefined) {
|
|
599
706
|
throw new NotFoundError(`${table} not found`)
|
|
600
707
|
}
|
|
601
|
-
await answerFiles(model, run.files, session, [row],
|
|
708
|
+
await answerFiles(model, run.files, session, [row], reach)
|
|
602
709
|
return row
|
|
603
710
|
})
|
|
604
711
|
return {
|
|
605
|
-
list: bound(
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
)
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
712
|
+
list: bound(site, async (options?: unknown) => {
|
|
713
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
714
|
+
return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
715
|
+
}),
|
|
716
|
+
all: bound(site, async (options?: unknown) => {
|
|
717
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
718
|
+
return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
|
|
719
|
+
}),
|
|
720
|
+
count: bound(site, async (options?: unknown) => {
|
|
721
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
722
|
+
return countRows(context, run, predicate, visibleThrough(model, reach), options)
|
|
723
|
+
}),
|
|
724
|
+
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
|
|
725
|
+
const { predicate, reach } = appListRead(context, capability)
|
|
726
|
+
return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
|
|
727
|
+
}),
|
|
615
728
|
get: bound(site, async (id: unknown) => {
|
|
616
|
-
const
|
|
617
|
-
return selectOne(context, run,
|
|
729
|
+
const { predicate, reach } = namedAppRead(context, capability, id)
|
|
730
|
+
return selectOne(context, run, predicate, visibleThrough(model, reach), reach)
|
|
618
731
|
}),
|
|
619
732
|
getForUpdate,
|
|
620
733
|
claim: claiming(parts, context, site, capability),
|
|
@@ -624,9 +737,8 @@ function applicationRows(
|
|
|
624
737
|
async (values: unknown, options?: unknown) => insertPrepared(context, run, prepareApplicationInsert(context, capability, values, options)),
|
|
625
738
|
),
|
|
626
739
|
update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
|
|
627
|
-
const
|
|
628
|
-
|
|
629
|
-
return updateRow(context, run, { scope: appKeyPredicate(model, id) }, changes, versionArgument(context, options))
|
|
740
|
+
const { scope, changes } = appUpdate(context, capability, id, values)
|
|
741
|
+
return updateRow(context, run, { scope }, changes, versionArgument(context, options))
|
|
630
742
|
}),
|
|
631
743
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
632
744
|
await removeRow(context, run, { scope: appRowPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
|
|
@@ -663,26 +775,24 @@ function publicApplicationRows(
|
|
|
663
775
|
}
|
|
664
776
|
return freeze({
|
|
665
777
|
list: rows['list'],
|
|
778
|
+
all: bound(site, async () => {
|
|
779
|
+
// The table's own read refusal first, as list answers it, so the message never points to a list it refuses too.
|
|
780
|
+
appListPredicate(context, capability)
|
|
781
|
+
throw new QueryRefusedError('public_reach', 'a public procedure pages its reads: read the table with list')
|
|
782
|
+
}),
|
|
666
783
|
count: rows['count'],
|
|
667
784
|
aggregate: rows['aggregate'],
|
|
668
785
|
get: bound(site, async (id: unknown) => {
|
|
669
786
|
appListPredicate(context, capability)
|
|
670
787
|
const action = heldAction(context, capability)
|
|
671
|
-
return selectOne(context, run,
|
|
788
|
+
return selectOne(context, run, appKeyScope(model, [action], id), visibleFor(model, action), soleReach(action))
|
|
672
789
|
}),
|
|
673
790
|
getForUpdate: refusal('lock'),
|
|
674
791
|
claim: refusal('claim'),
|
|
675
792
|
update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
|
|
676
793
|
tokenRow('update', id)
|
|
677
|
-
const
|
|
678
|
-
const
|
|
679
|
-
const saved = await updateRow<Readonly<Record<string, unknown>>>(
|
|
680
|
-
context,
|
|
681
|
-
run,
|
|
682
|
-
{ scope: appKeyPredicate(model, id) },
|
|
683
|
-
changes,
|
|
684
|
-
versionArgument(context, options),
|
|
685
|
-
)
|
|
794
|
+
const { scope, changes } = appUpdate(context, capability, id, values)
|
|
795
|
+
const saved = await updateRow<Readonly<Record<string, unknown>>>(context, run, { scope }, changes, versionArgument(context, options))
|
|
686
796
|
return freeze({ version: saved['version'] })
|
|
687
797
|
}),
|
|
688
798
|
remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
|
|
@@ -708,6 +818,17 @@ const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
|
|
|
708
818
|
/** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
|
|
709
819
|
const CLAIM_REARM_MIN_MS = 1_000
|
|
710
820
|
|
|
821
|
+
/**
|
|
822
|
+
* When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
|
|
823
|
+
* at the next due row it would take but no sooner than a second after it, or never when it would take none.
|
|
824
|
+
*/
|
|
825
|
+
export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
|
|
826
|
+
if (full) {
|
|
827
|
+
return new Date(now.getTime() + 1)
|
|
828
|
+
}
|
|
829
|
+
return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
|
|
830
|
+
}
|
|
831
|
+
|
|
711
832
|
/** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
|
|
712
833
|
function backoffMs(tickMs: number, attempts: number): number {
|
|
713
834
|
let backoff = tickMs
|
|
@@ -741,6 +862,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
|
|
|
741
862
|
return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
|
|
742
863
|
}
|
|
743
864
|
|
|
865
|
+
/**
|
|
866
|
+
* How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
|
|
867
|
+
* compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
|
|
868
|
+
* statement's size. Every chunk runs in the claim's one fenced transaction.
|
|
869
|
+
*/
|
|
870
|
+
const CLAIM_UPDATE_IDS = 50
|
|
871
|
+
|
|
744
872
|
/**
|
|
745
873
|
* Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
|
|
746
874
|
* attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
|
|
@@ -755,7 +883,7 @@ async function claimRows(
|
|
|
755
883
|
): Promise<readonly Readonly<Record<string, unknown>>[]> {
|
|
756
884
|
const model = context.model
|
|
757
885
|
const table = model.name
|
|
758
|
-
const { grant, scope } = claimScope(context, capability)
|
|
886
|
+
const { grant, action, scope } = claimScope(context, capability)
|
|
759
887
|
const queue = model.queue
|
|
760
888
|
const version = model.version
|
|
761
889
|
if (queue === undefined || version === undefined) {
|
|
@@ -766,9 +894,9 @@ async function claimRows(
|
|
|
766
894
|
throw new QueryRefusedError('list_page', 'claim takes { limit }: attempts count claims, so claim only what the run will reach')
|
|
767
895
|
}
|
|
768
896
|
const limit = limitOf(options['limit'])
|
|
769
|
-
const visible = visibleFor(model,
|
|
897
|
+
const visible = visibleFor(model, action)
|
|
770
898
|
const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
|
|
771
|
-
if (scope === undefined) {
|
|
899
|
+
if (scope === undefined || conditions === undefined) {
|
|
772
900
|
return []
|
|
773
901
|
}
|
|
774
902
|
const dialect = dialectOf(context)
|
|
@@ -783,7 +911,14 @@ async function claimRows(
|
|
|
783
911
|
const now = await databaseNow(session)
|
|
784
912
|
const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
|
|
785
913
|
const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
|
|
786
|
-
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
914
|
+
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
915
|
+
root: 'SelectQueryNode',
|
|
916
|
+
table,
|
|
917
|
+
joins: {},
|
|
918
|
+
scope,
|
|
919
|
+
lock: 'claim',
|
|
920
|
+
subqueries: context.subqueries,
|
|
921
|
+
})
|
|
787
922
|
const byAttempts = new Map<number, string[]>()
|
|
788
923
|
for (const row of rows) {
|
|
789
924
|
const attempts = row[queue.attempts]
|
|
@@ -797,37 +932,56 @@ async function claimRows(
|
|
|
797
932
|
for (const [attempts, ids] of byAttempts) {
|
|
798
933
|
const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
|
|
799
934
|
const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
const
|
|
807
|
-
|
|
808
|
-
|
|
935
|
+
for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
|
|
936
|
+
const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
|
|
937
|
+
const updated = await session.run<Readonly<Record<string, unknown>>>(
|
|
938
|
+
updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
|
|
939
|
+
{ root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
|
|
940
|
+
)
|
|
941
|
+
for (const row of updated) {
|
|
942
|
+
const id = row['id']
|
|
943
|
+
const next = row['version']
|
|
944
|
+
if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
|
|
945
|
+
throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
|
|
946
|
+
}
|
|
947
|
+
claimed.set(id, { version: next, attempts: attempts + 1, due })
|
|
809
948
|
}
|
|
810
|
-
claimed.set(id, { version: next, attempts: attempts + 1, due })
|
|
811
949
|
}
|
|
812
950
|
}
|
|
813
951
|
// The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
|
|
814
952
|
const fence = runtime.capabilities.fence()
|
|
815
953
|
if (fence !== null && rows.length > 0) {
|
|
816
|
-
|
|
817
|
-
let
|
|
818
|
-
if (
|
|
954
|
+
const full = rows.length >= limit
|
|
955
|
+
let next: Date | null = null
|
|
956
|
+
if (!full) {
|
|
819
957
|
const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
|
|
820
958
|
const [row] = answerRows(
|
|
821
959
|
dialect,
|
|
822
960
|
table,
|
|
823
961
|
rowColumnsOf(model),
|
|
824
|
-
await session.run<Readonly<Record<string, unknown>>>(later, {
|
|
962
|
+
await session.run<Readonly<Record<string, unknown>>>(later, {
|
|
963
|
+
root: 'SelectQueryNode',
|
|
964
|
+
table,
|
|
965
|
+
joins: {},
|
|
966
|
+
scope,
|
|
967
|
+
subqueries: context.subqueries,
|
|
968
|
+
}),
|
|
825
969
|
)
|
|
826
|
-
|
|
970
|
+
next = row === undefined ? null : dueOf(row, table, queue.due)
|
|
827
971
|
}
|
|
828
|
-
await rearmClaim(runtime, session, fence,
|
|
972
|
+
await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
|
|
973
|
+
}
|
|
974
|
+
return {
|
|
975
|
+
rows: await answerFiles(
|
|
976
|
+
model,
|
|
977
|
+
site.files,
|
|
978
|
+
session,
|
|
979
|
+
answerRows(dialect, table, rowColumnsOf(model), rows),
|
|
980
|
+
soleReach(action),
|
|
981
|
+
nameSet(site.holds ?? []),
|
|
982
|
+
),
|
|
983
|
+
claimed,
|
|
829
984
|
}
|
|
830
|
-
return { rows: await answerFiles(model, site.files, session, answerRows(dialect, table, rowColumnsOf(model), rows), grant.action), claimed }
|
|
831
985
|
})
|
|
832
986
|
return leased.rows.map((row) => {
|
|
833
987
|
const id = String(row[key])
|
|
@@ -839,7 +993,7 @@ async function claimRows(
|
|
|
839
993
|
for (const name of chain) {
|
|
840
994
|
links.set(name, String(row[name]))
|
|
841
995
|
}
|
|
842
|
-
const ref = runtimeOf(context.connection).capabilities.row({ table, action
|
|
996
|
+
const ref = runtimeOf(context.connection).capabilities.row({ table, action, principal: grant.principal, id, chain: links })
|
|
843
997
|
const answered: Record<string, unknown> = {}
|
|
844
998
|
for (const name of visible) {
|
|
845
999
|
setOwn(answered, name, row[name])
|
|
@@ -923,6 +1077,7 @@ function referenceTables(parts: DataLayerParts, site: DataSite, run: Runner): ob
|
|
|
923
1077
|
model.name,
|
|
924
1078
|
freeze({
|
|
925
1079
|
list: bound(site, async (options?: unknown) => listRows(context, run, everything(), model.visible, options, model.visible)),
|
|
1080
|
+
all: bound(site, async (options?: unknown) => allRows(context, run, everything(), model.visible, options, model.visible)),
|
|
926
1081
|
count: bound(site, async (options?: unknown) => countRows(context, run, everything(), model.visible, options)),
|
|
927
1082
|
}),
|
|
928
1083
|
)
|
|
@@ -972,6 +1127,17 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
972
1127
|
return equals(table, keyOf(model), id)
|
|
973
1128
|
}
|
|
974
1129
|
const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
|
|
1130
|
+
if (model.view) {
|
|
1131
|
+
return refused(site, 'read_only', `${table} is a view, which no handler writes`)
|
|
1132
|
+
}
|
|
1133
|
+
// A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
|
|
1134
|
+
if (delegates(model) || context.writers.length > 0) {
|
|
1135
|
+
return refused(
|
|
1136
|
+
site,
|
|
1137
|
+
'undeclared_reach',
|
|
1138
|
+
`${table} hands out access, so it is written through a capability only, never unscoped`,
|
|
1139
|
+
)
|
|
1140
|
+
}
|
|
975
1141
|
if (mode === 'read') {
|
|
976
1142
|
const verb = operation === 'remove' ? 'remove' : operation
|
|
977
1143
|
return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
|
|
@@ -981,7 +1147,11 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
981
1147
|
return freeze({
|
|
982
1148
|
list: bound(
|
|
983
1149
|
site,
|
|
984
|
-
async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, unscopedRead),
|
|
1150
|
+
async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
|
|
1151
|
+
),
|
|
1152
|
+
all: bound(
|
|
1153
|
+
site,
|
|
1154
|
+
async (options?: unknown) => allRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
|
|
985
1155
|
),
|
|
986
1156
|
count: bound(site, async (options?: unknown) => countRows(context, run, everything(), visible, options)),
|
|
987
1157
|
aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
|
|
@@ -990,12 +1160,12 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
990
1160
|
const dialect = dialectOf(context)
|
|
991
1161
|
const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
|
|
992
1162
|
const session = await run.read()
|
|
993
|
-
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
|
|
1163
|
+
const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
|
|
994
1164
|
const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
|
|
995
1165
|
if (row === undefined) {
|
|
996
1166
|
throw new NotFoundError(`${table} not found`)
|
|
997
1167
|
}
|
|
998
|
-
await answerFiles(model, run.files, session, [row], unscopedRead)
|
|
1168
|
+
await answerFiles(model, run.files, session, [row], soleReach(unscopedRead))
|
|
999
1169
|
return row
|
|
1000
1170
|
}),
|
|
1001
1171
|
insert: write('insert', async (values: unknown) => insertUnscoped(context, run, site.principal, values)),
|
|
@@ -1076,21 +1246,37 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
|
|
|
1076
1246
|
return read
|
|
1077
1247
|
}
|
|
1078
1248
|
|
|
1079
|
-
/**
|
|
1080
|
-
|
|
1249
|
+
/**
|
|
1250
|
+
* A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). Undefined when a condition is an
|
|
1251
|
+
* `in` with an empty list: it matches no row, so the read answers nothing and sends no statement, as an empty `Within`.
|
|
1252
|
+
*/
|
|
1253
|
+
function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] | undefined {
|
|
1081
1254
|
if (where === undefined) {
|
|
1082
1255
|
return []
|
|
1083
1256
|
}
|
|
1084
|
-
const
|
|
1257
|
+
const parsed = parseList(where, (condition): Compare | Contains | undefined => {
|
|
1085
1258
|
const parts = parseList(condition, (part) => part)
|
|
1086
1259
|
if (parts === undefined || parts.length !== 3) {
|
|
1087
1260
|
throw new QueryRefusedError('invalid_argument', 'where takes [column, operator, value] conditions, each a plain array')
|
|
1088
1261
|
}
|
|
1262
|
+
if (parts[1] === 'in' && parseList(parts[2], (item) => item)?.length === 0) {
|
|
1263
|
+
// The column is still held to the capability's columns: an empty list does not make a hidden one nameable.
|
|
1264
|
+
comparableColumnOf(shape, parts[0], 'compares')
|
|
1265
|
+
return undefined
|
|
1266
|
+
}
|
|
1089
1267
|
return parseCondition(shape, parts[0], parts[1], parts[2])
|
|
1090
1268
|
})
|
|
1091
|
-
if (
|
|
1269
|
+
if (parsed === undefined) {
|
|
1092
1270
|
throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
|
|
1093
1271
|
}
|
|
1272
|
+
const conditions: (Compare | Contains)[] = []
|
|
1273
|
+
for (let index = 0; index < parsed.length; index++) {
|
|
1274
|
+
const condition = parsed[index]
|
|
1275
|
+
if (condition === undefined) {
|
|
1276
|
+
return undefined
|
|
1277
|
+
}
|
|
1278
|
+
conditions[index] = condition
|
|
1279
|
+
}
|
|
1094
1280
|
return boundTerms(context, context.model, conditions)
|
|
1095
1281
|
}
|
|
1096
1282
|
|
|
@@ -1101,7 +1287,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
|
|
|
1101
1287
|
if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
|
|
1102
1288
|
throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
|
|
1103
1289
|
}
|
|
1104
|
-
return { column:
|
|
1290
|
+
return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
|
|
1105
1291
|
})
|
|
1106
1292
|
if (terms === undefined) {
|
|
1107
1293
|
throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
|
|
@@ -1129,14 +1315,21 @@ function limitOf(limit: unknown): number {
|
|
|
1129
1315
|
}
|
|
1130
1316
|
|
|
1131
1317
|
function rowState(table: string, conditions: readonly (Compare | Contains)[], order: readonly OrderColumn[], limit: number | undefined): SelectState {
|
|
1132
|
-
return { origin: freeze({}), table, columns: undefined, conditions, orderBy: order, limit, offset: undefined, joins: [] }
|
|
1318
|
+
return { origin: freeze({}), table, columns: undefined, conditions, orderBy: order, limit, offset: undefined, joins: [], matchesNone: false }
|
|
1133
1319
|
}
|
|
1134
1320
|
|
|
1135
|
-
/**
|
|
1136
|
-
|
|
1321
|
+
/** The list a cursor belongs to, as its signature covers it: its table and its whole order, the tiebreak included. */
|
|
1322
|
+
function cursorList(table: string, order: readonly OrderColumn[]): string {
|
|
1323
|
+
return JSON.stringify([table, order.map((term) => [term.column, term.direction])])
|
|
1324
|
+
}
|
|
1137
1325
|
|
|
1138
|
-
/** A page's position: the text of its last row's order columns (`keyset.c<n>`),
|
|
1139
|
-
function encodeCursor(
|
|
1326
|
+
/** A page's position: the text of its last row's order columns (`keyset.c<n>`), signed for its list. */
|
|
1327
|
+
async function encodeCursor(
|
|
1328
|
+
key: () => Promise<CryptoKey>,
|
|
1329
|
+
table: string,
|
|
1330
|
+
row: Readonly<Record<string, unknown>>,
|
|
1331
|
+
order: readonly OrderColumn[],
|
|
1332
|
+
): Promise<string> {
|
|
1140
1333
|
const values: CursorValue[] = order.map(({ column: name }, index) => {
|
|
1141
1334
|
const value = hasOwn(row, cursorAlias(index)) ? row[cursorAlias(index)] : null
|
|
1142
1335
|
if (typeof value === 'string' || value === null) {
|
|
@@ -1144,7 +1337,7 @@ function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly Or
|
|
|
1144
1337
|
}
|
|
1145
1338
|
throw new QueryRefusedError('list_page', `${name} came back as ${typeof value} text, which a list cannot page by`)
|
|
1146
1339
|
})
|
|
1147
|
-
return
|
|
1340
|
+
return await signCursor(key, cursorList(table, order), values)
|
|
1148
1341
|
}
|
|
1149
1342
|
|
|
1150
1343
|
/** A row as the caller sees it: the position columns stay the layer's. */
|
|
@@ -1161,30 +1354,6 @@ function withoutCursor(row: Readonly<Record<string, unknown>>, order: readonly O
|
|
|
1161
1354
|
return item
|
|
1162
1355
|
}
|
|
1163
1356
|
|
|
1164
|
-
/** The cursor `after` names, parsed at the boundary: one plain value per order column. */
|
|
1165
|
-
function decodeCursor(after: unknown, order: readonly OrderColumn[]): readonly CursorValue[] {
|
|
1166
|
-
const refused = () => new QueryRefusedError('list_page', 'after takes the next cursor of a page of this same list')
|
|
1167
|
-
if (typeof after !== 'string' || after.length === 0) {
|
|
1168
|
-
throw refused()
|
|
1169
|
-
}
|
|
1170
|
-
let parsed: unknown
|
|
1171
|
-
try {
|
|
1172
|
-
parsed = JSON.parse(Buffer.from(after, 'base64url').toString('utf8'))
|
|
1173
|
-
} catch {
|
|
1174
|
-
throw refused()
|
|
1175
|
-
}
|
|
1176
|
-
const values = parseList(parsed, (value): CursorValue => {
|
|
1177
|
-
if (typeof value === 'string' || value === null) {
|
|
1178
|
-
return value
|
|
1179
|
-
}
|
|
1180
|
-
throw refused()
|
|
1181
|
-
})
|
|
1182
|
-
if (values === undefined || values.length !== order.length) {
|
|
1183
|
-
throw refused()
|
|
1184
|
-
}
|
|
1185
|
-
return values
|
|
1186
|
-
}
|
|
1187
|
-
|
|
1188
1357
|
function compare(table: string, name: string, operator: '>' | '<' | '=', value: Primitive): OperationNode {
|
|
1189
1358
|
return BinaryOperationNode.create(column(table, name), OperatorNode.create(operator), ValueNode.create(value))
|
|
1190
1359
|
}
|
|
@@ -1229,7 +1398,7 @@ async function listRows(
|
|
|
1229
1398
|
visible: readonly string[],
|
|
1230
1399
|
input: unknown,
|
|
1231
1400
|
tiebreak: readonly string[],
|
|
1232
|
-
|
|
1401
|
+
reach?: ReadReach,
|
|
1233
1402
|
): Promise<{ readonly items: Readonly<Record<string, unknown>>[]; readonly next: string | null }> {
|
|
1234
1403
|
const table = context.model.name
|
|
1235
1404
|
const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
|
|
@@ -1237,8 +1406,14 @@ async function listRows(
|
|
|
1237
1406
|
const conditions = conditionsOf(context, shape, options['where'])
|
|
1238
1407
|
const order = orderOf(shape, options['orderBy'], tiebreak)
|
|
1239
1408
|
const limit = limitOf(options['limit'])
|
|
1240
|
-
const
|
|
1241
|
-
|
|
1409
|
+
const session = await run.read()
|
|
1410
|
+
// Read once per page, whether the page verifies `after`, signs `next` or both.
|
|
1411
|
+
let read: Promise<CryptoKey> | undefined
|
|
1412
|
+
const key = (): Promise<CryptoKey> => (read ??= cursorKey(session))
|
|
1413
|
+
const position = options['after'] === undefined
|
|
1414
|
+
? undefined
|
|
1415
|
+
: keysetAfter(table, order, await openCursor(key, cursorList(table, order), options['after'], order.length))
|
|
1416
|
+
if (scope === undefined || conditions === undefined) {
|
|
1242
1417
|
return { items: [], next: null }
|
|
1243
1418
|
}
|
|
1244
1419
|
const dialect = dialectOf(context)
|
|
@@ -1247,22 +1422,62 @@ async function listRows(
|
|
|
1247
1422
|
table,
|
|
1248
1423
|
order.map((term) => term.column),
|
|
1249
1424
|
)
|
|
1250
|
-
const session = await run.read()
|
|
1251
1425
|
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
1252
1426
|
root: 'SelectQueryNode',
|
|
1253
1427
|
table,
|
|
1254
1428
|
joins: {},
|
|
1255
1429
|
scope,
|
|
1430
|
+
subqueries: context.subqueries,
|
|
1431
|
+
through: context.through,
|
|
1256
1432
|
})
|
|
1257
1433
|
const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
|
|
1258
1434
|
const last = page[page.length - 1]
|
|
1259
1435
|
const items = page.map((row) => withoutCursor(row, order))
|
|
1260
1436
|
return {
|
|
1261
|
-
items:
|
|
1262
|
-
next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
|
|
1437
|
+
items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
|
|
1438
|
+
next: rows.length > limit && last !== undefined ? await encodeCursor(key, table, last, order) : null,
|
|
1263
1439
|
}
|
|
1264
1440
|
}
|
|
1265
1441
|
|
|
1442
|
+
/**
|
|
1443
|
+
* Every row of a read in one statement, in the order asked with the tiebreak last, or a refusal when more than
|
|
1444
|
+
* `MAX_ALL_ROWS` match: it never answers a truncated set.
|
|
1445
|
+
*/
|
|
1446
|
+
async function allRows(
|
|
1447
|
+
context: TableContext,
|
|
1448
|
+
run: Runner,
|
|
1449
|
+
scope: OperationNode | undefined,
|
|
1450
|
+
visible: readonly string[],
|
|
1451
|
+
input: unknown,
|
|
1452
|
+
tiebreak: readonly string[],
|
|
1453
|
+
reach?: ReadReach,
|
|
1454
|
+
): Promise<Readonly<Record<string, unknown>>[]> {
|
|
1455
|
+
const table = context.model.name
|
|
1456
|
+
const options = readOptions(input, ['where', 'orderBy'], 'all')
|
|
1457
|
+
const shape = actionShape(context.model, visible)
|
|
1458
|
+
const conditions = conditionsOf(context, shape, options['where'])
|
|
1459
|
+
const order = orderOf(shape, options['orderBy'], tiebreak)
|
|
1460
|
+
if (scope === undefined || conditions === undefined) {
|
|
1461
|
+
return []
|
|
1462
|
+
}
|
|
1463
|
+
const dialect = dialectOf(context)
|
|
1464
|
+
const node = selectNode(rowState(table, conditions, order, MAX_ALL_ROWS + 1), visible, scope, undefined, context.model.dates, dialect)
|
|
1465
|
+
const session = await run.read()
|
|
1466
|
+
const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
|
|
1467
|
+
root: 'SelectQueryNode',
|
|
1468
|
+
table,
|
|
1469
|
+
joins: {},
|
|
1470
|
+
scope,
|
|
1471
|
+
subqueries: context.subqueries,
|
|
1472
|
+
through: context.through,
|
|
1473
|
+
})
|
|
1474
|
+
if (rows.length > MAX_ALL_ROWS) {
|
|
1475
|
+
throw new QueryRefusedError('too_many_rows', `all() of ${table} matches more than ${MAX_ALL_ROWS} rows: narrow it with where, or page it with list`)
|
|
1476
|
+
}
|
|
1477
|
+
const items = answerRows(dialect, table, rowColumnsOf(context.model), rows)
|
|
1478
|
+
return reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach)
|
|
1479
|
+
}
|
|
1480
|
+
|
|
1266
1481
|
async function countRows(
|
|
1267
1482
|
context: TableContext,
|
|
1268
1483
|
run: Runner,
|
|
@@ -1273,11 +1488,18 @@ async function countRows(
|
|
|
1273
1488
|
const table = context.model.name
|
|
1274
1489
|
const options = readOptions(input, ['where'], 'count')
|
|
1275
1490
|
const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
|
|
1276
|
-
if (scope === undefined) {
|
|
1491
|
+
if (scope === undefined || conditions === undefined) {
|
|
1277
1492
|
return 0
|
|
1278
1493
|
}
|
|
1279
1494
|
const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
|
|
1280
|
-
const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
|
|
1495
|
+
const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
|
|
1496
|
+
root: 'SelectQueryNode',
|
|
1497
|
+
table,
|
|
1498
|
+
joins: {},
|
|
1499
|
+
scope,
|
|
1500
|
+
subqueries: context.subqueries,
|
|
1501
|
+
through: context.through,
|
|
1502
|
+
})
|
|
1281
1503
|
const count = row === undefined ? '0' : row['count']
|
|
1282
1504
|
return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
|
|
1283
1505
|
}
|