@fabrika/db 0.9.0-dev.7 → 0.9.0-dev.70

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +69 -13
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +67 -9
  10. package/src/errors.ts +9 -5
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +187 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +33 -14
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +216 -77
  24. package/src/orm.ts +417 -158
  25. package/src/policy.ts +2043 -131
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-migrate.ts +102 -1
  31. package/src/sqlite.ts +46 -1
  32. package/src/store.ts +1958 -167
  33. package/src/tables.ts +156 -6
  34. package/src/temporal.ts +39 -4
  35. package/src/testing-shared.ts +872 -148
  36. package/src/testing-sqlite.ts +215 -40
  37. package/src/testing.ts +151 -22
  38. package/src/vocabulary-tables.ts +172 -26
  39. package/types/src/authority.d.ts +147 -0
  40. package/types/src/builtins.d.ts +2 -0
  41. package/types/src/capability.d.ts +50 -2
  42. package/types/src/codegen-sqlite.d.ts +8 -1
  43. package/types/src/codegen.d.ts +54 -10
  44. package/types/src/condition-nodes.d.ts +9 -0
  45. package/types/src/conditions.d.ts +151 -0
  46. package/types/src/description.d.ts +40 -9
  47. package/types/src/errors.d.ts +8 -5
  48. package/types/src/file-columns.d.ts +6 -4
  49. package/types/src/framework.d.ts +5 -2
  50. package/types/src/guard.d.ts +24 -0
  51. package/types/src/index.d.ts +4 -3
  52. package/types/src/job-leases.d.ts +8 -1
  53. package/types/src/job-wakes.d.ts +28 -5
  54. package/types/src/json.d.ts +35 -0
  55. package/types/src/list-cursor.d.ts +13 -0
  56. package/types/src/migrations.d.ts +5 -0
  57. package/types/src/nodes.d.ts +5 -1
  58. package/types/src/notifications.d.ts +37 -0
  59. package/types/src/orm-types.d.ts +167 -75
  60. package/types/src/orm.d.ts +21 -0
  61. package/types/src/policy.d.ts +378 -27
  62. package/types/src/push-subscriptions.d.ts +49 -0
  63. package/types/src/registry.d.ts +36 -1
  64. package/types/src/request-receipts.d.ts +22 -0
  65. package/types/src/sql.d.ts +2 -2
  66. package/types/src/sqlite-migrate.d.ts +32 -0
  67. package/types/src/store.d.ts +118 -31
  68. package/types/src/tables.d.ts +8 -2
  69. package/types/src/temporal.d.ts +7 -1
  70. package/types/src/testing-shared.d.ts +125 -26
  71. package/types/src/testing-sqlite.d.ts +17 -2
  72. package/types/src/testing.d.ts +1 -1
  73. package/types/src/vocabulary-tables.d.ts +176 -22
package/src/orm.ts CHANGED
@@ -5,16 +5,26 @@
5
5
 
6
6
  import { uuidv7 } from '@fabrika/platform'
7
7
  import type { OperationNode } from 'kysely'
8
- import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
- import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
8
+ import { AndNode, BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
+ import { refScope } from './authority'
10
+ import { freeze, hasOwn, inSet, isSafeInteger, type NameSet, 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 { columnOf, type Compare, type Contains, parseCondition, type Primitive, type SelectState, type TableShape } from './description'
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 { linksPredicate, linkValues } from './links'
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 { modelOf, namesAction, type TableModels, updatableBy, visibleFor } from './policy'
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
- appRecordPredicate,
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
- reachColumn,
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 linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
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, { root: 'SelectQueryNode', table: context.model.name, joins: {}, scope, lock: 'update' })
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
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
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
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
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 = linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
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
- if (model !== undefined && listable && reachColumn(model, grant.dimension) !== undefined) {
443
- const context = parts.contextOf(model.name)
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, grant.action))
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 of `action`, read-only and every row, with the columns that
506
- * action reads (`visibleFor`): listed and aggregated with its read action or an action of its `appRead`, counted with
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, action: string): object {
510
- const visible = visibleFor(context.model, action)
511
- const shape = actionShape(context.model, visible)
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
- site,
516
- async (options?: unknown) => listRows(context, run, appRecordPredicate(context, capability, 'rows'), visible, options, key, action),
517
- ),
518
- count: bound(site, async (options?: unknown) => countRows(context, run, appRecordPredicate(context, capability, 'counts'), visible, options)),
519
- aggregate: bound(
520
- site,
521
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appRecordPredicate(context, capability, 'rows'), shape, spec),
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(site, async (id: unknown) => {
550
- scope()
551
- return selectOne(context, run, appKeyPredicate(model, id), visible, heldAction(context, capability))
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
- /** An `app` capability whose action the application table names: it reads one row with the columns of its action. */
557
- function namedApp(context: TableContext, capability: unknown): string {
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 table = context.model.name
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 (!namesAction(context.model, grant.action)) {
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.action}': read it from an app endpoint whose action ${table} names`,
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 grant.action
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 = appKeyPredicate(model, id)
593
- const action = namedApp(context, capability)
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], action)
708
+ await answerFiles(model, run.files, session, [row], reach)
602
709
  return row
603
710
  })
604
711
  return {
605
- list: bound(
606
- site,
607
- async (options?: unknown) =>
608
- listRows(context, run, appListPredicate(context, capability), visible(), options, key, heldAction(context, capability)),
609
- ),
610
- count: bound(site, async (options?: unknown) => countRows(context, run, appListPredicate(context, capability), visible(), options)),
611
- aggregate: bound(
612
- site,
613
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appListPredicate(context, capability), actionShape(model, visible()), spec),
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 action = namedApp(context, capability)
617
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
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 grant = updatingApp(context, capability)
628
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
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, appKeyPredicate(model, id), visibleFor(model, action), action)
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 grant = updatingApp(context, capability)
678
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
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, grant.action)
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, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
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
- const updated = await session.run<Readonly<Record<string, unknown>>>(
801
- updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
802
- { root: 'UpdateQueryNode', table, joins: {}, scope },
803
- )
804
- for (const row of updated) {
805
- const id = row['id']
806
- const next = row['version']
807
- if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
808
- throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
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
- // A full claim left rows behind: due at once.
817
- let rearm: Date | null = new Date(now.getTime() + 1)
818
- if (rows.length < limit) {
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, { root: 'SelectQueryNode', table, joins: {}, scope }),
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
- rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
970
+ next = row === undefined ? null : dueOf(row, table, queue.due)
827
971
  }
828
- await rearmClaim(runtime, session, fence, rearm)
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: grant.action, principal: grant.principal, id, chain: links })
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
- /** A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). */
1080
- function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] {
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 conditions = parseList(where, (condition) => {
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 (conditions === undefined) {
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: columnOf(shape, parts[0]), direction }
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
- /** An order column's value as the database prints it: exact, where a `Date` would drop microseconds. */
1136
- type CursorValue = string | null
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>`), as opaque text. */
1139
- function encodeCursor(row: Readonly<Record<string, unknown>>, order: readonly OrderColumn[]): string {
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 Buffer.from(JSON.stringify(values)).toString('base64url')
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,31 +1354,7 @@ 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
- function compare(table: string, name: string, operator: '>' | '<' | '=', value: Primitive): OperationNode {
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
  }
1191
1360
 
@@ -1193,20 +1362,43 @@ function isNull(table: string, name: string, negated: boolean): OperationNode {
1193
1362
  return BinaryOperationNode.create(column(table, name), OperatorNode.create(negated ? 'is not' : 'is'), ValueNode.createImmediate(null))
1194
1363
  }
1195
1364
 
1196
- /** Rows after `value` in one order column, where Postgres sorts nulls last ascending and first descending. */
1197
- function after(table: string, order: OrderColumn, value: CursorValue): OperationNode | undefined {
1365
+ /**
1366
+ * Rows after `value` in one order column, where Postgres sorts nulls last ascending and first descending. A NOT NULL
1367
+ * column holds no null, so its terms leave the null out.
1368
+ */
1369
+ function after(table: string, order: OrderColumn, value: CursorValue, notNull: NameSet): OperationNode | undefined {
1198
1370
  if (order.direction === 'asc') {
1199
- return value === null ? undefined : anyOf([compare(table, order.column, '>', value), isNull(table, order.column, false)])
1371
+ if (value === null) {
1372
+ return undefined
1373
+ }
1374
+ const later = compare(table, order.column, '>', value)
1375
+ return inSet(notNull, order.column) ? later : anyOf([later, isNull(table, order.column, false)])
1200
1376
  }
1201
1377
  return value === null ? isNull(table, order.column, true) : compare(table, order.column, '<', value)
1202
1378
  }
1203
1379
 
1204
- /** `(c1 after v1) or (c1 = v1 and c2 after v2) or …`: every row the order puts after the cursor's. */
1205
- function keysetAfter(table: string, order: readonly OrderColumn[], values: readonly CursorValue[]): OperationNode {
1380
+ /** Rows at or after `value` in one order column, or undefined where that is every row (a null, descending). */
1381
+ function atOrAfter(table: string, order: OrderColumn, value: CursorValue, notNull: NameSet): OperationNode | undefined {
1382
+ if (order.direction === 'desc') {
1383
+ return value === null ? undefined : compare(table, order.column, '<=', value)
1384
+ }
1385
+ if (value === null) {
1386
+ return isNull(table, order.column, false)
1387
+ }
1388
+ const later = compare(table, order.column, '>=', value)
1389
+ return inSet(notNull, order.column) ? later : anyOf([later, isNull(table, order.column, false)])
1390
+ }
1391
+
1392
+ /**
1393
+ * `(c1 after v1) or (c1 = v1 and c2 after v2) or …`: every row the order puts after the cursor's. The first column's
1394
+ * bound is ANDed before it, though every branch implies it: a database reads that bound as a range of an index on the
1395
+ * order and stops after the page, where the disjunction alone makes it fetch and sort every row before the cursor's.
1396
+ */
1397
+ function keysetAfter(table: string, order: readonly OrderColumn[], values: readonly CursorValue[], notNull: NameSet): OperationNode {
1206
1398
  const branches: OperationNode[] = []
1207
1399
  for (let index = 0; index < order.length; index++) {
1208
1400
  const term = order[index]
1209
- const position = term === undefined ? undefined : after(table, term, values[index] ?? null)
1401
+ const position = term === undefined ? undefined : after(table, term, values[index] ?? null, notNull)
1210
1402
  if (term === undefined || position === undefined) {
1211
1403
  continue
1212
1404
  }
@@ -1218,7 +1410,13 @@ function keysetAfter(table: string, order: readonly OrderColumn[], values: reado
1218
1410
  }
1219
1411
  branches[branches.length] = equal.length === 0 ? position : allOf([...equal, position])
1220
1412
  }
1221
- return branches.length === 0 ? ValueNode.createImmediate(false) : anyOf(branches)
1413
+ if (branches.length === 0) {
1414
+ return ValueNode.createImmediate(false)
1415
+ }
1416
+ const first = order[0]
1417
+ const bound = first === undefined ? undefined : atOrAfter(table, first, values[0] ?? null, notNull)
1418
+ const rows = anyOf(branches)
1419
+ return bound === undefined ? rows : AndNode.create(bound, rows)
1222
1420
  }
1223
1421
 
1224
1422
  /** One keyset page: `limit` rows in the order asked, the tiebreak columns last, and the cursor of the next page. */
@@ -1229,7 +1427,7 @@ async function listRows(
1229
1427
  visible: readonly string[],
1230
1428
  input: unknown,
1231
1429
  tiebreak: readonly string[],
1232
- action?: string,
1430
+ reach?: ReadReach,
1233
1431
  ): Promise<{ readonly items: Readonly<Record<string, unknown>>[]; readonly next: string | null }> {
1234
1432
  const table = context.model.name
1235
1433
  const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
@@ -1237,30 +1435,84 @@ async function listRows(
1237
1435
  const conditions = conditionsOf(context, shape, options['where'])
1238
1436
  const order = orderOf(shape, options['orderBy'], tiebreak)
1239
1437
  const limit = limitOf(options['limit'])
1240
- const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1241
- if (scope === undefined) {
1438
+ const session = await run.read()
1439
+ // Read once per page, whether the page verifies `after`, signs `next` or both.
1440
+ let read: Promise<CryptoKey> | undefined
1441
+ const key = (): Promise<CryptoKey> => (read ??= cursorKey(session))
1442
+ const position = options['after'] === undefined
1443
+ ? undefined
1444
+ : keysetAfter(table, order, await openCursor(key, cursorList(table, order), options['after'], order.length), context.model.notNull)
1445
+ if (scope === undefined || conditions === undefined) {
1242
1446
  return { items: [], next: null }
1243
1447
  }
1244
1448
  const dialect = dialectOf(context)
1245
1449
  const node = withCursorColumns(
1246
- selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
1450
+ selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect, context.model.notNull),
1247
1451
  table,
1248
1452
  order.map((term) => term.column),
1249
1453
  )
1250
- const session = await run.read()
1251
1454
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
1252
1455
  root: 'SelectQueryNode',
1253
1456
  table,
1254
1457
  joins: {},
1255
1458
  scope,
1459
+ subqueries: context.subqueries,
1460
+ through: context.through,
1256
1461
  })
1257
1462
  const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1258
1463
  const last = page[page.length - 1]
1259
1464
  const items = page.map((row) => withoutCursor(row, order))
1260
1465
  return {
1261
- items: action === undefined ? items : await answerFiles(context.model, run.files, session, items, action),
1262
- next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
1466
+ items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
1467
+ next: rows.length > limit && last !== undefined ? await encodeCursor(key, table, last, order) : null,
1468
+ }
1469
+ }
1470
+
1471
+ /**
1472
+ * Every row of a read in one statement, in the order asked with the tiebreak last, or a refusal when more than
1473
+ * `MAX_ALL_ROWS` match: it never answers a truncated set.
1474
+ */
1475
+ async function allRows(
1476
+ context: TableContext,
1477
+ run: Runner,
1478
+ scope: OperationNode | undefined,
1479
+ visible: readonly string[],
1480
+ input: unknown,
1481
+ tiebreak: readonly string[],
1482
+ reach?: ReadReach,
1483
+ ): Promise<Readonly<Record<string, unknown>>[]> {
1484
+ const table = context.model.name
1485
+ const options = readOptions(input, ['where', 'orderBy'], 'all')
1486
+ const shape = actionShape(context.model, visible)
1487
+ const conditions = conditionsOf(context, shape, options['where'])
1488
+ const order = orderOf(shape, options['orderBy'], tiebreak)
1489
+ if (scope === undefined || conditions === undefined) {
1490
+ return []
1491
+ }
1492
+ const dialect = dialectOf(context)
1493
+ const node = selectNode(
1494
+ rowState(table, conditions, order, MAX_ALL_ROWS + 1),
1495
+ visible,
1496
+ scope,
1497
+ undefined,
1498
+ context.model.dates,
1499
+ dialect,
1500
+ context.model.notNull,
1501
+ )
1502
+ const session = await run.read()
1503
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
1504
+ root: 'SelectQueryNode',
1505
+ table,
1506
+ joins: {},
1507
+ scope,
1508
+ subqueries: context.subqueries,
1509
+ through: context.through,
1510
+ })
1511
+ if (rows.length > MAX_ALL_ROWS) {
1512
+ 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`)
1263
1513
  }
1514
+ const items = answerRows(dialect, table, rowColumnsOf(context.model), rows)
1515
+ return reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach)
1264
1516
  }
1265
1517
 
1266
1518
  async function countRows(
@@ -1273,11 +1525,18 @@ async function countRows(
1273
1525
  const table = context.model.name
1274
1526
  const options = readOptions(input, ['where'], 'count')
1275
1527
  const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
1276
- if (scope === undefined) {
1528
+ if (scope === undefined || conditions === undefined) {
1277
1529
  return 0
1278
1530
  }
1279
1531
  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, { root: 'SelectQueryNode', table, joins: {}, scope })
1532
+ const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
1533
+ root: 'SelectQueryNode',
1534
+ table,
1535
+ joins: {},
1536
+ scope,
1537
+ subqueries: context.subqueries,
1538
+ through: context.through,
1539
+ })
1281
1540
  const count = row === undefined ? '0' : row['count']
1282
1541
  return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
1283
1542
  }