@fabrika/db 0.9.0-dev.3 → 0.9.0-dev.30

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 (82) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +8 -5
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +181 -0
  24. package/src/migrations.ts +43 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +198 -67
  27. package/src/orm.ts +383 -133
  28. package/src/policy.ts +1933 -122
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +55 -3
  31. package/src/request-receipts.ts +107 -0
  32. package/src/sql.ts +247 -476
  33. package/src/sqlite-bun.ts +149 -0
  34. package/src/sqlite-migrate.ts +242 -0
  35. package/src/sqlite.ts +269 -0
  36. package/src/store.ts +2292 -239
  37. package/src/stored-files.ts +188 -52
  38. package/src/tables.ts +171 -5
  39. package/src/temporal.ts +122 -9
  40. package/src/testing-shared.ts +1348 -0
  41. package/src/testing-sqlite.ts +685 -0
  42. package/src/testing.ts +310 -494
  43. package/src/vocabulary-tables.ts +159 -27
  44. package/types/src/application-rows.d.ts +58 -0
  45. package/types/src/authority.d.ts +147 -0
  46. package/types/src/builtins.d.ts +2 -0
  47. package/types/src/capability.d.ts +55 -2
  48. package/types/src/codegen-sqlite.d.ts +13 -0
  49. package/types/src/codegen.d.ts +79 -5
  50. package/types/src/condition-nodes.d.ts +9 -0
  51. package/types/src/conditions.d.ts +151 -0
  52. package/types/src/database.d.ts +81 -20
  53. package/types/src/description.d.ts +26 -8
  54. package/types/src/errors.d.ts +7 -5
  55. package/types/src/file-columns.d.ts +6 -4
  56. package/types/src/framework.d.ts +12 -5
  57. package/types/src/guard.d.ts +24 -0
  58. package/types/src/index.d.ts +5 -4
  59. package/types/src/job-leases.d.ts +34 -5
  60. package/types/src/job-wakes.d.ts +101 -0
  61. package/types/src/json.d.ts +18 -0
  62. package/types/src/migrations-sqlite.d.ts +4 -0
  63. package/types/src/migrations.d.ts +2 -0
  64. package/types/src/nodes.d.ts +17 -2
  65. package/types/src/orm-types.d.ts +155 -63
  66. package/types/src/orm.d.ts +21 -0
  67. package/types/src/policy.d.ts +344 -16
  68. package/types/src/postgres.d.ts +12 -0
  69. package/types/src/registry.d.ts +40 -3
  70. package/types/src/request-receipts.d.ts +22 -0
  71. package/types/src/sql.d.ts +29 -21
  72. package/types/src/sqlite-bun.d.ts +21 -0
  73. package/types/src/sqlite-migrate.d.ts +28 -0
  74. package/types/src/sqlite.d.ts +24 -0
  75. package/types/src/store.d.ts +143 -34
  76. package/types/src/stored-files.d.ts +6 -2
  77. package/types/src/tables.d.ts +18 -2
  78. package/types/src/temporal.d.ts +24 -0
  79. package/types/src/testing-shared.d.ts +290 -0
  80. package/types/src/testing-sqlite.d.ts +37 -0
  81. package/types/src/testing.d.ts +2 -93
  82. package/types/src/vocabulary-tables.d.ts +169 -22
package/src/orm.ts CHANGED
@@ -3,16 +3,27 @@
3
3
  // is that invocation, then refuses what the site may not do with the message its types give, then runs the store's
4
4
  // own checks of kind, dimension and action against the capability.
5
5
 
6
+ import { uuidv7 } from '@fabrika/platform'
6
7
  import type { OperationNode } from 'kysely'
7
8
  import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
+ import { refScope } from './authority'
8
10
  import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
9
11
  import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
10
12
  import type { InvocationTransaction, Session } from './database'
11
- 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'
12
23
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
13
24
  import { answerFiles, type FileBinding } from './file-columns'
14
25
  import { databaseNow } from './job-leases'
15
- import { linksPredicate, linkValues } from './links'
26
+ import { rearmClaim } from './job-wakes'
16
27
  import {
17
28
  aggregateNode,
18
29
  allOf,
@@ -24,28 +35,48 @@ import {
24
35
  everything,
25
36
  inList,
26
37
  lockedSelectNode,
38
+ nextClaimNode,
27
39
  scopedWhere,
28
40
  selectNode,
29
41
  updateNode,
30
42
  withCursorColumns,
31
43
  } from './nodes'
32
44
  import type { DataKind, TargetForm, UnscopedMode } from './orm-types'
33
- import { modelOf, namesAction, type TableModels, updatableBy, visibleFor } from './policy'
45
+ import {
46
+ accessTablesOf,
47
+ delegates,
48
+ modelOf,
49
+ namesAction,
50
+ type ReadReach,
51
+ soleReach,
52
+ type TableModels,
53
+ updatableBy,
54
+ visibleFor,
55
+ visibleThrough,
56
+ } from './policy'
34
57
  import { type SqlSite, type SqlTag, sqlTag } from './sql'
35
58
  import {
36
59
  actionShape,
37
60
  aggregateRows,
38
61
  type AggregateSpec,
39
62
  answer,
63
+ appGetScope,
40
64
  appKeyPredicate,
65
+ appKeyScope,
41
66
  appListPredicate,
42
- appRecordPredicate,
67
+ appListRead,
68
+ type AppRead,
69
+ appRecordRead,
43
70
  appRowPredicate,
71
+ appUpdate,
72
+ boundTerms,
73
+ boundValues,
44
74
  childObjectPredicate,
45
75
  childScope,
46
76
  claimedRowPredicate,
47
77
  claimScope,
48
78
  type DataLayerRuntime,
79
+ dialectOf,
49
80
  heldAction,
50
81
  insertPrepared,
51
82
  insertRow,
@@ -56,10 +87,11 @@ import {
56
87
  prepareApplicationInsert,
57
88
  prepareChildInsert,
58
89
  prepareDimensionInsert,
59
- reachColumn,
90
+ reachedBy,
60
91
  reachPredicate,
61
92
  readValues,
62
93
  removeRow,
94
+ rowColumnsOf,
63
95
  type Runner,
64
96
  runtimeOf,
65
97
  scopedApplicationRead,
@@ -68,15 +100,20 @@ import {
68
100
  selfLinks,
69
101
  type TableContext,
70
102
  updateRow,
71
- updatingApp,
72
103
  updatingRef,
73
104
  versionArgument,
74
105
  } from './store'
75
- import { answerDays, timestampInput } from './temporal'
106
+ import { answerRows, timestampInput } from './temporal'
76
107
 
77
108
  /** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
78
109
  export const DEFAULT_LIST_LIMIT = 50
79
110
  export const MAX_LIST_LIMIT = 500
111
+ /**
112
+ * The most rows `all()` answers; past it, it refuses instead of truncating. It bounds rows, not bytes: 10 000 rows of
113
+ * ~1 KB, held two or three times over (driver, answer, response), is tens of MB of the one 128 MB Durable Object
114
+ * isolate every concurrent invocation of the environment shares. Wide rows or a growing set page with `list`.
115
+ */
116
+ export const MAX_ALL_ROWS = 10_000
80
117
 
81
118
  /** The framework's own tables; no declaration reaches one. */
82
119
  const FRAMEWORK_PREFIX = 'fabrika_'
@@ -102,6 +139,11 @@ export interface DataSite {
102
139
  * only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
103
140
  */
104
141
  readonly files?: FileBinding
142
+ /**
143
+ * The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
144
+ * answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
145
+ */
146
+ readonly holds?: readonly string[]
105
147
  /** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
106
148
  readonly carried?: ReadonlySet<string>
107
149
  /** Throws unless the work running now is the invocation these handles were made for. */
@@ -126,6 +168,11 @@ export interface DataHandles {
126
168
  readonly reference: object
127
169
  /** `ctx.db.unscoped`, or `undefined` for a site that declares none. */
128
170
  readonly unscoped: object | undefined
171
+ /**
172
+ * At most two rows of `table` whose `column` holds `value`, as an unscoped read answers them: the framework's read of
173
+ * the caller's own row (`ctx.caller` of `@fabrika/app`). No handle of an application reaches it.
174
+ */
175
+ rowsNaming(table: string, column: string, value: string): Promise<readonly Readonly<Record<string, unknown>>[]>
129
176
  }
130
177
 
131
178
  /** The data side of one bound layer, which only the framework reaches (`@fabrika/db/framework`). */
@@ -158,22 +205,20 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
158
205
  direct: () => parts.newSession(parts.runtime()),
159
206
  transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
160
207
  handles: (site: DataSite) => handlesOf(parts, site),
161
- sql: (site: SqlSite) =>
162
- sqlTag(
208
+ sql: (site: SqlSite) => {
209
+ const database = parts.runtime().database
210
+ return sqlTag(
163
211
  site,
164
- parts.runtime().database.schema,
165
- (capability, table, use, assigned) => {
212
+ database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
213
+ (capability, table, use) => {
166
214
  if (!hasOwn(parts.models, table)) {
167
215
  throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
168
216
  }
169
- return scopeTerms(parts.contextOf(table), capability, use, assigned)
217
+ return scopeTerms(parts.contextOf(table), capability, use)
170
218
  },
171
- (table) => {
172
- if (modelOf(parts.models, table)?.scope.mode === 'reference') {
173
- throw new QueryRefusedError('read_only', `ctx.sql: ${table} is a reference table, which no statement writes: its rows come from a migration`)
174
- }
175
- },
176
- ),
219
+ accessTablesOf(parts.models),
220
+ )
221
+ },
177
222
  })
178
223
  }
179
224
 
@@ -259,6 +304,24 @@ function handlesOf(parts: DataLayerParts, site: DataSite): DataHandles {
259
304
  },
260
305
  reference: referenceTables(parts, site, run),
261
306
  unscoped,
307
+ rowsNaming: async (table: string, column: string, value: string) => {
308
+ site.check()
309
+ const model = table.startsWith(FRAMEWORK_PREFIX) ? undefined : modelOf(parts.models, table)
310
+ if (model === undefined) {
311
+ throw new QueryRefusedError('unknown_table', `the caller's table ${table} is not a table of src/db/tables.ts`)
312
+ }
313
+ const keyed = model.scope.mode === 'dimension' || model.scope.mode === 'child' || model.scope.mode === 'app'
314
+ const page = await listRows(
315
+ parts.contextOf(table),
316
+ run,
317
+ everything(),
318
+ model.visible,
319
+ { where: [[column, '=', value]], limit: 2 },
320
+ keyed ? [keyOf(model)] : model.visible,
321
+ soleReach(model.actions.read[0] ?? ''),
322
+ )
323
+ return page.items
324
+ },
262
325
  })
263
326
  }
264
327
 
@@ -309,7 +372,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
309
372
 
310
373
  /** The predicate of the target object, over the whole chain its `Ref` carries. */
311
374
  function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
312
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
375
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date())
313
376
  }
314
377
 
315
378
  function targetRow(
@@ -323,19 +386,26 @@ function targetRow(
323
386
  const onOnly = (operation: string) => `${operation} acts on one object: declare access with on`
324
387
  const get = bound(site, async () => {
325
388
  const grant = namedRef(context, capability, dimension)
326
- return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), grant.action)
389
+ return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), soleReach(grant.action))
327
390
  })
328
391
  const lock = bound(site, async () => {
329
392
  const grant = namedRef(context, capability, dimension)
330
393
  const scope = targetPredicate(context, grant)
331
394
  const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
332
395
  const session = await run.read()
333
- const rows = await session.run(node, { root: 'SelectQueryNode', table: context.model.name, joins: {}, scope, lock: 'update' })
334
- const [row] = answerDays(context.model.name, context.model.dates, rows)
396
+ const rows = await session.run(node, {
397
+ root: 'SelectQueryNode',
398
+ table: context.model.name,
399
+ joins: {},
400
+ scope,
401
+ lock: 'update',
402
+ subqueries: context.subqueries,
403
+ })
404
+ const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
335
405
  if (row === undefined) {
336
406
  throw new NotFoundError(`${context.model.name} not found`)
337
407
  }
338
- await answerFiles(context.model, run.files, session, [row], grant.action)
408
+ await answerFiles(context.model, run.files, session, [row], soleReach(grant.action))
339
409
  return row
340
410
  })
341
411
  const getForUpdate = site.kind === 'job'
@@ -368,15 +438,18 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
368
438
  return freeze({
369
439
  list: bound(site, async (options?: unknown) => {
370
440
  const grant = namedRef(context, capability, parent)
371
- return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], grant.action)
441
+ return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
442
+ }),
443
+ all: bound(site, async (options?: unknown) => {
444
+ const grant = namedRef(context, capability, parent)
445
+ return allRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
372
446
  }),
373
447
  get: bound(site, async (id: unknown) => {
374
448
  const grant = namedRef(context, capability, parent)
375
449
  if (typeof id !== 'string' || id.length === 0) {
376
450
  throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its ${key}, a non-empty string`)
377
451
  }
378
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
379
- return selectOne(context, run, scope, visibleFor(context.model, grant.action), grant.action)
452
+ return selectOne(context, run, parentPredicate(context, grant, id), visibleFor(context.model, grant.action), soleReach(grant.action))
380
453
  }),
381
454
  insert: writing(
382
455
  site,
@@ -389,8 +462,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
389
462
  }
390
463
  const grant = updatingRef(context, capability, parent)
391
464
  const changes = readValues(values, updatableBy(context.model, grant.action), 'update', context.model)
392
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
393
- return updateRow(context, run, { scope }, changes, versionArgument(context, options))
465
+ return updateRow(context, run, { scope: parentPredicate(context, grant, id) }, changes, versionArgument(context, options))
394
466
  }),
395
467
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
396
468
  await removeRow(context, run, { scope: childObjectPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -403,8 +475,13 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
403
475
  return freeze({
404
476
  list: bound(site, async (options?: unknown) => {
405
477
  const grant = namedRef(context, capability, dimension)
406
- const scope = linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
407
- return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
478
+ const scope = refScope(context, context.model, context.model.chain, grant, new Date())
479
+ return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
480
+ }),
481
+ all: bound(site, async (options?: unknown) => {
482
+ const grant = namedRef(context, capability, dimension)
483
+ const scope = refScope(context, context.model, context.model.chain, grant, new Date())
484
+ return allRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
408
485
  }),
409
486
  insert: writing(
410
487
  site,
@@ -435,9 +512,9 @@ function withinTables(parts: DataLayerParts, site: DataSite, run: Runner, capabi
435
512
  for (let index = 0; index < tables.length; index++) {
436
513
  const model = modelOf(parts.models, tables[index] ?? '')
437
514
  const listable = model?.scope.mode === 'dimension' || model?.scope.mode === 'child'
438
- if (model !== undefined && listable && reachColumn(model, grant.dimension) !== undefined) {
439
- const context = parts.contextOf(model.name)
440
- setOwn(handle, model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
515
+ const context = model !== undefined && listable ? parts.contextOf(model.name) : undefined
516
+ if (context !== undefined && reachedBy(context, grant.dimension)) {
517
+ setOwn(handle, context.model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
441
518
  }
442
519
  }
443
520
  return freeze(handle)
@@ -461,7 +538,11 @@ function listedRows(
461
538
  claim: claiming(parts, context, site, capability),
462
539
  list: bound(site, async (options?: unknown) => {
463
540
  const predicate = scope()
464
- return listRows(context, run, predicate, visible(), options, key, heldAction(context, capability))
541
+ return listRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
542
+ }),
543
+ all: bound(site, async (options?: unknown) => {
544
+ const predicate = scope()
545
+ return allRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
465
546
  }),
466
547
  count: bound(site, async (options?: unknown) => {
467
548
  const predicate = scope()
@@ -491,31 +572,37 @@ function applicationTables(parts: DataLayerParts, site: DataSite, run: Runner, c
491
572
  const rows = applicationRows(parts, context, site, run, capability)
492
573
  setOwn(handle, model.name, site.public === true ? publicApplicationRows(context, site, run, capability, rows) : freeze(rows))
493
574
  } else if (site.public !== true && (model.scope.mode === 'dimension' || model.scope.mode === 'child')) {
494
- setOwn(handle, model.name, appRecordRows(context, site, run, capability, grant.action))
575
+ setOwn(handle, model.name, appRecordRows(context, site, run, capability))
495
576
  }
496
577
  }
497
578
  return freeze(handle)
498
579
  }
499
580
 
500
581
  /**
501
- * A dimension or child table under an `app` capability of `action`, read-only and every row, with the columns that
502
- * action reads (`visibleFor`): listed and aggregated with its read action or an action of its `appRead`, counted with
582
+ * A dimension or child table under an `app` capability, read-only and every row, with the columns its reaching actions
583
+ * read alone (`visibleThrough`): listed and aggregated with its read action or an action of its `appRead`, counted with
503
584
  * those or an action of its `appCount`.
504
585
  */
505
- function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown, action: string): object {
506
- const visible = visibleFor(context.model, action)
507
- const shape = actionShape(context.model, visible)
508
- const key = [keyOf(context.model)]
586
+ function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown): object {
587
+ const model = context.model
588
+ const key = [keyOf(model)]
509
589
  return freeze({
510
- list: bound(
511
- site,
512
- async (options?: unknown) => listRows(context, run, appRecordPredicate(context, capability, 'rows'), visible, options, key, action),
513
- ),
514
- count: bound(site, async (options?: unknown) => countRows(context, run, appRecordPredicate(context, capability, 'counts'), visible, options)),
515
- aggregate: bound(
516
- site,
517
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appRecordPredicate(context, capability, 'rows'), shape, spec),
518
- ),
590
+ list: bound(site, async (options?: unknown) => {
591
+ const { predicate, reach } = appRecordRead(context, capability, 'rows')
592
+ return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
593
+ }),
594
+ all: bound(site, async (options?: unknown) => {
595
+ const { predicate, reach } = appRecordRead(context, capability, 'rows')
596
+ return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
597
+ }),
598
+ count: bound(site, async (options?: unknown) => {
599
+ const { predicate, reach } = appRecordRead(context, capability, 'counts')
600
+ return countRows(context, run, predicate, visibleThrough(model, reach), options)
601
+ }),
602
+ aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
603
+ const { predicate, reach } = appRecordRead(context, capability, 'rows')
604
+ return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
605
+ }),
519
606
  })
520
607
  }
521
608
 
@@ -539,30 +626,55 @@ function scopedApplicationRows(context: TableContext, site: DataSite, run: Runne
539
626
  const key = [keyOf(model)]
540
627
  const scope = () => scopedApplicationRead(context, capability)
541
628
  return freeze({
542
- list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, heldAction(context, capability))),
629
+ list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
630
+ all: bound(site, async (options?: unknown) => allRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
543
631
  count: bound(site, async (options?: unknown) => countRows(context, run, scope(), visible, options)),
544
632
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, scope(), context.shape, spec)),
545
- get: bound(site, async (id: unknown) => {
546
- scope()
547
- return selectOne(context, run, appKeyPredicate(model, id), visible, heldAction(context, capability))
548
- }),
633
+ get: bound(
634
+ site,
635
+ async (id: unknown) =>
636
+ selectOne(
637
+ context,
638
+ run,
639
+ scopedApplicationRead(context, capability, appKeyPredicate(model, id)),
640
+ visible,
641
+ soleReach(heldAction(context, capability)),
642
+ ),
643
+ ),
549
644
  })
550
645
  }
551
646
 
552
- /** An `app` capability whose action the application table names: it reads one row with the columns of its action. */
553
- function namedApp(context: TableContext, capability: unknown): string {
647
+ /**
648
+ * The row `key` names, for an `app` capability with an action the application table names, or any but a public
649
+ * procedure's on a table read with `'any'`: within the conditions of the actions it holds that the table names, any one
650
+ * admitting the row, and with the columns they read alone (`visibleThrough`).
651
+ */
652
+ function namedAppRead(context: TableContext, capability: unknown, key: unknown): AppRead {
554
653
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
555
- const table = context.model.name
654
+ const model = context.model
655
+ const table = model.name
556
656
  if (grant.kind !== 'app') {
557
657
  throw new CapabilityError('wrong_capability', `a read of ${table} here needs the capability of an app endpoint, got ${describeGrant(grant)}`)
558
658
  }
559
- if (!namesAction(context.model, grant.action)) {
659
+ if (model.actions.readAny) {
660
+ // Refuses a public procedure's grant, which reads no table read with 'any'.
661
+ appListPredicate(context, capability)
662
+ return { predicate: appGetScope(model, grant.actions, key), reach: freeze({ actions: grant.actions, narrowed: false }) }
663
+ }
664
+ const named: string[] = []
665
+ for (let index = 0; index < grant.actions.length; index++) {
666
+ const action = grant.actions[index]
667
+ if (action !== undefined && namesAction(model, action)) {
668
+ named[named.length] = action
669
+ }
670
+ }
671
+ if (named.length === 0) {
560
672
  throw new CapabilityError(
561
673
  'wrong_action',
562
- `${table} does not name the action '${grant.action}': read it from an app endpoint whose action ${table} names`,
674
+ `${table} does not name the action '${grant.actions.join("', '")}': read it from an app endpoint whose action ${table} names`,
563
675
  )
564
676
  }
565
- return grant.action
677
+ return { predicate: appGetScope(model, named, key), reach: freeze({ actions: named, narrowed: true }) }
566
678
  }
567
679
 
568
680
  /**
@@ -578,39 +690,43 @@ function applicationRows(
578
690
  ): Readonly<Record<string, unknown>> {
579
691
  const model = context.model
580
692
  const table = model.name
581
- const visible = () => visibleFor(model, heldAction(context, capability))
582
693
  const key = [keyOf(model)]
583
694
  const getForUpdate = site.kind === 'job'
584
695
  ? refused(site, 'read_only', 'a job writes inside ctx.transaction((tx) => …): use tx.db there')
585
696
  : site.kind === 'query'
586
697
  ? refused(site, 'read_only', 'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation')
587
698
  : bound(site, async (id: unknown) => {
588
- const scope = appKeyPredicate(model, id)
589
- const action = namedApp(context, capability)
590
- const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
699
+ const { predicate: scope, reach } = namedAppRead(context, capability, id)
700
+ const node = lockedSelectNode(table, visibleThrough(model, reach), scope, model.dates)
591
701
  const session = await run.read()
592
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
593
- const [row] = answerDays(table, model.dates, rows)
702
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update', subqueries: context.subqueries })
703
+ const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
594
704
  if (row === undefined) {
595
705
  throw new NotFoundError(`${table} not found`)
596
706
  }
597
- await answerFiles(model, run.files, session, [row], action)
707
+ await answerFiles(model, run.files, session, [row], reach)
598
708
  return row
599
709
  })
600
710
  return {
601
- list: bound(
602
- site,
603
- async (options?: unknown) =>
604
- listRows(context, run, appListPredicate(context, capability), visible(), options, key, heldAction(context, capability)),
605
- ),
606
- count: bound(site, async (options?: unknown) => countRows(context, run, appListPredicate(context, capability), visible(), options)),
607
- aggregate: bound(
608
- site,
609
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appListPredicate(context, capability), actionShape(model, visible()), spec),
610
- ),
711
+ list: bound(site, async (options?: unknown) => {
712
+ const { predicate, reach } = appListRead(context, capability)
713
+ return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
714
+ }),
715
+ all: bound(site, async (options?: unknown) => {
716
+ const { predicate, reach } = appListRead(context, capability)
717
+ return allRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
718
+ }),
719
+ count: bound(site, async (options?: unknown) => {
720
+ const { predicate, reach } = appListRead(context, capability)
721
+ return countRows(context, run, predicate, visibleThrough(model, reach), options)
722
+ }),
723
+ aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
724
+ const { predicate, reach } = appListRead(context, capability)
725
+ return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
726
+ }),
611
727
  get: bound(site, async (id: unknown) => {
612
- const action = namedApp(context, capability)
613
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
728
+ const { predicate, reach } = namedAppRead(context, capability, id)
729
+ return selectOne(context, run, predicate, visibleThrough(model, reach), reach)
614
730
  }),
615
731
  getForUpdate,
616
732
  claim: claiming(parts, context, site, capability),
@@ -620,9 +736,8 @@ function applicationRows(
620
736
  async (values: unknown, options?: unknown) => insertPrepared(context, run, prepareApplicationInsert(context, capability, values, options)),
621
737
  ),
622
738
  update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
623
- const grant = updatingApp(context, capability)
624
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
625
- return updateRow(context, run, { scope: appKeyPredicate(model, id) }, changes, versionArgument(context, options))
739
+ const { scope, changes } = appUpdate(context, capability, id, values)
740
+ return updateRow(context, run, { scope }, changes, versionArgument(context, options))
626
741
  }),
627
742
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
628
743
  await removeRow(context, run, { scope: appRowPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -659,26 +774,24 @@ function publicApplicationRows(
659
774
  }
660
775
  return freeze({
661
776
  list: rows['list'],
777
+ all: bound(site, async () => {
778
+ // The table's own read refusal first, as list answers it, so the message never points to a list it refuses too.
779
+ appListPredicate(context, capability)
780
+ throw new QueryRefusedError('public_reach', 'a public procedure pages its reads: read the table with list')
781
+ }),
662
782
  count: rows['count'],
663
783
  aggregate: rows['aggregate'],
664
784
  get: bound(site, async (id: unknown) => {
665
785
  appListPredicate(context, capability)
666
786
  const action = heldAction(context, capability)
667
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
787
+ return selectOne(context, run, appKeyScope(model, [action], id), visibleFor(model, action), soleReach(action))
668
788
  }),
669
789
  getForUpdate: refusal('lock'),
670
790
  claim: refusal('claim'),
671
791
  update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
672
792
  tokenRow('update', id)
673
- const grant = updatingApp(context, capability)
674
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
675
- const saved = await updateRow<Readonly<Record<string, unknown>>>(
676
- context,
677
- run,
678
- { scope: appKeyPredicate(model, id) },
679
- changes,
680
- versionArgument(context, options),
681
- )
793
+ const { scope, changes } = appUpdate(context, capability, id, values)
794
+ const saved = await updateRow<Readonly<Record<string, unknown>>>(context, run, { scope }, changes, versionArgument(context, options))
682
795
  return freeze({ version: saved['version'] })
683
796
  }),
684
797
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
@@ -701,6 +814,19 @@ function publicApplicationRows(
701
814
  const DEFAULT_TICK_MS = 60_000
702
815
  /** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
703
816
  const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
817
+ /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
818
+ const CLAIM_REARM_MIN_MS = 1_000
819
+
820
+ /**
821
+ * When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
822
+ * at the next due row it would take but no sooner than a second after it, or never when it would take none.
823
+ */
824
+ export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
825
+ if (full) {
826
+ return new Date(now.getTime() + 1)
827
+ }
828
+ return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
829
+ }
704
830
 
705
831
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
706
832
  function backoffMs(tickMs: number, attempts: number): number {
@@ -711,6 +837,15 @@ function backoffMs(tickMs: number, attempts: number): number {
711
837
  return Math.min(backoff, MAX_BACKOFF_MS)
712
838
  }
713
839
 
840
+ /** A queue row's due time as the layer answers it. */
841
+ function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
842
+ const due = row[column]
843
+ if (!(due instanceof Date)) {
844
+ throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
845
+ }
846
+ return due
847
+ }
848
+
714
849
  /** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
715
850
  function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
716
851
  if (site.kind === 'query') {
@@ -726,6 +861,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
726
861
  return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
727
862
  }
728
863
 
864
+ /**
865
+ * How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
866
+ * compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
867
+ * statement's size. Every chunk runs in the claim's one fenced transaction.
868
+ */
869
+ const CLAIM_UPDATE_IDS = 50
870
+
729
871
  /**
730
872
  * Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
731
873
  * attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
@@ -740,7 +882,7 @@ async function claimRows(
740
882
  ): Promise<readonly Readonly<Record<string, unknown>>[]> {
741
883
  const model = context.model
742
884
  const table = model.name
743
- const { grant, scope } = claimScope(context, capability)
885
+ const { grant, action, scope } = claimScope(context, capability)
744
886
  const queue = model.queue
745
887
  const version = model.version
746
888
  if (queue === undefined || version === undefined) {
@@ -751,26 +893,31 @@ async function claimRows(
751
893
  throw new QueryRefusedError('list_page', 'claim takes { limit }: attempts count claims, so claim only what the run will reach')
752
894
  }
753
895
  const limit = limitOf(options['limit'])
754
- const visible = visibleFor(model, grant.action)
755
- const conditions = conditionsOf(actionShape(model, visible), options['where'])
896
+ const visible = visibleFor(model, action)
897
+ const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
756
898
  if (scope === undefined) {
757
899
  return []
758
900
  }
901
+ const dialect = dialectOf(context)
759
902
  const key = keyOf(model)
760
903
  const chain = model.chain.map((link) => link.column)
761
904
  const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
762
905
  const tickMs = site.tickMs ?? DEFAULT_TICK_MS
763
- const order = [{ column: queue.due, direction: 'asc' as const }, { column: key, direction: 'asc' as const }]
764
- const leased = await parts.fenced(parts.runtime(), async (session) => {
906
+ const byDue = { column: queue.due, direction: 'asc' as const }
907
+ const order = [byDue, { column: key, direction: 'asc' as const }]
908
+ const runtime = parts.runtime()
909
+ const leased = await parts.fenced(runtime, async (session) => {
765
910
  const now = await databaseNow(session)
766
- const node = claimNode(
767
- rowState(table, conditions, order, limit),
768
- selected,
769
- { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts },
911
+ const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
912
+ const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
913
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
914
+ root: 'SelectQueryNode',
915
+ table,
916
+ joins: {},
770
917
  scope,
771
- model.dates,
772
- )
773
- const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
918
+ lock: 'claim',
919
+ subqueries: context.subqueries,
920
+ })
774
921
  const byAttempts = new Map<number, string[]>()
775
922
  for (const row of rows) {
776
923
  const attempts = row[queue.attempts]
@@ -784,20 +931,56 @@ async function claimRows(
784
931
  for (const [attempts, ids] of byAttempts) {
785
932
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
786
933
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
787
- const updated = await session.run<Readonly<Record<string, unknown>>>(
788
- updateNode(table, changes, version, scopedWhere(inList(table, key, ids), scope), answer(context)),
789
- { root: 'UpdateQueryNode', table, joins: {}, scope },
790
- )
791
- for (const row of updated) {
792
- const id = row['id']
793
- const next = row['version']
794
- if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
795
- throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
934
+ for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
935
+ const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
936
+ const updated = await session.run<Readonly<Record<string, unknown>>>(
937
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
938
+ { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
939
+ )
940
+ for (const row of updated) {
941
+ const id = row['id']
942
+ const next = row['version']
943
+ if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
944
+ throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
945
+ }
946
+ claimed.set(id, { version: next, attempts: attempts + 1, due })
796
947
  }
797
- claimed.set(id, { version: next, attempts: attempts + 1, due })
798
948
  }
799
949
  }
800
- return { rows: await answerFiles(model, site.files, session, answerDays(table, model.dates, rows), grant.action), claimed }
950
+ // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
951
+ const fence = runtime.capabilities.fence()
952
+ if (fence !== null && rows.length > 0) {
953
+ const full = rows.length >= limit
954
+ let next: Date | null = null
955
+ if (!full) {
956
+ const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
957
+ const [row] = answerRows(
958
+ dialect,
959
+ table,
960
+ rowColumnsOf(model),
961
+ await session.run<Readonly<Record<string, unknown>>>(later, {
962
+ root: 'SelectQueryNode',
963
+ table,
964
+ joins: {},
965
+ scope,
966
+ subqueries: context.subqueries,
967
+ }),
968
+ )
969
+ next = row === undefined ? null : dueOf(row, table, queue.due)
970
+ }
971
+ await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
972
+ }
973
+ return {
974
+ rows: await answerFiles(
975
+ model,
976
+ site.files,
977
+ session,
978
+ answerRows(dialect, table, rowColumnsOf(model), rows),
979
+ soleReach(action),
980
+ nameSet(site.holds ?? []),
981
+ ),
982
+ claimed,
983
+ }
801
984
  })
802
985
  return leased.rows.map((row) => {
803
986
  const id = String(row[key])
@@ -809,7 +992,7 @@ async function claimRows(
809
992
  for (const name of chain) {
810
993
  links.set(name, String(row[name]))
811
994
  }
812
- const ref = runtimeOf(context.connection).capabilities.row({ table, action: grant.action, principal: grant.principal, id, chain: links })
995
+ const ref = runtimeOf(context.connection).capabilities.row({ table, action, principal: grant.principal, id, chain: links })
813
996
  const answered: Record<string, unknown> = {}
814
997
  for (const name of visible) {
815
998
  setOwn(answered, name, row[name])
@@ -893,6 +1076,7 @@ function referenceTables(parts: DataLayerParts, site: DataSite, run: Runner): ob
893
1076
  model.name,
894
1077
  freeze({
895
1078
  list: bound(site, async (options?: unknown) => listRows(context, run, everything(), model.visible, options, model.visible)),
1079
+ all: bound(site, async (options?: unknown) => allRows(context, run, everything(), model.visible, options, model.visible)),
896
1080
  count: bound(site, async (options?: unknown) => countRows(context, run, everything(), model.visible, options)),
897
1081
  }),
898
1082
  )
@@ -942,6 +1126,17 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
942
1126
  return equals(table, keyOf(model), id)
943
1127
  }
944
1128
  const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
1129
+ if (model.view) {
1130
+ return refused(site, 'read_only', `${table} is a view, which no handler writes`)
1131
+ }
1132
+ // A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
1133
+ if (delegates(model) || context.writers.length > 0) {
1134
+ return refused(
1135
+ site,
1136
+ 'undeclared_reach',
1137
+ `${table} hands out access, so it is written through a capability only, never unscoped`,
1138
+ )
1139
+ }
945
1140
  if (mode === 'read') {
946
1141
  const verb = operation === 'remove' ? 'remove' : operation
947
1142
  return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
@@ -951,20 +1146,25 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
951
1146
  return freeze({
952
1147
  list: bound(
953
1148
  site,
954
- async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, unscopedRead),
1149
+ async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
1150
+ ),
1151
+ all: bound(
1152
+ site,
1153
+ async (options?: unknown) => allRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
955
1154
  ),
956
1155
  count: bound(site, async (options?: unknown) => countRows(context, run, everything(), visible, options)),
957
1156
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
958
1157
  get: bound(site, async (id: unknown) => {
959
1158
  const scope = everything()
960
- const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates)
1159
+ const dialect = dialectOf(context)
1160
+ const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
961
1161
  const session = await run.read()
962
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
963
- const [row] = answerDays(table, model.dates, rows)
1162
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
1163
+ const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
964
1164
  if (row === undefined) {
965
1165
  throw new NotFoundError(`${table} not found`)
966
1166
  }
967
- await answerFiles(model, run.files, session, [row], unscopedRead)
1167
+ await answerFiles(model, run.files, session, [row], soleReach(unscopedRead))
968
1168
  return row
969
1169
  }),
970
1170
  insert: write('insert', async (values: unknown) => insertUnscoped(context, run, site.principal, values)),
@@ -1003,7 +1203,7 @@ async function insertUnscoped(context: TableContext, run: Runner, principal: str
1003
1203
  )
1004
1204
  }
1005
1205
  }
1006
- row.set(keyOf(model), Bun.randomUUIDv7())
1206
+ row.set(keyOf(model), uuidv7())
1007
1207
  if (model.version !== undefined) {
1008
1208
  row.set(model.version, 1)
1009
1209
  }
@@ -1045,7 +1245,8 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
1045
1245
  return read
1046
1246
  }
1047
1247
 
1048
- function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[] {
1248
+ /** A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). */
1249
+ function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] {
1049
1250
  if (where === undefined) {
1050
1251
  return []
1051
1252
  }
@@ -1059,7 +1260,7 @@ function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[]
1059
1260
  if (conditions === undefined) {
1060
1261
  throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
1061
1262
  }
1062
- return conditions
1263
+ return boundTerms(context, context.model, conditions)
1063
1264
  }
1064
1265
 
1065
1266
  function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[]): OrderColumn[] {
@@ -1069,7 +1270,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
1069
1270
  if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
1070
1271
  throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
1071
1272
  }
1072
- return { column: columnOf(shape, parts[0]), direction }
1273
+ return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
1073
1274
  })
1074
1275
  if (terms === undefined) {
1075
1276
  throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
@@ -1197,20 +1398,21 @@ async function listRows(
1197
1398
  visible: readonly string[],
1198
1399
  input: unknown,
1199
1400
  tiebreak: readonly string[],
1200
- action?: string,
1401
+ reach?: ReadReach,
1201
1402
  ): Promise<{ readonly items: Readonly<Record<string, unknown>>[]; readonly next: string | null }> {
1202
1403
  const table = context.model.name
1203
1404
  const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
1204
1405
  const shape = actionShape(context.model, visible)
1205
- const conditions = conditionsOf(shape, options['where'])
1406
+ const conditions = conditionsOf(context, shape, options['where'])
1206
1407
  const order = orderOf(shape, options['orderBy'], tiebreak)
1207
1408
  const limit = limitOf(options['limit'])
1208
1409
  const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1209
1410
  if (scope === undefined) {
1210
1411
  return { items: [], next: null }
1211
1412
  }
1413
+ const dialect = dialectOf(context)
1212
1414
  const node = withCursorColumns(
1213
- selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates),
1415
+ selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
1214
1416
  table,
1215
1417
  order.map((term) => term.column),
1216
1418
  )
@@ -1220,16 +1422,57 @@ async function listRows(
1220
1422
  table,
1221
1423
  joins: {},
1222
1424
  scope,
1425
+ subqueries: context.subqueries,
1426
+ through: context.through,
1223
1427
  })
1224
- const page = answerDays(table, context.model.dates, rows.slice(0, limit))
1428
+ const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1225
1429
  const last = page[page.length - 1]
1226
1430
  const items = page.map((row) => withoutCursor(row, order))
1227
1431
  return {
1228
- items: action === undefined ? items : await answerFiles(context.model, run.files, session, items, action),
1432
+ items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
1229
1433
  next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
1230
1434
  }
1231
1435
  }
1232
1436
 
1437
+ /**
1438
+ * Every row of a read in one statement, in the order asked with the tiebreak last, or a refusal when more than
1439
+ * `MAX_ALL_ROWS` match: it never answers a truncated set.
1440
+ */
1441
+ async function allRows(
1442
+ context: TableContext,
1443
+ run: Runner,
1444
+ scope: OperationNode | undefined,
1445
+ visible: readonly string[],
1446
+ input: unknown,
1447
+ tiebreak: readonly string[],
1448
+ reach?: ReadReach,
1449
+ ): Promise<Readonly<Record<string, unknown>>[]> {
1450
+ const table = context.model.name
1451
+ const options = readOptions(input, ['where', 'orderBy'], 'all')
1452
+ const shape = actionShape(context.model, visible)
1453
+ const conditions = conditionsOf(context, shape, options['where'])
1454
+ const order = orderOf(shape, options['orderBy'], tiebreak)
1455
+ if (scope === undefined) {
1456
+ return []
1457
+ }
1458
+ const dialect = dialectOf(context)
1459
+ const node = selectNode(rowState(table, conditions, order, MAX_ALL_ROWS + 1), visible, scope, undefined, context.model.dates, dialect)
1460
+ const session = await run.read()
1461
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
1462
+ root: 'SelectQueryNode',
1463
+ table,
1464
+ joins: {},
1465
+ scope,
1466
+ subqueries: context.subqueries,
1467
+ through: context.through,
1468
+ })
1469
+ if (rows.length > MAX_ALL_ROWS) {
1470
+ 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`)
1471
+ }
1472
+ const items = answerRows(dialect, table, rowColumnsOf(context.model), rows)
1473
+ return reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach)
1474
+ }
1475
+
1233
1476
  async function countRows(
1234
1477
  context: TableContext,
1235
1478
  run: Runner,
@@ -1239,12 +1482,19 @@ async function countRows(
1239
1482
  ): Promise<number> {
1240
1483
  const table = context.model.name
1241
1484
  const options = readOptions(input, ['where'], 'count')
1242
- const conditions = conditionsOf(actionShape(context.model, visible), options['where'])
1485
+ const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
1243
1486
  if (scope === undefined) {
1244
1487
  return 0
1245
1488
  }
1246
1489
  const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
1247
- const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1490
+ const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
1491
+ root: 'SelectQueryNode',
1492
+ table,
1493
+ joins: {},
1494
+ scope,
1495
+ subqueries: context.subqueries,
1496
+ through: context.through,
1497
+ })
1248
1498
  const count = row === undefined ? '0' : row['count']
1249
1499
  return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
1250
1500
  }