@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.20

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 (80) hide show
  1. package/package.json +35 -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 +229 -40
  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 +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -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 +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
package/src/store.ts CHANGED
@@ -1,5 +1,36 @@
1
- import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
1
+ import { uuidv7 } from '@fabrika/platform'
2
+ import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
2
3
  import { admissions } from './admissions'
4
+ import {
5
+ accessReach,
6
+ type AccessRelation,
7
+ activeRow,
8
+ conditioned,
9
+ conditionedAny,
10
+ everyPath,
11
+ gateTerms,
12
+ heldThrough,
13
+ holdsBesides,
14
+ isIn,
15
+ knownRelation,
16
+ type LayerRelation,
17
+ type MemberReveals,
18
+ memberTerms,
19
+ namesPrincipal,
20
+ noPath,
21
+ type PathRule,
22
+ pathTerms,
23
+ refScope,
24
+ relationCondition,
25
+ relationGate,
26
+ relationSource,
27
+ type RelationSources,
28
+ relationTerms,
29
+ revealedNodes,
30
+ type SplitReach,
31
+ throughPath,
32
+ viewScope,
33
+ } from './authority'
3
34
  import {
4
35
  defineValue,
5
36
  freeze,
@@ -24,18 +55,28 @@ import {
24
55
  type AppGrant,
25
56
  type CapabilityAuthority,
26
57
  type CapabilityGrant,
58
+ type ContainerGrant,
27
59
  describeGrant,
28
60
  MAX_WITHIN_VALUES,
29
61
  type Ref,
30
62
  type RefGrant,
63
+ type RelationHold,
31
64
  type Within,
32
65
  type WithinGrant,
33
66
  } from './capability'
34
- import { type Database, InvocationTransaction, type Session, sessionOf } from './database'
67
+ import { conditionNode, subquery } from './condition-nodes'
68
+ import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
69
+ import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
35
70
  import {
71
+ type ComparableColumn,
72
+ comparableColumnOf,
73
+ type Compare,
74
+ type Condition,
75
+ type Contains,
36
76
  finishSelect,
37
77
  isPrimitive,
38
78
  type JoinShape,
79
+ type JoinState,
39
80
  type NoColumns,
40
81
  type Primitive,
41
82
  type ScopedSelect,
@@ -47,9 +88,11 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
47
88
  import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
48
89
  import { fileReference } from './file-references'
49
90
  import { webhookTables } from './framework-tables'
50
- import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
91
+ import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
51
92
  import { fencedTransaction, jobLeases } from './job-leases'
52
- import { linksPredicate, linkValues } from './links'
93
+ import { jobWakes, leaseProjection } from './job-wakes'
94
+ import { jsonInput } from './json'
95
+ import { linksPredicate, type LinkValue, linkValues } from './links'
53
96
  import {
54
97
  acknowledgement,
55
98
  acknowledgementNode,
@@ -69,6 +112,8 @@ import {
69
112
  scopedWhere,
70
113
  selectNode,
71
114
  updateNode,
115
+ valueList,
116
+ valuesNode,
72
117
  } from './nodes'
73
118
  import { dataAccess } from './orm'
74
119
  import {
@@ -77,39 +122,54 @@ import {
77
122
  type ChildTableName,
78
123
  type Container,
79
124
  type ContainerOf,
125
+ delegates,
80
126
  type DimensionOf,
81
127
  type DimensionTableName,
82
128
  includes,
83
129
  type InsertValues,
84
130
  type JoinableChildren,
85
131
  type ListDimensionOf,
132
+ type MemberRevealModel,
86
133
  modelOf,
87
134
  type MoveAcknowledgement,
88
135
  namesAction,
136
+ nodeColumnOf,
89
137
  type Operation,
90
138
  type ParentOf,
139
+ type PathWriter,
140
+ pathWriters,
91
141
  type PolicyRow,
142
+ type ReadReach,
143
+ type RevealModel,
144
+ type SecondaryPath,
92
145
  type TableModel,
93
146
  type TableModels,
94
147
  tableModels,
95
148
  type Tables,
96
149
  updatableBy,
150
+ updatableByAny,
97
151
  updateActions,
98
152
  type UpdateValues,
99
153
  type VersionArguments,
100
154
  visibleFor,
155
+ visibleThrough,
101
156
  } from './policy'
102
- import { frameworkSideOf, type Locator, register } from './registry'
157
+ import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
103
158
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
104
159
  import { storedFiles, storedFilesMetadata } from './stored-files'
105
160
  import { type TablePolicies, tablePolicies } from './tables'
106
- import { answerDays, dayInput, timestampInput } from './temporal'
161
+ import { answerRows, dayInput, type RowColumns, storedTimestamp, timestampInput } from './temporal'
107
162
 
108
163
  export interface DataLayerRuntime {
109
164
  readonly database: Database
110
165
  readonly capabilities: CapabilityAuthority
111
166
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
112
167
  readonly readOnly?: () => boolean
168
+ /**
169
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
170
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
171
+ */
172
+ readonly projectWakes?: (transaction: Session) => Promise<void>
113
173
  }
114
174
 
115
175
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
@@ -124,7 +184,114 @@ export interface TableContext {
124
184
  readonly destination: TableModel | undefined
125
185
  readonly shape: TableShape
126
186
  readonly joins: Readonly<Record<string, readonly ForeignKeyPair[]>>
187
+ /** The model of each child a select may join, by its table name. */
188
+ readonly children: Readonly<Record<string, TableModel>>
127
189
  readonly connection: Connection
190
+ /** Every relation of the layer with its source table: what a relation term of any table reads. */
191
+ readonly relations: RelationSources
192
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
193
+ readonly members: MemberReveals
194
+ /** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
195
+ readonly subqueries: Readonly<Record<string, readonly string[]>>
196
+ /** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
197
+ readonly through: ViewParent | undefined
198
+ /** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
199
+ readonly writers: readonly PathBound[]
200
+ }
201
+
202
+ /** A path column an insert writes under its bound, and the table that owns the dimension it names. */
203
+ export interface PathBound extends PathWriter {
204
+ readonly owner: TableModel
205
+ }
206
+
207
+ /** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
208
+ export interface ViewParent extends ViewParentLink {
209
+ readonly context: TableContext
210
+ }
211
+
212
+ /** A child view's access views, as the guard admits them on its statements: its key in each view's row column. */
213
+ function viewAccessLinks(model: TableModel, key: string): readonly ViewAccessLink[] {
214
+ const links: ViewAccessLink[] = []
215
+ for (let index = 0; index < model.access.length; index++) {
216
+ const access = model.access[index]
217
+ if (access !== undefined) links[links.length] = freeze({ key, view: access.view, row: access.row })
218
+ }
219
+ return freeze(links)
220
+ }
221
+
222
+ /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
223
+ export function dialectOf(context: TableContext): SqlDialect {
224
+ return runtimeOf(context.connection).database.dialect
225
+ }
226
+
227
+ /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
228
+ export function rowColumnsOf(model: TableModel): RowColumns {
229
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json }
230
+ }
231
+
232
+ /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
233
+ function boundTimestamp(model: TableModel, column: string, value: Primitive): Primitive {
234
+ if (typeof value !== 'string' && !(value instanceof Date)) {
235
+ throw new QueryRefusedError('invalid_value', `${model.name}.${column} takes a Date or ISO 8601 text with Z or an offset`)
236
+ }
237
+ return storedTimestamp(value, `${model.name}.${column}`)
238
+ }
239
+
240
+ /** The values a write binds: on SQLite each timestamp as its stored UTC text, so text order is time order. */
241
+ export function boundValues(context: TableContext, values: ReadonlyMap<string, Primitive | null>): ReadonlyMap<string, Primitive | null> {
242
+ const model = context.model
243
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
244
+ return values
245
+ }
246
+ const bound = new Map<string, Primitive | null>()
247
+ for (const [name, value] of values) {
248
+ bound.set(name, value === null || !inSet(model.timestamps, name) ? value : boundTimestamp(model, name, value))
249
+ }
250
+ return bound
251
+ }
252
+
253
+ /** A term's values as they are bound: on SQLite, one over a timestamp of `model` compares stored UTC text. */
254
+ function boundTerm(model: TableModel, term: Compare | Contains): Compare | Contains {
255
+ const value = term.kind === 'compare' ? term.value : null
256
+ if (term.kind !== 'compare' || value === null || !inSet(model.timestamps, term.column)) {
257
+ return term
258
+ }
259
+ const bind = (item: Primitive): Primitive => boundTimestamp(model, term.column, item)
260
+ return { ...term, value: isList(value) ? value.map(bind) : bind(value) }
261
+ }
262
+
263
+ function isList(value: Primitive | readonly Primitive[]): value is readonly Primitive[] {
264
+ return isArray(value)
265
+ }
266
+
267
+ /** A list's terms over `model`'s columns, as `boundTerm` binds each. */
268
+ export function boundTerms(context: TableContext, model: TableModel, terms: readonly (Compare | Contains)[]): readonly (Compare | Contains)[] {
269
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
270
+ return terms
271
+ }
272
+ return terms.map((term) => boundTerm(model, term))
273
+ }
274
+
275
+ /** A description's conditions over `model`'s columns, an OR group's terms included, as `boundTerm` binds each. */
276
+ function boundConditions(context: TableContext, model: TableModel, conditions: readonly Condition[]): readonly Condition[] {
277
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
278
+ return conditions
279
+ }
280
+ return conditions.map((condition) =>
281
+ condition.kind === 'any' ? { ...condition, conditions: condition.conditions.map((term) => boundTerm(model, term)) } : boundTerm(model, condition)
282
+ )
283
+ }
284
+
285
+ /** A select's conditions, its joined children's included, as they are bound. */
286
+ function boundState(context: TableContext, state: SelectState): SelectState {
287
+ if (dialectOf(context) === 'postgres') {
288
+ return state
289
+ }
290
+ const joins = state.joins.map((join) => {
291
+ const child = ownEntry(context.children, join.join.shape.table)
292
+ return child === undefined ? join : { ...join, select: { ...join.select, conditions: boundConditions(context, child, join.select.conditions) } }
293
+ })
294
+ return { ...state, conditions: boundConditions(context, context.model, state.conditions), joins }
128
295
  }
129
296
 
130
297
  export function runtimeOf(connection: Connection): DataLayerRuntime {
@@ -210,13 +377,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
210
377
  return grant
211
378
  }
212
379
 
213
- /** The chain links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. */
380
+ /**
381
+ * The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
382
+ * table's own dimension counts, so its containers lie above a `Within` of it.
383
+ */
214
384
  function linksAbove(model: TableModel, dimension: string): readonly Container[] {
215
- for (let index = 0; index < model.chain.length; index++) {
216
- if (model.chain[index]?.dimension === dimension) {
385
+ const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
386
+ for (let index = 0; index < links.length; index++) {
387
+ if (links[index]?.dimension === dimension) {
217
388
  const above: Container[] = []
218
- for (let position = index + 1; position < model.chain.length; position++) {
219
- const link = model.chain[position]
389
+ for (let position = index + 1; position < links.length; position++) {
390
+ const link = links[position]
220
391
  if (link !== undefined) {
221
392
  above[above.length] = link
222
393
  }
@@ -227,18 +398,93 @@ function linksAbove(model: TableModel, dimension: string): readonly Container[]
227
398
  return []
228
399
  }
229
400
 
401
+ /**
402
+ * The links of a row that lie inside the `Within`'s own dimension: the object itself for a dimension table, and the
403
+ * chain links nearer than `dimension`. A grant on one of them admits the row as a single-object read admits it.
404
+ */
405
+ function linksBelow(model: TableModel, dimension: string): readonly Container[] {
406
+ const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
407
+ const below: Container[] = []
408
+ for (let index = 0; index < links.length; index++) {
409
+ const link = links[index]
410
+ if (link === undefined || link.dimension === dimension) {
411
+ return below
412
+ }
413
+ below[below.length] = link
414
+ }
415
+ return []
416
+ }
417
+
418
+ /**
419
+ * One `<column> in (values)` per contained grant on a link of the row inside the `Within`'s dimension. A grant on a
420
+ * dimension the table carries no link of admits none of its rows; one on the `Within`'s dimension or above it is refused.
421
+ */
422
+ function containedTests(model: TableModel, grant: WithinGrant): { readonly column: string; readonly values: readonly string[] }[] {
423
+ const below = linksBelow(model, grant.dimension)
424
+ const above = linksAbove(model, grant.dimension)
425
+ const tests: { readonly column: string; readonly values: readonly string[] }[] = []
426
+ for (let index = 0; index < grant.contained.length; index++) {
427
+ const contained = grant.contained[index]
428
+ if (contained === undefined) {
429
+ continue
430
+ }
431
+ if (contained.dimension === grant.dimension || linkOf(above, contained.dimension) !== undefined) {
432
+ throw new CapabilityError(
433
+ 'unenforceable',
434
+ `the Within of ${grant.dimension} carries a grant on ${contained.dimension}, which does not lie inside ${grant.dimension} in ${model.name}`,
435
+ )
436
+ }
437
+ const link = linkOf(below, contained.dimension)
438
+ if (link !== undefined && contained.values.length > 0) {
439
+ tests[tests.length] = { column: link.column, values: contained.values }
440
+ }
441
+ }
442
+ return tests
443
+ }
444
+
445
+ /** The link of `dimension` among `links`, by an index loop: no array method an application could replace. */
446
+ function linkOf(links: readonly Container[], dimension: string): Container | undefined {
447
+ for (let index = 0; index < links.length; index++) {
448
+ const link = links[index]
449
+ if (link !== undefined && link.dimension === dimension) {
450
+ return link
451
+ }
452
+ }
453
+ return undefined
454
+ }
455
+
456
+ /** Every scope value a `Within` carries: its own, its containers' and its contained dimensions'. */
457
+ function withinCount(grant: WithinGrant): number {
458
+ if (grant.values === 'all') {
459
+ return 0
460
+ }
461
+ let count = grant.values.length
462
+ for (let index = 0; index < grant.containers.length; index++) {
463
+ count += grant.containers[index]?.values.length ?? 0
464
+ }
465
+ for (let index = 0; index < grant.contained.length; index++) {
466
+ count += grant.contained[index]?.values.length ?? 0
467
+ }
468
+ for (let index = 0; index < grant.revealing.length; index++) {
469
+ count += grant.revealing[index]?.values.length ?? 0
470
+ }
471
+ return count
472
+ }
473
+
230
474
  /**
231
475
  * `column in (values) or <container column> in (container values) …`, one disjunct per container dimension, so
232
476
  * the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
233
477
  * answers `[]` without a query.
234
478
  */
235
- function withinPredicate(model: TableModel, column: string, grant: WithinGrant): OperationNode | undefined {
479
+ function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
480
+ const model = context.model
481
+ const now = new Date()
236
482
  if (grant.values === 'all') {
237
- return everything()
483
+ return conditioned(model, grant.action, 'all', now)
238
484
  }
239
485
  const above = linksAbove(model, grant.dimension)
240
486
  const predicates: OperationNode[] = []
241
- let count = grant.values.length
487
+ const count = withinCount(grant)
242
488
  if (grant.values.length > 0) {
243
489
  predicates[predicates.length] = inList(model.name, column, grant.values)
244
490
  }
@@ -247,52 +493,236 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
247
493
  if (container === undefined) {
248
494
  continue
249
495
  }
250
- let link: Container | undefined
251
- for (let position = 0; position < above.length; position++) {
252
- if (above[position]?.dimension === container.dimension) {
253
- link = above[position]
254
- }
255
- }
496
+ const link = linkOf(above, container.dimension)
256
497
  if (link === undefined) {
257
498
  throw new CapabilityError(
258
499
  'unenforceable',
259
500
  `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${model.name} carries no column for above ${grant.dimension}; the layer cannot enforce it`,
260
501
  )
261
502
  }
262
- count += container.values.length
263
503
  if (container.values.length > 0) {
264
504
  predicates[predicates.length] = inList(model.name, link.column, container.values)
265
505
  }
266
506
  }
507
+ const contained = containedTests(model, grant)
508
+ for (let index = 0; index < contained.length; index++) {
509
+ const test = contained[index]
510
+ if (test !== undefined) {
511
+ predicates[predicates.length] = inList(model.name, test.column, test.values)
512
+ }
513
+ }
267
514
  if (count > MAX_WITHIN_VALUES) {
268
515
  throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
269
516
  }
270
- return predicates.length === 0 ? undefined : anyOf(predicates)
517
+ addRelationTerms(context, grant, operation === 'read', predicates, now)
518
+ if (operation === 'read') addMemberTerms(context, grant, predicates, now)
519
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
520
+ }
521
+
522
+ /** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
523
+ function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
524
+ const terms = memberTerms(context.members, context.model, grant, now)
525
+ for (let index = 0; index < terms.length; index++) {
526
+ const term = terms[index]
527
+ if (term !== undefined) predicates[predicates.length] = term
528
+ }
529
+ }
530
+
531
+ /** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
532
+ function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
533
+ for (let index = 0; index < grant.relations.length; index++) {
534
+ const hold = grant.relations[index]
535
+ if (hold === undefined) continue
536
+ const terms = relationTerms(
537
+ context.relations,
538
+ context.model,
539
+ hold,
540
+ grant.principal,
541
+ grant.action,
542
+ now,
543
+ reads ? everyPath : noPath,
544
+ )
545
+ for (let position = 0; position < terms.length; position++) {
546
+ const term = terms[position]
547
+ if (term !== undefined) predicates[predicates.length] = term
548
+ }
549
+ }
550
+ }
551
+
552
+ /**
553
+ * The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
554
+ * `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
555
+ * (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
556
+ * Within's lies at no node the column holds, so it reaches no row here.
557
+ */
558
+ function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
559
+ const model = context.model
560
+ const now = new Date()
561
+ if (grant.values === 'all') {
562
+ return conditioned(model, grant.action, 'all', now)
563
+ }
564
+ if (withinCount(grant) > MAX_WITHIN_VALUES) {
565
+ throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
566
+ }
567
+ const predicates: OperationNode[] = []
568
+ for (let index = 0; index < paths.length; index++) {
569
+ const path = paths[index]
570
+ if (path === undefined) continue
571
+ if (grant.values.length > 0) {
572
+ const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
573
+ if (own !== undefined) predicates[predicates.length] = own
574
+ }
575
+ for (let position = 0; position < grant.containers.length; position++) {
576
+ const container = grant.containers[position]
577
+ if (container === undefined || container.values.length === 0) continue
578
+ const above = throughPath(model.name, path, container.dimension, valueList(container.values))
579
+ if (above === undefined) {
580
+ throw new CapabilityError(
581
+ 'unenforceable',
582
+ `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
583
+ )
584
+ }
585
+ predicates[predicates.length] = above
586
+ }
587
+ }
588
+ addRelationTerms(context, grant, true, predicates, now)
589
+ addMemberTerms(context, grant, predicates, now)
590
+ return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
271
591
  }
272
592
 
273
593
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
274
594
  export function selfLinks(model: TableModel): readonly Container[] {
275
595
  const scope = dimensionScope(model)
276
- return [{ dimension: scope.dimension, column: scope.key }, ...model.chain]
596
+ const links: Container[] = [{ dimension: scope.dimension, column: scope.key }]
597
+ for (let index = 0; index < model.chain.length; index++) {
598
+ const link = model.chain[index]
599
+ if (link !== undefined) {
600
+ links[links.length] = link
601
+ }
602
+ }
603
+ return links
277
604
  }
278
605
 
279
- /** This object, over the whole chain the Ref carries. */
280
- export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
606
+ /** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
607
+ export function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode {
281
608
  const scope = dimensionScope(context.model)
282
609
  const grant = refGrant(context, capability, scope.dimension, operation)
283
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
610
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
284
611
  }
285
612
 
286
613
  /** Rows of a dimension table within the scope values of its list dimension. */
287
614
  export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
288
615
  const scope = dimensionScope(context.model)
289
616
  const grant = withinGrant(context, capability, listDimension(scope), operation)
290
- return withinPredicate(context.model, scope.container?.column ?? scope.key, grant)
617
+ return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
618
+ }
619
+
620
+ /**
621
+ * Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
622
+ * of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
623
+ */
624
+ export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
625
+ const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
626
+ const through = context.through
627
+ if (through !== undefined) {
628
+ const parent = through.context
629
+ const now = new Date()
630
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
631
+ const reached = narrowed.length === 0
632
+ ? refScope(parent, parent.model, selfLinks(parent.model), grant, now)
633
+ : splitRefReach(context.model, parent, grant, narrowed, now)
634
+ return viewScope(context.model, through, grant.action, reached, now, row)
635
+ }
636
+ return refScope(context, context.model, context.model.chain, grant, new Date(), row)
637
+ }
638
+
639
+ /** Of `holds`, the relations a child view's `relationWhen` narrows for `action`: each reads the parent through a part of its own. */
640
+ function viewNarrowed(view: TableModel, holds: readonly RelationHold[], action: string): readonly string[] {
641
+ const narrowed: string[] = []
642
+ for (let index = 0; index < holds.length; index++) {
643
+ const relation = holds[index]?.relation ?? ''
644
+ if (relationCondition(view, relation, action) !== undefined && !includes(narrowed, relation)) narrowed[narrowed.length] = relation
645
+ }
646
+ return narrowed
647
+ }
648
+
649
+ /**
650
+ * A Ref's reach of a view's parent, split by the relations the view narrows: the chain with the terms of its other
651
+ * relations, member reveals and paths, and the chain with each narrowed relation's own terms. A part that reaches no
652
+ * parent row adds nothing; none left is unenforceable, never unconditioned.
653
+ */
654
+ function splitRefReach(view: TableModel, parent: TableContext, grant: RefGrant, narrowed: readonly string[], now: Date): SplitReach {
655
+ const model = parent.model
656
+ const chain = linksPredicate(model.name, linkValues(model.name, selfLinks(model), grant))
657
+ const paths = heldThrough(grant.action)
658
+ const others = holdsBesides(grant.relations, narrowed)
659
+ const rest: RefGrant = { ...grant, relations: others }
660
+ const restTerms = others.length === 0 && rest.revealing.length === 0 && rest.paths.length === 0 ? [] : gateTerms(parent, model, rest, now, paths)
661
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
662
+ for (let index = 0; index < grant.relations.length; index++) {
663
+ const hold = grant.relations[index]
664
+ const condition = hold === undefined || !includes(narrowed, hold.relation) ? undefined : relationCondition(view, hold.relation, grant.action)
665
+ const terms = hold === undefined || condition === undefined
666
+ ? []
667
+ : relationTerms(parent.relations, model, hold, grant.principal, grant.action, now, paths)
668
+ if (condition !== undefined && terms.length > 0) relations[relations.length] = { reached: allOf([chain, anyOf(terms)]), condition }
669
+ }
670
+ if (restTerms.length === 0 && relations.length === 0) {
671
+ throw new CapabilityError(
672
+ 'unenforceable',
673
+ `the Ref of ${grant.dimension} is held through relations, member reveals or secondary paths, none of which reaches a row of ${model.name} for ${grant.action}`,
674
+ )
675
+ }
676
+ return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
291
677
  }
292
678
 
293
- /** Rows of a child table that belong to the parent object the Ref names, over the whole chain. */
294
- export function parentPredicate(context: TableContext, grant: RefGrant): OperationNode {
295
- return linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
679
+ /**
680
+ * A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
681
+ * those whose parent row exists. A relation the view narrows (`relationWhen`) reaches the parent through a part of its
682
+ * own, ANDed with the view's condition. The view's own access views list rows beside them. Undefined where nothing is
683
+ * reached: the empty `Within`.
684
+ */
685
+ function throughParent(
686
+ context: TableContext,
687
+ through: ViewParent,
688
+ grant: WithinGrant,
689
+ reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
690
+ ): OperationNode | undefined {
691
+ const now = new Date()
692
+ if (grant.values === 'all') {
693
+ return viewScope(context.model, through, grant.action, 'all', now)
694
+ }
695
+ const own: OperationNode[] = []
696
+ for (let index = 0; index < grant.relations.length; index++) {
697
+ const hold = grant.relations[index]
698
+ const terms = hold === undefined ? [] : accessReach(context.model, hold, grant.principal, grant.action, now)
699
+ for (let position = 0; position < terms.length; position++) {
700
+ const term = terms[position]
701
+ if (term !== undefined) own[own.length] = term
702
+ }
703
+ }
704
+ const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
705
+ if (narrowed.length === 0) {
706
+ const reached = reach(through.context, grant)
707
+ return reached === undefined && own.length === 0 ? undefined : viewScope(context.model, through, grant.action, reached, now, undefined, own)
708
+ }
709
+ const rest = reach(through.context, { ...grant, relations: holdsBesides(grant.relations, narrowed) })
710
+ const relations: { reached: OperationNode; condition: ConditionModel }[] = []
711
+ for (let index = 0; index < grant.relations.length; index++) {
712
+ const hold = grant.relations[index]
713
+ const condition = hold === undefined || !includes(narrowed, hold.relation)
714
+ ? undefined
715
+ : relationCondition(context.model, hold.relation, grant.action)
716
+ const alone: WithinGrant | undefined = hold === undefined
717
+ ? undefined
718
+ : { ...grant, values: [], containers: [], contained: [], revealing: [], relations: [hold] }
719
+ const reached = condition === undefined || alone === undefined ? undefined : reach(through.context, alone)
720
+ if (condition !== undefined && reached !== undefined) relations[relations.length] = { reached, condition }
721
+ }
722
+ if (rest === undefined && relations.length === 0 && own.length === 0) {
723
+ return undefined
724
+ }
725
+ return viewScope(context.model, through, grant.action, { rest, relations }, now, undefined, own)
296
726
  }
297
727
 
298
728
  export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
@@ -306,7 +736,11 @@ export function childListPredicate(context: TableContext, capability: unknown, o
306
736
  throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
307
737
  }
308
738
  checkGrant(context, grant, listDimension(scope.parent), operation)
309
- return withinPredicate(context.model, scope.parent.container?.column ?? scope.column, grant)
739
+ if (context.through !== undefined) {
740
+ const column = scope.parent.container?.column ?? scope.parent.key
741
+ return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
742
+ }
743
+ return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
310
744
  }
311
745
 
312
746
  /**
@@ -326,9 +760,39 @@ export function reachColumn(model: TableModel, dimension: string): string | unde
326
760
  return undefined
327
761
  }
328
762
 
763
+ /**
764
+ * Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
765
+ * view through its parent's, its parent's own dimension included.
766
+ */
767
+ export function reachedBy(context: TableContext, dimension: string): boolean {
768
+ const model = context.through?.context.model ?? context.model
769
+ return parentColumn(model, context.through !== undefined, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
770
+ }
771
+
772
+ /** The column that places a row of `model` in `dimension`, a view's parent's own key among them (`own`). */
773
+ function parentColumn(model: TableModel, own: boolean, dimension: string): string | undefined {
774
+ if (own && model.scope.mode === 'dimension' && model.scope.dimension === dimension) {
775
+ return model.scope.key
776
+ }
777
+ return reachColumn(model, dimension)
778
+ }
779
+
780
+ /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
781
+ export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
782
+ const paths: SecondaryPath[] = []
783
+ for (let index = 0; index < model.readThrough.length; index++) {
784
+ const path = model.readThrough[index]
785
+ if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
786
+ paths[paths.length] = path
787
+ }
788
+ }
789
+ return paths
790
+ }
791
+
329
792
  /**
330
793
  * Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
331
- * `org` through their stamped `org_id`, as under one of `project` through `project_id`.
794
+ * `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
795
+ * table reaches through a secondary path, through that path's column.
332
796
  */
333
797
  export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
334
798
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
@@ -337,23 +801,34 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
337
801
  throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
338
802
  }
339
803
  checkAction(context, 'read', grant.action)
340
- const column = reachColumn(context.model, grant.dimension)
341
- if (column === undefined) {
804
+ if (!reachedBy(context, grant.dimension)) {
342
805
  throw new CapabilityError(
343
806
  'out_of_reach',
344
- `a Within of ${grant.dimension} does not reach ${table}: its containment chain does not hold ${grant.dimension}`,
807
+ `a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
345
808
  )
346
809
  }
347
- return withinPredicate(context.model, column, grant)
810
+ if (context.through !== undefined) {
811
+ return throughParent(context, context.through, grant, (parent, part) => withinReach(parent, part, true))
812
+ }
813
+ return withinReach(context, grant, false)
814
+ }
815
+
816
+ /** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
817
+ function withinReach(context: TableContext, grant: WithinGrant, own: boolean): OperationNode | undefined {
818
+ const column = parentColumn(context.model, own, grant.dimension)
819
+ if (column !== undefined) {
820
+ return withinPredicate(context, column, grant, 'read')
821
+ }
822
+ return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
348
823
  }
349
824
 
350
825
  /**
351
- * A fragment on an UPDATE or DELETE target: the capability's action is that operation's, and an application table is
352
- * written by an `app` capability only, a dimension or child table never by one. An UPDATE may instead hold a column's
353
- * own write action when every column it assigns declares that action (`updatingRef`'s rule); `assigned` is
354
- * `undefined` before the statement is known, and then any such action is taken.
826
+ * A fragment its author marks as an UPDATE or DELETE target: the capability's action is that operation's, and an
827
+ * application table is written by an `app` capability only, a dimension or child table never by one. An UPDATE may
828
+ * instead hold a column's own write action; which columns the statement sets is the author's and the approver's to
829
+ * keep to that action's (`updatableBy`), as the statement is not read for it.
355
830
  */
356
- function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete', assigned: readonly string[] | undefined): void {
831
+ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete'): void {
357
832
  const model = context.model
358
833
  const statement = `${use === 'update' ? 'UPDATE' : 'DELETE'} of ${model.name}`
359
834
  if (grant.kind === 'app' && model.scope.mode !== 'app') {
@@ -363,7 +838,8 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
363
838
  throw new CapabilityError('table_kind', `a scoped site writes no application table: ${statement} needs the capability of an app endpoint`)
364
839
  }
365
840
  const actions = model.actions[use]
366
- if (includes(actions, grant.action)) {
841
+ const held = grantActions(grant)
842
+ if (admitted(held, actions).length > 0) {
367
843
  return
368
844
  }
369
845
  const columnWrites: string[] = []
@@ -375,50 +851,83 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
375
851
  if (actions.length === 0 && columnWrites.length === 0) {
376
852
  throw new CapabilityError('undeclared_operation', `${statement}: its policy declares no ${use} action`)
377
853
  }
378
- if (!includes(columnWrites, grant.action)) {
854
+ if (admitted(held, columnWrites).length === 0) {
379
855
  const needs = actions.length === 0 ? [] : [`its ${use} action ${actions.join(' or ')}`]
380
856
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
381
- throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
382
- }
383
- if (assigned === undefined) {
384
- return
857
+ throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${held.join(', ')}`)
385
858
  }
386
- const written = updatableBy(model, grant.action)
387
- const outside: string[] = assigned.length === 0 ? ['no column it can name'] : []
388
- for (let index = 0; index < assigned.length; index++) {
389
- const column = assigned[index]
390
- if (column !== undefined && !inSet(written, column)) outside[outside.length] = column
859
+ }
860
+
861
+ /** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
862
+ export function grantActions(grant: CapabilityGrant): readonly string[] {
863
+ return grant.kind === 'app' ? grant.actions : [grant.action]
864
+ }
865
+
866
+ /** The actions of `held` that `allowed` lists: those that allow an operation, as any one of them does. */
867
+ function admitted(held: readonly string[], allowed: readonly string[]): string[] {
868
+ const found: string[] = []
869
+ for (let index = 0; index < held.length; index++) {
870
+ const action = held[index]
871
+ if (action !== undefined && includes(allowed, action)) {
872
+ found[found.length] = action
873
+ }
391
874
  }
392
- if (outside.length > 0) {
393
- throw new CapabilityError(
394
- 'wrong_action',
395
- `${statement} assigns ${
396
- outside.join(', ')
397
- }, which ${grant.action} does not write: a column's own write action scopes an UPDATE of its columns only`,
398
- )
875
+ return found
876
+ }
877
+
878
+ /** The first of `actions` the table narrows with a `when`: a fragment, which renders column tests only, cannot hold it. */
879
+ function heldCondition(model: TableModel, actions: readonly string[]): string | undefined {
880
+ for (let index = 0; index < actions.length; index++) {
881
+ const action = actions[index]
882
+ if (action !== undefined && hasOwn(model.when, action)) {
883
+ return action
884
+ }
399
885
  }
886
+ return undefined
400
887
  }
401
888
 
402
889
  /**
403
890
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
404
891
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
405
892
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
406
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
407
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
408
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
409
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
893
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
894
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
895
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
896
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
897
+ * every row.
410
898
  */
411
- export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms {
899
+ export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms {
412
900
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
413
901
  const model = context.model
414
902
  if (grant.kind === 'row') {
415
903
  throw new CapabilityError('wrong_capability', `ctx.sql.scope takes a Ref, a Within or an app capability, got ${describeGrant(grant)}`)
416
904
  }
417
905
  if (use !== 'read') {
418
- checkWriteTarget(context, grant, use, assigned)
906
+ checkWriteTarget(context, grant, use)
907
+ }
908
+ // The fragment renders column tests only; a relation's, a member reveal's or a path's subquery, or an action's condition, would be left out.
909
+ const held = grant.kind !== 'app'
910
+ && (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
911
+ // An `'any'` read is unconditioned: a `when` keyed by the action narrows only its writes.
912
+ const readsEvery = grant.kind === 'app' && use === 'read' && readsAny(context, grant)
913
+ const conditionedBy = readsEvery ? undefined : heldCondition(model, grantActions(grant))
914
+ if (held || conditionedBy !== undefined) {
915
+ throw new CapabilityError(
916
+ 'unenforceable',
917
+ `ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${
918
+ conditionedBy ?? grantActions(grant).join(', ')
919
+ } on ${model.name}: read it through ctx.db`,
920
+ )
921
+ }
922
+ // Nor the subquery through the parent row, which alone places a child view's rows.
923
+ if (grant.kind !== 'app' && context.through !== undefined) {
924
+ throw new CapabilityError(
925
+ 'unenforceable',
926
+ `ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
927
+ )
419
928
  }
420
929
  if (grant.kind === 'app') {
421
- if (use === 'read') {
930
+ if (use === 'read' && !readsEvery) {
422
931
  // The action is held as a global grant, so its scope is every row of a table it reaches.
423
932
  checkAppReach(context, grant)
424
933
  }
@@ -443,7 +952,22 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
443
952
  if (use === 'read' && !namesAction(model, grant.action)) {
444
953
  throw new CapabilityError('wrong_action', `${model.name} does not name the action ${grant.action}: a Ref reads it with an action it names`)
445
954
  }
446
- return [linkValues(model.name, links.slice(start), grant).map(({ link, value }) => ({ column: link.column, value }))]
955
+ const reached: Container[] = []
956
+ for (let index = start; index < links.length; index++) {
957
+ const link = links[index]
958
+ if (link !== undefined) {
959
+ reached[reached.length] = link
960
+ }
961
+ }
962
+ const values = linkValues(model.name, reached, grant)
963
+ const tests: ScopeTest[] = []
964
+ for (let index = 0; index < values.length; index++) {
965
+ const entry = values[index]
966
+ if (entry !== undefined) {
967
+ tests[tests.length] = { column: entry.link.column, value: entry.value }
968
+ }
969
+ }
970
+ return [tests]
447
971
  }
448
972
  const column = reachColumn(model, grant.dimension)
449
973
  if (column === undefined) {
@@ -463,21 +987,31 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
463
987
  }
464
988
  const above = linksAbove(model, grant.dimension)
465
989
  const groups: ScopeTest[][] = []
466
- let count = grant.values.length
990
+ const count = withinCount(grant)
467
991
  if (grant.values.length > 0) {
468
- groups.push([{ column, value: grant.values }])
992
+ groups[groups.length] = [{ column, value: grant.values }]
469
993
  }
470
- for (const container of grant.containers) {
471
- const link = above.find((candidate) => candidate.dimension === container.dimension)
994
+ for (let index = 0; index < grant.containers.length; index++) {
995
+ const container = grant.containers[index]
996
+ if (container === undefined) {
997
+ continue
998
+ }
999
+ const link = linkOf(above, container.dimension)
472
1000
  if (link === undefined) {
473
1001
  throw new CapabilityError(
474
1002
  'unenforceable',
475
1003
  `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${model.name} carries no column for above ${grant.dimension}; the layer cannot enforce it`,
476
1004
  )
477
1005
  }
478
- count += container.values.length
479
1006
  if (container.values.length > 0) {
480
- groups.push([{ column: link.column, value: container.values }])
1007
+ groups[groups.length] = [{ column: link.column, value: container.values }]
1008
+ }
1009
+ }
1010
+ const contained = containedTests(model, grant)
1011
+ for (let index = 0; index < contained.length; index++) {
1012
+ const test = contained[index]
1013
+ if (test !== undefined) {
1014
+ groups[groups.length] = [{ column: test.column, value: test.values }]
481
1015
  }
482
1016
  }
483
1017
  if (count > MAX_WITHIN_VALUES) {
@@ -517,32 +1051,63 @@ export function updatingRef(context: TableContext, capability: unknown, dimensio
517
1051
  */
518
1052
  export type AppReach = 'rows' | 'counts'
519
1053
 
520
- /** Refuses an `app` capability whose action does not reach `reach` of a dimension or child table. */
521
- function checkRecordReach(context: TableContext, grant: AppGrant, reach: AppReach): void {
1054
+ /**
1055
+ * The actions of an `app` capability that reach `reach` of a dimension or child table, at least one: its read action and
1056
+ * its `appRead`, and for `counts` its `appCount` too. Refuses a capability none of whose actions does.
1057
+ */
1058
+ function recordReach(context: TableContext, grant: AppGrant, reach: AppReach): readonly string[] {
522
1059
  const model = context.model
523
1060
  const { appRead, appCount } = model.actions
524
1061
  const read = model.actions.read.join(' or ')
525
- if (
526
- includes(model.actions.read, grant.action) || includes(appRead, grant.action) || (reach === 'counts' && includes(appCount, grant.action))
527
- ) {
528
- return
1062
+ const reaching = admitted(grant.actions, model.actions.read)
1063
+ const reads = admitted(grant.actions, appRead)
1064
+ for (let index = 0; index < reads.length; index++) {
1065
+ reaching[reaching.length] = reads[index] ?? ''
1066
+ }
1067
+ const counts = admitted(grant.actions, appCount)
1068
+ if (reach === 'counts') {
1069
+ for (let index = 0; index < counts.length; index++) {
1070
+ reaching[reaching.length] = counts[index] ?? ''
1071
+ }
529
1072
  }
530
- if (includes(appCount, grant.action)) {
1073
+ if (reaching.length > 0) {
1074
+ return reaching
1075
+ }
1076
+ const held = grant.actions.join(', ')
1077
+ if (counts.length > 0) {
531
1078
  throw new CapabilityError(
532
1079
  'wrong_action',
533
- `an app capability of ${grant.action} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
1080
+ `an app capability of ${held} only counts ${model.name} (its appCount): it reads no row, so list, aggregate and a scope fragment need its read action ${read}${
534
1081
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
535
1082
  }`,
536
1083
  )
537
1084
  }
538
1085
  throw new CapabilityError(
539
1086
  'wrong_action',
540
- `an app capability of ${grant.action} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
1087
+ `an app capability of ${held} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
541
1088
  appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
542
1089
  } only`,
543
1090
  )
544
1091
  }
545
1092
 
1093
+ /** The actions of an `app` capability the application table names; refuses a capability none of whose actions it names. */
1094
+ function namedActions(model: TableModel, grant: AppGrant): readonly string[] {
1095
+ const named: string[] = []
1096
+ for (let index = 0; index < grant.actions.length; index++) {
1097
+ const action = grant.actions[index]
1098
+ if (action !== undefined && namesAction(model, action)) {
1099
+ named[named.length] = action
1100
+ }
1101
+ }
1102
+ if (named.length === 0) {
1103
+ throw new CapabilityError(
1104
+ 'wrong_action',
1105
+ `an app capability of ${grant.actions.join(', ')} does not reach ${model.name}: ${model.name} does not name the action`,
1106
+ )
1107
+ }
1108
+ return named
1109
+ }
1110
+
546
1111
  /**
547
1112
  * Refuses a table `ctx.db.app` does not list for the capability (`applicationTables` in `orm.ts`): it lists an
548
1113
  * application table under any action the table names, and the rows of a dimension or child table under its read
@@ -552,12 +1117,7 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
552
1117
  const model = context.model
553
1118
  const mode = model.scope.mode
554
1119
  if (mode === 'app') {
555
- if (!namesAction(model, grant.action)) {
556
- throw new CapabilityError(
557
- 'wrong_action',
558
- `an app capability of ${grant.action} does not reach ${model.name}: ${model.name} does not name the action`,
559
- )
560
- }
1120
+ namedActions(model, grant)
561
1121
  return
562
1122
  }
563
1123
  if (mode !== 'dimension' && mode !== 'child') {
@@ -566,14 +1126,20 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
566
1126
  `an app capability does not reach ${model.name}: ctx.db.app lists application, dimension and child tables only`,
567
1127
  )
568
1128
  }
569
- checkRecordReach(context, grant, 'rows')
1129
+ recordReach(context, grant, 'rows')
1130
+ }
1131
+
1132
+ /** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
1133
+ export interface AppRead {
1134
+ readonly predicate: OperationNode
1135
+ readonly reach: ReadReach
570
1136
  }
571
1137
 
572
1138
  /**
573
- * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`: `true`, for an action that
574
- * reaches `reach` (`checkRecordReach`).
1139
+ * Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
1140
+ * `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
575
1141
  */
576
- export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1142
+ export function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead {
577
1143
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
578
1144
  const model = context.model
579
1145
  if (grant.kind !== 'app') {
@@ -585,8 +1151,13 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
585
1151
  if (model.scope.mode !== 'dimension' && model.scope.mode !== 'child') {
586
1152
  throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
587
1153
  }
588
- checkRecordReach(context, grant, reach)
589
- return everything()
1154
+ const actions = recordReach(context, grant, reach)
1155
+ return { predicate: conditionedAny(model, actions, 'all', new Date()), reach: freeze({ actions, narrowed: true }) }
1156
+ }
1157
+
1158
+ /** `appRecordRead`'s rows. */
1159
+ export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
1160
+ return appRecordRead(context, capability, reach).predicate
590
1161
  }
591
1162
 
592
1163
  /** An `app` capability addresses a row by its key, and writes, only in an application table. */
@@ -600,10 +1171,11 @@ function checkApplicationTable(context: TableContext, operation: Operation): voi
600
1171
  }
601
1172
 
602
1173
  /**
603
- * The capability of an `app` endpoint for `operation` on `table`: its action is that operation's. An application table
604
- * is written with it, and a dimension or child table read with it.
1174
+ * The capability of an `app` endpoint for `operation` on `table`, and its actions that are that operation's, at least
1175
+ * one. An application table is written with it, and a dimension or child
1176
+ * table read with it.
605
1177
  */
606
- function appGrant(context: TableContext, capability: unknown, operation: Operation): AppGrant {
1178
+ function appGrant(context: TableContext, capability: unknown, operation: Operation): AppOperation {
607
1179
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
608
1180
  const table = context.model.name
609
1181
  if (grant.kind !== 'app') {
@@ -612,22 +1184,82 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
612
1184
  if (operation !== 'read') {
613
1185
  checkApplicationTable(context, operation)
614
1186
  }
1187
+ if (operation === 'read' && readsAny(context, grant)) {
1188
+ return { grant, actions: grant.actions, narrowed: false }
1189
+ }
615
1190
  checkAppReach(context, grant)
616
- checkAction(context, operation, grant.action)
617
- return grant
1191
+ return { grant, actions: operationActions(context, operation, grant), narrowed: true }
1192
+ }
1193
+
1194
+ /**
1195
+ * An `app` capability and those of its actions that allow one operation: every one it holds for a read of a table read
1196
+ * with `'any'`, which no `when` narrows.
1197
+ */
1198
+ interface AppOperation extends ReadReach {
1199
+ readonly grant: AppGrant
1200
+ }
1201
+
1202
+ /** The actions of `grant` that allow `operation` on the table, at least one; `checkAction` over a set. */
1203
+ function operationActions(context: TableContext, operation: Operation, grant: AppGrant): readonly string[] {
1204
+ const actions = requiredActions(context, operation)
1205
+ const allowing = admitted(grant.actions, actions)
1206
+ if (allowing.length === 0) {
1207
+ throw new CapabilityError(
1208
+ 'wrong_action',
1209
+ `${operation} on ${context.model.name} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`,
1210
+ )
1211
+ }
1212
+ return allowing
1213
+ }
1214
+
1215
+ /**
1216
+ * Whether `grant` reads `context`'s table because it is read with `'any'`: every `app` grant but a public procedure's,
1217
+ * which is refused there. The read is unconditioned: a `when` of the grant's action narrows only its writes.
1218
+ */
1219
+ function readsAny(context: TableContext, grant: AppGrant): boolean {
1220
+ const model = context.model
1221
+ if (model.scope.mode !== 'app' || !model.actions.readAny) {
1222
+ return false
1223
+ }
1224
+ if (grant.public) {
1225
+ throw new CapabilityError(
1226
+ 'wrong_capability',
1227
+ `a public procedure does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1228
+ )
1229
+ }
1230
+ return true
1231
+ }
1232
+
1233
+ /**
1234
+ * The rows `held`, the read actions of an `app` capability, read of `context`'s table within `branch`: narrowed by their
1235
+ * conditions, any one admitting a row, unless the table is read with `'any'`.
1236
+ */
1237
+ function appReadPredicate(context: TableContext, held: AppOperation, branch: OperationNode | 'all'): OperationNode {
1238
+ if (context.model.scope.mode === 'app' && context.model.actions.readAny) {
1239
+ return branch === 'all' ? ValueNode.createImmediate(true) : branch
1240
+ }
1241
+ return conditionedAny(context.model, held.actions, branch, new Date())
1242
+ }
1243
+
1244
+ /**
1245
+ * Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
1246
+ * `'any'`, and the reach whose columns it answers.
1247
+ */
1248
+ export function appListRead(context: TableContext, capability: unknown): AppRead {
1249
+ const held = appGrant(context, capability, 'read')
1250
+ return { predicate: appReadPredicate(context, held, 'all'), reach: freeze({ actions: held.actions, narrowed: held.narrowed }) }
618
1251
  }
619
1252
 
620
- /** Every row a capability of an `app` endpoint reads in `table`, by the table's read action: `true`. */
1253
+ /** `appListRead`'s rows. */
621
1254
  export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
622
- appGrant(context, capability, 'read')
623
- return everything()
1255
+ return appListRead(context, capability).predicate
624
1256
  }
625
1257
 
626
1258
  /**
627
1259
  * Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
628
1260
  * or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
629
1261
  */
630
- export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
1262
+ export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
631
1263
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
632
1264
  const model = context.model
633
1265
  if (model.scope.mode !== 'app') {
@@ -636,6 +1268,12 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
636
1268
  if (grant.kind === 'app') {
637
1269
  throw new CapabilityError('wrong_capability', `a read of ${model.name} from a scoped site needs a Ref or a Within, got ${describeGrant(grant)}`)
638
1270
  }
1271
+ if (model.actions.readAny) {
1272
+ throw new CapabilityError(
1273
+ 'wrong_capability',
1274
+ `a scoped site does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
1275
+ )
1276
+ }
639
1277
  const read = requiredActions(context, 'read')
640
1278
  if (!includes(read, grant.action)) {
641
1279
  throw new CapabilityError(
@@ -643,14 +1281,15 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
643
1281
  `a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
644
1282
  )
645
1283
  }
646
- return everything()
1284
+ return conditioned(model, grant.action, branch, new Date())
647
1285
  }
648
1286
 
649
1287
  /** One row of an application table by its key, for an `app` capability of `operation`'s action. */
650
1288
  export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
651
1289
  checkApplicationTable(context, operation)
652
- appGrant(context, capability, operation)
653
- return appKeyPredicate(context.model, key)
1290
+ const held = appGrant(context, capability, operation)
1291
+ const row = appKeyPredicate(context.model, key)
1292
+ return operation === 'read' ? appReadPredicate(context, held, row) : conditionedAny(context.model, held.actions, row, new Date())
654
1293
  }
655
1294
 
656
1295
  /**
@@ -660,14 +1299,20 @@ export function appRowPredicate(context: TableContext, capability: unknown, key:
660
1299
  export function claimScope(
661
1300
  context: TableContext,
662
1301
  capability: unknown,
663
- ): { readonly grant: AppGrant | WithinGrant; readonly scope: OperationNode | undefined } {
1302
+ ): { readonly grant: AppGrant | WithinGrant; readonly action: string; readonly scope: OperationNode | undefined } {
664
1303
  const model = context.model
665
1304
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
666
1305
  if (model.queue === undefined) {
667
1306
  throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
668
1307
  }
669
1308
  if (grant.kind === 'app') {
670
- return { grant: appGrant(context, capability, 'update'), scope: everything() }
1309
+ const [action, ...more] = grant.actions
1310
+ // A claimed row's `row.ref` is finished under one action; only a job claims, and its `ctx.app(action)` holds one.
1311
+ if (more.length > 0) {
1312
+ throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a capability of one action, got one of ${grant.actions.join(', ')}`)
1313
+ }
1314
+ appGrant(context, capability, 'update')
1315
+ return { grant, action, scope: conditioned(model, action, 'all', new Date()) }
671
1316
  }
672
1317
  if (grant.kind !== 'within') {
673
1318
  throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
@@ -683,7 +1328,7 @@ export function claimScope(
683
1328
  `a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
684
1329
  )
685
1330
  }
686
- return { grant, scope: withinPredicate(model, column, grant) }
1331
+ return { grant, action: grant.action, scope: withinPredicate(context, column, grant, 'update') }
687
1332
  }
688
1333
 
689
1334
  /**
@@ -706,7 +1351,17 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
706
1351
  }
707
1352
  terms[terms.length] = equals(model.name, link.column, value)
708
1353
  }
709
- return allOf(terms)
1354
+ return conditioned(model, grant.action, allOf(terms), new Date())
1355
+ }
1356
+
1357
+ /** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
1358
+ export function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1359
+ return conditionedAny(model, actions, appKeyPredicate(model, key), new Date())
1360
+ }
1361
+
1362
+ /** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
1363
+ export function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
1364
+ return model.actions.readAny ? appKeyPredicate(model, key) : appKeyScope(model, actions, key)
710
1365
  }
711
1366
 
712
1367
  /** The row of an application table `key` names. */
@@ -718,10 +1373,10 @@ export function appKeyPredicate(model: TableModel, key: unknown): OperationNode
718
1373
  }
719
1374
 
720
1375
  /**
721
- * The capability of an `app` endpoint whose action updates columns of an application table: its update action, or a
722
- * column's own write action. Which columns it updates follows from the action (`updatableBy`).
1376
+ * The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
1377
+ * action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
723
1378
  */
724
- export function updatingApp(context: TableContext, capability: unknown): AppGrant {
1379
+ export function updatingApp(context: TableContext, capability: unknown): readonly string[] {
725
1380
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
726
1381
  const table = context.model.name
727
1382
  if (grant.kind !== 'app') {
@@ -732,29 +1387,91 @@ export function updatingApp(context: TableContext, capability: unknown): AppGran
732
1387
  if (actions.length === 0) {
733
1388
  throw new CapabilityError('undeclared_operation', `${table} allows no update; its policy declares no update action`)
734
1389
  }
735
- for (let index = 0; index < actions.length; index++) {
736
- if (actions[index] === grant.action) {
737
- return grant
738
- }
739
- }
740
- throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.action}`)
741
- }
742
-
743
- export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
744
- const scope = childScope(context)
745
- if (typeof key !== 'string' || key.length === 0) {
746
- throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
1390
+ const updating = admitted(grant.actions, actions)
1391
+ if (updating.length === 0) {
1392
+ throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`)
747
1393
  }
748
- const grant = refGrant(context, parent, scope.parent.dimension, operation)
749
- return allOf([equals(context.model.name, scope.key, key), parentPredicate(context, grant)])
750
- }
751
-
752
- export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
753
- return { root, table: context.model.name, joins: root === 'SelectQueryNode' ? context.joins : {}, scope }
1394
+ return updating
754
1395
  }
755
1396
 
756
1397
  /**
757
- * Where a table operation's statements run: a store's own sessions, one transaction per mutation, or the mini-ORM's
1398
+ * An `app` capability's update of the application table row `key`: `values`, read against the columns its update
1399
+ * actions write, and the row's scope under only those actions that write every given column, any one's condition
1400
+ * admitting the row. So several held actions never write one action's columns on rows only another one reaches.
1401
+ */
1402
+ export function appUpdate(
1403
+ context: TableContext,
1404
+ capability: unknown,
1405
+ key: unknown,
1406
+ values: unknown,
1407
+ ): { readonly scope: OperationNode; readonly changes: Map<string, Primitive | null> } {
1408
+ const model = context.model
1409
+ const updating = updatingApp(context, capability)
1410
+ const writable = updatableByAny(model, updating)
1411
+ const changes = readValues(values, writable, 'update', model)
1412
+ // `readValues` took only columns of `writable`, so those of them `changes` sets are every column it sets.
1413
+ const columns = namesOf(writable)
1414
+ const written: string[] = []
1415
+ for (let index = 0; index < columns.length; index++) {
1416
+ const name = columns[index] ?? ''
1417
+ if (changes.has(name)) {
1418
+ written[written.length] = name
1419
+ }
1420
+ }
1421
+ const covering: string[] = []
1422
+ for (let index = 0; index < updating.length; index++) {
1423
+ const action = updating[index]
1424
+ if (action !== undefined && writesEvery(updatableBy(model, action), written)) {
1425
+ covering[covering.length] = action
1426
+ }
1427
+ }
1428
+ if (covering.length === 0) {
1429
+ throw new CapabilityError(
1430
+ 'wrong_action',
1431
+ `no action of ${updating.join(', ')} updates every column of this update of ${model.name} (${
1432
+ written.join(', ')
1433
+ }): update the columns of each action apart`,
1434
+ )
1435
+ }
1436
+ return { scope: appKeyScope(model, covering, key), changes }
1437
+ }
1438
+
1439
+ /** Whether `columns` holds each of `written`. */
1440
+ function writesEvery(columns: NameSet, written: readonly string[]): boolean {
1441
+ for (let index = 0; index < written.length; index++) {
1442
+ if (!inSet(columns, written[index])) {
1443
+ return false
1444
+ }
1445
+ }
1446
+ return true
1447
+ }
1448
+
1449
+ export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
1450
+ const scope = childScope(context)
1451
+ if (typeof key !== 'string' || key.length === 0) {
1452
+ throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
1453
+ }
1454
+ const grant = refGrant(context, parent, scope.parent.dimension, operation)
1455
+ return parentPredicate(context, grant, key)
1456
+ }
1457
+
1458
+ export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
1459
+ // Every store write reaches its statement through here: a view's rows are its tables', never written (ADR-0072).
1460
+ if (context.model.view && root !== 'SelectQueryNode') {
1461
+ throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
1462
+ }
1463
+ return {
1464
+ root,
1465
+ table: context.model.name,
1466
+ joins: root === 'SelectQueryNode' ? context.joins : {},
1467
+ scope,
1468
+ subqueries: context.subqueries,
1469
+ through: context.through,
1470
+ }
1471
+ }
1472
+
1473
+ /**
1474
+ * Where a table operation's statements run: a store's own sessions, one transaction per mutation, or the mini-ORM's
758
1475
  * invocation transaction (`orm.ts`), where every statement of a handler runs in one.
759
1476
  */
760
1477
  export interface Runner {
@@ -776,9 +1493,29 @@ export function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Ses
776
1493
  return fence === null ? session.transaction(work) : fencedTransaction(session, fence, work)
777
1494
  }
778
1495
 
779
- /** The action a capability holds, which its operation's checks already admitted. */
1496
+ /**
1497
+ * The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
1498
+ * capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
1499
+ */
780
1500
  export function heldAction(context: TableContext, capability: unknown): string {
781
- return runtimeOf(context.connection).capabilities.resolve(capability).action
1501
+ const grant = runtimeOf(context.connection).capabilities.resolve(capability)
1502
+ if (grant.kind !== 'app') {
1503
+ return grant.action
1504
+ }
1505
+ const [action, ...more] = grant.actions
1506
+ if (more.length > 0) {
1507
+ throw new CapabilityError(
1508
+ 'wrong_capability',
1509
+ `this read takes a capability of one action, got one of ${grant.actions.join(', ')}: read through ctx.db.app`,
1510
+ )
1511
+ }
1512
+ return action
1513
+ }
1514
+
1515
+ /** The one action a capability holds, or `undefined` for an `anyOf` endpoint's `app` capability that holds several. */
1516
+ function soleAction(context: TableContext, capability: unknown): string | undefined {
1517
+ const actions = grantActions(runtimeOf(context.connection).capabilities.resolve(capability))
1518
+ return actions.length === 1 ? actions[0] : undefined
782
1519
  }
783
1520
 
784
1521
  function storeRunner(context: TableContext): Runner {
@@ -830,6 +1567,10 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
830
1567
  copied.set(key, fileValue(model, key, value))
831
1568
  continue
832
1569
  }
1570
+ if (inSet(model.json, key)) {
1571
+ copied.set(key, value === null ? null : jsonInput(value, `${table}.${key}`))
1572
+ continue
1573
+ }
833
1574
  if (value !== null && !isPrimitive(value)) {
834
1575
  throw new QueryRefusedError('invalid_argument', `${table}.${key} takes a plain value (string, number, bigint, boolean, Date or null)`)
835
1576
  }
@@ -879,69 +1620,114 @@ async function selectRows<S>(
879
1620
  context: TableContext,
880
1621
  scope: OperationNode | undefined,
881
1622
  state: SelectState,
882
- action: string,
1623
+ action: string | undefined,
883
1624
  visible: readonly string[] = context.model.visible,
884
1625
  ): Promise<S[]> {
885
1626
  const run = storeRunner(context)
1627
+ const now = new Date()
1628
+ const joins: JoinState[] = []
886
1629
  for (let index = 0; index < state.joins.length; index++) {
887
1630
  const join = state.joins[index]
888
- if (join !== undefined && !includes(join.join.readActions, action)) {
1631
+ if (join === undefined) continue
1632
+ if (action === undefined) {
1633
+ throw new CapabilityError('wrong_capability', `joining ${join.join.shape.table} takes a capability of one action, whose condition narrows it`)
1634
+ }
1635
+ if (!includes(join.join.readActions, action)) {
889
1636
  throw new CapabilityError(
890
1637
  'wrong_action',
891
1638
  `joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
892
1639
  )
893
1640
  }
1641
+ joins[joins.length] = heldJoin(context, join, action, now)
894
1642
  }
895
1643
  if (scope === undefined) {
896
1644
  return []
897
1645
  }
898
- const node = selectNode(state, visible, scope, undefined, context.model.dates)
1646
+ const dialect = dialectOf(context)
1647
+ const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
899
1648
  const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
900
- return answerDays(context.model.name, joinedDays(context.model.dates, state), rows)
1649
+ return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
1650
+ }
1651
+
1652
+ /**
1653
+ * `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
1654
+ * subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
1655
+ */
1656
+ function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
1657
+ const child = ownEntry(context.children, join.join.shape.table)
1658
+ if (child === undefined) {
1659
+ throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
1660
+ }
1661
+ const condition = ownEntry(child.when, action)
1662
+ if (condition === undefined) {
1663
+ return join
1664
+ }
1665
+ let reads = false
1666
+ conditionReach(condition, () => {
1667
+ reads = true
1668
+ })
1669
+ if (reads) {
1670
+ throw new CapabilityError(
1671
+ 'unenforceable',
1672
+ `joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
1673
+ )
1674
+ }
1675
+ return { ...join, condition: conditionNode(child.name, condition, now) }
901
1676
  }
902
1677
 
903
- /** The `date` columns of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
904
- function joinedDays(own: NameSet, state: SelectState): NameSet {
1678
+ /** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
1679
+ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1680
+ const own = rowColumnsOf(context.model)
905
1681
  if (state.joins.length === 0) {
906
1682
  return own
907
1683
  }
908
- const names: string[] = []
909
- const ownDates = namesOf(own)
910
- for (let index = 0; index < ownDates.length; index++) {
911
- names[names.length] = ownDates[index] ?? ''
912
- }
913
- for (let index = 0; index < state.joins.length; index++) {
914
- const shape = state.joins[index]?.join.shape
915
- const dates = shape === undefined ? [] : namesOf(shape.dates)
916
- for (let position = 0; position < dates.length; position++) {
917
- names[names.length] = `${shape?.table}.${dates[position]}`
1684
+ const joined = (pick: (columns: RowColumns) => NameSet): NameSet => {
1685
+ const names: string[] = []
1686
+ const owned = namesOf(pick(own))
1687
+ for (let index = 0; index < owned.length; index++) {
1688
+ names[names.length] = owned[index] ?? ''
918
1689
  }
1690
+ for (let index = 0; index < state.joins.length; index++) {
1691
+ const table = state.joins[index]?.join.shape.table ?? ''
1692
+ const child = ownEntry(context.children, table)
1693
+ const columns = child === undefined ? [] : namesOf(pick(rowColumnsOf(child)))
1694
+ for (let position = 0; position < columns.length; position++) {
1695
+ names[names.length] = `${table}.${columns[position]}`
1696
+ }
1697
+ }
1698
+ return nameSet(names)
1699
+ }
1700
+ return {
1701
+ days: joined((columns) => columns.days),
1702
+ timestamps: joined((columns) => columns.timestamps),
1703
+ booleans: joined((columns) => columns.booleans),
1704
+ json: joined((columns) => columns.json),
919
1705
  }
920
- return nameSet(names)
921
1706
  }
922
1707
 
923
1708
  /**
924
1709
  * One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
925
- * `action` is what read it: each file column then answers a reference that reads the file only under a read action.
1710
+ * `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
926
1711
  */
927
1712
  export async function selectOne<O>(
928
1713
  context: TableContext,
929
1714
  run: Runner,
930
1715
  scope: OperationNode,
931
1716
  visible = context.model.visible,
932
- action?: string,
1717
+ reach?: ReadReach,
933
1718
  ): Promise<O> {
934
1719
  const start = startSelect(context.shape)
935
1720
  const state = finishSelect(start, start)
936
- const node = selectNode(state, visible, scope, undefined, context.model.dates)
1721
+ const dialect = dialectOf(context)
1722
+ const node = selectNode(state, visible, scope, undefined, context.model.dates, dialect)
937
1723
  const session = await run.read()
938
1724
  const rows = await session.run<O>(node, guard(context, 'SelectQueryNode', scope))
939
- const [row] = answerDays(context.model.name, context.model.dates, rows)
1725
+ const [row] = answerRows(dialect, context.model.name, rowColumnsOf(context.model), rows)
940
1726
  if (row === undefined) {
941
1727
  throw new NotFoundError(`${context.model.name} not found`)
942
1728
  }
943
- if (action !== undefined) {
944
- await answerFiles(context.model, run.files, session, [row], action)
1729
+ if (reach !== undefined) {
1730
+ await answerFiles(context.model, run.files, session, [row], reach)
945
1731
  }
946
1732
  return row
947
1733
  }
@@ -1011,28 +1797,55 @@ export function keyOf(model: TableModel): string {
1011
1797
  * Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
1012
1798
  * Ref minted before its object moved would insert into, or move rows into, the object's new container.
1013
1799
  */
1014
- async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
1800
+ async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<void> {
1801
+ if (!(await destinationHeld(transaction, context, grant, paths))) {
1802
+ throw context.destination === undefined
1803
+ ? new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
1804
+ : new NotFoundError(`${context.destination.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1805
+ }
1806
+ }
1807
+
1808
+ /** Whether the destination still lies where `grant`'s chain says and still holds it, locked `for share` (`lockDestination`). */
1809
+ async function destinationHeld(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
1015
1810
  const owner = context.destination
1016
1811
  if (owner === undefined) {
1017
- return
1812
+ // No table owns the destination, so a Ref held through relations or member reveals is checked on the rows that hold it.
1813
+ return grant.relations.length === 0 && grant.revealing.length === 0 ? true : await holdingRowLocked(transaction, context, grant)
1018
1814
  }
1019
- const scope = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1815
+ const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
1816
+ // A Ref held through a relation or a member reveal inserts only while a row of it still holds the destination.
1817
+ const gate = relationGate(context, owner, grant, new Date(), paths ?? heldThrough(grant.action))
1818
+ const scope = gate === undefined ? chain : allOf([chain, gate])
1020
1819
  const node = lockNode(owner.name, keyOf(owner), scope)
1021
- const rows = await transaction.run(node, { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, lock: 'share' })
1022
- if (rows.length === 0) {
1023
- throw new NotFoundError(`${owner.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
1024
- }
1820
+ const rows = await transaction.run(node, {
1821
+ root: 'SelectQueryNode',
1822
+ table: owner.name,
1823
+ joins: {},
1824
+ scope,
1825
+ lock: 'share',
1826
+ subqueries: context.subqueries,
1827
+ })
1828
+ return rows.length > 0
1025
1829
  }
1026
1830
 
1831
+ /** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
1027
1832
  export async function insertRow<O>(
1028
1833
  context: TableContext,
1029
1834
  run: Runner,
1030
- values: ReadonlyMap<string, Primitive | null>,
1031
- destination: RefGrant | undefined,
1835
+ given: ReadonlyMap<string, Primitive | null>,
1836
+ prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
1032
1837
  ): Promise<O> {
1838
+ const values = boundValues(context, given)
1033
1839
  return run.write(async (transaction) => {
1034
- if (destination !== undefined) {
1035
- await lockDestination(transaction, context, destination)
1840
+ if (prepared?.destination !== undefined) {
1841
+ await lockDestination(transaction, context, prepared.destination)
1842
+ }
1843
+ const before = await narrowedHolds(transaction, context, prepared)
1844
+ if (prepared !== undefined) {
1845
+ await checkPrincipalAssign(transaction, context, prepared.writer, given)
1846
+ await checkRevealAssign(transaction, context, prepared.writer, given)
1847
+ await checkMemberRevealAssign(transaction, context, prepared.writer, given)
1848
+ await checkPathWriters(transaction, context, prepared.writer, given)
1036
1849
  }
1037
1850
  const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
1038
1851
  if (row === undefined) {
@@ -1040,6 +1853,8 @@ export async function insertRow<O>(
1040
1853
  }
1041
1854
  checkVersion(context, row)
1042
1855
  await referenceInserted(context, run, transaction, values)
1856
+ await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
1857
+ await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
1043
1858
  return row
1044
1859
  })
1045
1860
  }
@@ -1053,18 +1868,20 @@ export interface OnConflict {
1053
1868
  readonly mode: 'nothing' | 'update'
1054
1869
  /** The values given for the table's update columns: what `update` sets on the conflicting row. */
1055
1870
  readonly updates: ReadonlyMap<string, Primitive | null>
1871
+ /** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
1872
+ readonly actions: readonly string[]
1056
1873
  }
1057
1874
 
1058
1875
  const CONFLICT_FIELDS = nameSet(['columns', 'do'])
1059
1876
 
1060
1877
  /**
1061
1878
  * The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
1062
- * also needs the capability's action to be one of the table's update actions.
1879
+ * also needs one of the capability's `actions` to be one of the table's update actions.
1063
1880
  */
1064
1881
  export function onConflictOf(
1065
1882
  context: TableContext,
1066
1883
  options: unknown,
1067
- action: string,
1884
+ actions: readonly string[],
1068
1885
  given: ReadonlyMap<string, Primitive | null>,
1069
1886
  ): OnConflict | undefined {
1070
1887
  if (options === undefined) {
@@ -1081,6 +1898,10 @@ export function onConflictOf(
1081
1898
  if (!inSet(model.columns, name)) {
1082
1899
  throw new QueryRefusedError('on_conflict', `onConflict names ${String(name)}, which is not a column of ${model.name}`)
1083
1900
  }
1901
+ if (inSet(model.json, name)) {
1902
+ // jsonb compares by value and SQLite's text by spelling: the two dialects would disagree about a conflict.
1903
+ throw new QueryRefusedError('on_conflict', `onConflict names ${name}, a JSON column of ${model.name}, which the data layer never compares`)
1904
+ }
1084
1905
  return name
1085
1906
  })
1086
1907
  if (columns === undefined || columns.length === 0) {
@@ -1091,13 +1912,14 @@ export function onConflictOf(
1091
1912
  throw new QueryRefusedError('on_conflict', "onConflict.do takes 'nothing' or 'update'")
1092
1913
  }
1093
1914
  const updates = new Map<string, Primitive | null>()
1915
+ const updating = admitted(actions, model.actions.update)
1094
1916
  if (mode === 'update') {
1095
- if (!includes(model.actions.update, action)) {
1917
+ if (updating.length === 0) {
1096
1918
  throw new CapabilityError(
1097
1919
  'wrong_action',
1098
1920
  `an insert of ${model.name} that updates on a conflict also needs its update action ${
1099
1921
  model.actions.update.join(' or ') || '(none)'
1100
- }; the capability holds ${action}`,
1922
+ }; the capability holds ${actions.join(', ')}`,
1101
1923
  )
1102
1924
  }
1103
1925
  const columns = namesOf(model.update)
@@ -1109,7 +1931,7 @@ export function onConflictOf(
1109
1931
  }
1110
1932
  }
1111
1933
  }
1112
- return freeze({ columns: freeze(columns), mode, updates })
1934
+ return freeze({ columns: freeze(columns), mode, updates, actions: freeze(updating) })
1113
1935
  }
1114
1936
 
1115
1937
  /** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
@@ -1164,18 +1986,20 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
1164
1986
 
1165
1987
  /**
1166
1988
  * `insert … on conflict (columns) do nothing`, and for `update` the conflicting row's update in the same transaction,
1167
- * within the insert's own containment. A row deleted between the two is inserted on the second try; a conflicting row
1168
- * the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1989
+ * within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
1990
+ * inserted on the second try; a conflicting row the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
1169
1991
  * false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
1170
1992
  */
1171
1993
  async function insertOnConflict(
1172
1994
  context: TableContext,
1173
1995
  run: Runner,
1174
1996
  transaction: Session,
1175
- values: ReadonlyMap<string, Primitive | null>,
1997
+ given: ReadonlyMap<string, Primitive | null>,
1176
1998
  conflict: OnConflict,
1177
1999
  ): Promise<Readonly<Record<string, unknown>>> {
1178
2000
  const model = context.model
2001
+ const values = boundValues(context, given)
2002
+ const updates = boundValues(context, conflict.updates)
1179
2003
  const matches: OperationNode[] = []
1180
2004
  for (let index = 0; index < conflict.columns.length; index++) {
1181
2005
  const name = conflict.columns[index] ?? ''
@@ -1185,7 +2009,7 @@ async function insertOnConflict(
1185
2009
  }
1186
2010
  matches[matches.length] = equals(model.name, name, value)
1187
2011
  }
1188
- const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
2012
+ const scope = conflict.mode === 'update' ? conditionedAny(model, conflict.actions, insertedScope(context, values), new Date()) : undefined
1189
2013
  for (let attempt = 0; attempt < 2; attempt++) {
1190
2014
  const node = insertNode(model.name, values, answer(context), conflict.columns)
1191
2015
  const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
@@ -1201,17 +2025,17 @@ async function insertOnConflict(
1201
2025
  return { inserted: false }
1202
2026
  }
1203
2027
  const where = scopedWhere(allOf(matches), scope)
1204
- const unchanged = conflict.updates.size === 0
2028
+ const unchanged = updates.size === 0
1205
2029
  const update = unchanged
1206
2030
  ? acknowledgementNode(model.name, keyOf(model), model.version, where)
1207
- : updateNode(model.name, conflict.updates, model.version, where, answer(context))
2031
+ : updateNode(model.name, updates, model.version, where, answer(context))
1208
2032
  const [updated] = await transaction.run<Readonly<Record<string, unknown>>>(
1209
2033
  update,
1210
2034
  guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', scope),
1211
2035
  )
1212
2036
  if (updated !== undefined) {
1213
2037
  checkVersion(context, updated)
1214
- await referenceUpdated(context, run, transaction, conflict.updates, updated)
2038
+ await referenceUpdated(context, run, transaction, updates, updated)
1215
2039
  return { ...updated, inserted: false }
1216
2040
  }
1217
2041
  }
@@ -1264,30 +2088,54 @@ export async function updateRow<O>(
1264
2088
  context: TableContext,
1265
2089
  run: Runner,
1266
2090
  target: Addressed,
1267
- changes: ReadonlyMap<string, Primitive | null>,
2091
+ given: ReadonlyMap<string, Primitive | null>,
1268
2092
  expectedVersion: OperationNode | undefined,
1269
- destination?: RefGrant,
2093
+ moved?: MovedRow,
1270
2094
  ): Promise<O> {
1271
2095
  const { name: table, version } = context.model
2096
+ const changes = boundValues(context, given)
1272
2097
  const where = scopedWhere(conditionsWith(target, expectedVersion), target.scope)
1273
2098
  const unchanged = changes.size === 0
1274
2099
  const node = unchanged
1275
2100
  ? acknowledgementNode(table, keyOf(context.model), version, where)
1276
2101
  : updateNode(table, changes, version, where, answer(context))
1277
2102
  return run.write(async (transaction) => {
1278
- if (destination !== undefined) {
1279
- await lockDestination(transaction, context, destination)
2103
+ // A move follows containment, so a path never holds its destination.
2104
+ if (moved !== undefined) {
2105
+ await lockDestination(transaction, context, moved.destination, noPath)
1280
2106
  }
2107
+ const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
1281
2108
  const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
1282
2109
  if (row !== undefined) {
1283
2110
  checkVersion(context, row)
1284
2111
  await referenceUpdated(context, run, transaction, changes, row)
2112
+ if (moved !== undefined) {
2113
+ await judgeInserted(transaction, context, moved.judged, rowKey(context, row))
2114
+ await judgeNarrowed(transaction, context, moved, before, rowKey(context, row))
2115
+ }
1285
2116
  return row
1286
2117
  }
1287
2118
  return missingOrChanged(context, transaction, target, expectedVersion)
1288
2119
  })
1289
2120
  }
1290
2121
 
2122
+ /**
2123
+ * A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
2124
+ * after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
2125
+ * `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
2126
+ */
2127
+ export interface MovedRow {
2128
+ readonly destination: RefGrant
2129
+ readonly judged: JudgedInsert | undefined
2130
+ readonly narrowed: readonly NarrowedInsert[]
2131
+ }
2132
+
2133
+ /** The key `row`, a write's acknowledgement, answers; `undefined` when it answers none as text. */
2134
+ function rowKey(context: TableContext, row: unknown): string | undefined {
2135
+ const value: unknown = typeof row === 'object' && row !== null ? ownDescriptor(row, keyOf(context.model))?.value : undefined
2136
+ return typeof value === 'string' ? value : undefined
2137
+ }
2138
+
1291
2139
  /** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
1292
2140
  export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
1293
2141
  const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
@@ -1303,11 +2151,11 @@ type Columns<Row> = keyof Row & string
1303
2151
  type NumericColumn<Row> = { [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never }[Columns<Row>]
1304
2152
 
1305
2153
  export interface AggregateSpec<Row> {
1306
- readonly groupBy?: readonly Columns<Row>[]
2154
+ readonly groupBy?: readonly ComparableColumn<Row>[]
1307
2155
  readonly count?: boolean
1308
2156
  readonly sum?: readonly NumericColumn<Row>[]
1309
- readonly min?: readonly Columns<Row>[]
1310
- readonly max?: readonly Columns<Row>[]
2157
+ readonly min?: readonly ComparableColumn<Row>[]
2158
+ readonly max?: readonly ComparableColumn<Row>[]
1311
2159
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>
1312
2160
  }
1313
2161
 
@@ -1344,7 +2192,7 @@ function aggregateColumns(table: string, shape: TableShape, spec: AggregateInput
1344
2192
  if (!inSet(shape.visible, name)) {
1345
2193
  throw new QueryRefusedError('unknown_column', `${String(name)} is not a column of ${table} (columns: ${namesOf(shape.visible).join(', ')})`)
1346
2194
  }
1347
- return name
2195
+ return comparableColumnOf(shape, name, 'aggregates')
1348
2196
  })
1349
2197
  if (names === undefined) {
1350
2198
  throw new QueryRefusedError('invalid_argument', `aggregate ${field} takes a plain array of column names`)
@@ -1389,18 +2237,27 @@ export async function aggregateRows<Row, O>(
1389
2237
  if (scope === undefined) {
1390
2238
  return []
1391
2239
  }
1392
- const node = aggregateNode(context.model.name, columns, filter?.conditions ?? [], scope, context.model.dates)
2240
+ const dialect = dialectOf(context)
2241
+ const conditions = boundConditions(context, context.model, filter?.conditions ?? [])
2242
+ const node = aggregateNode(context.model.name, columns, conditions, scope, context.model.dates)
1393
2243
  const rows = await (await run.read()).run<O>(node, guard(context, 'SelectQueryNode', scope))
1394
- return answerDays(context.model.name, aggregateDays(context.model.dates, columns), rows)
1395
- }
1396
-
1397
- /** The `date` columns of an aggregate's rows: a grouped one by its name, and its `min_` and `max_`. */
1398
- function aggregateDays(dates: NameSet, columns: AggregateColumns): NameSet {
2244
+ const own = rowColumnsOf(context.model)
2245
+ const answered = answerRows(dialect, context.model.name, {
2246
+ days: aggregated(own.days, columns),
2247
+ timestamps: aggregated(own.timestamps, columns),
2248
+ booleans: aggregated(own.booleans, columns),
2249
+ json: nameSet([]),
2250
+ }, rows)
2251
+ return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
2252
+ }
2253
+
2254
+ /** The columns of `set` among an aggregate's: a grouped one by its name, and its `min_` and `max_`. */
2255
+ function aggregated(set: NameSet, columns: AggregateColumns): NameSet {
1399
2256
  const names: string[] = []
1400
2257
  const add = (prefix: string, list: readonly string[]) => {
1401
2258
  for (let index = 0; index < list.length; index++) {
1402
2259
  const name = list[index] ?? ''
1403
- if (inSet(dates, name)) {
2260
+ if (inSet(set, name)) {
1404
2261
  names[names.length] = `${prefix}${name}`
1405
2262
  }
1406
2263
  }
@@ -1411,11 +2268,59 @@ function aggregateDays(dates: NameSet, columns: AggregateColumns): NameSet {
1411
2268
  return nameSet(names)
1412
2269
  }
1413
2270
 
2271
+ /**
2272
+ * An aggregate's numbers as Postgres's driver answers them: `count` as bigint text, and an integral `sum` as text too
2273
+ * (Postgres sums an integer as bigint or numeric). SQLite answers both as numbers, and a whole sum of a REAL column is
2274
+ * text here where Postgres's float8 sum is a number; `AggregateRow` types a sum as either.
2275
+ */
2276
+ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]): O[] {
2277
+ const integral = (where: string, value: unknown): unknown => {
2278
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
2279
+ return value
2280
+ }
2281
+ if (!isSafeInteger(value)) {
2282
+ throw new QueryRefusedError('unexpected_row', `${where} came back as an integer past the safe range, which a number cannot hold exactly`)
2283
+ }
2284
+ return String(value)
2285
+ }
2286
+ for (let index = 0; index < rows.length; index++) {
2287
+ const row = rows[index]
2288
+ if (typeof row !== 'object' || row === null) {
2289
+ continue
2290
+ }
2291
+ if (columns.count) {
2292
+ defineValue(row, 'count', integral(`${table}.count`, ownDescriptor(row, 'count')?.value))
2293
+ }
2294
+ for (let position = 0; position < columns.sum.length; position++) {
2295
+ const name = `sum_${columns.sum[position] ?? ''}`
2296
+ defineValue(row, name, integral(`${table}.${name}`, ownDescriptor(row, name)?.value))
2297
+ }
2298
+ }
2299
+ return rows
2300
+ }
2301
+
1414
2302
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
1415
2303
  export interface PreparedInsert {
1416
2304
  readonly row: Map<string, Primitive | null>
2305
+ /** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
2306
+ readonly writer: string
1417
2307
  readonly destination: RefGrant | undefined
1418
2308
  readonly conflict: OnConflict | undefined
2309
+ /** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
2310
+ readonly judged: JudgedInsert | undefined
2311
+ /** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
2312
+ readonly narrowed: readonly NarrowedInsert[]
2313
+ }
2314
+
2315
+ export interface JudgedInsert {
2316
+ readonly action: string
2317
+ readonly condition: ConditionModel
2318
+ }
2319
+
2320
+ /** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
2321
+ export interface NarrowedInsert {
2322
+ readonly relation: string
2323
+ readonly condition: ConditionModel
1419
2324
  }
1420
2325
 
1421
2326
  /**
@@ -1426,27 +2331,66 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
1426
2331
  const scope = dimensionScope(context.model)
1427
2332
  const grant = refGrant(context, target, listDimension(scope), 'insert')
1428
2333
  const row = readValues(values, context.model.insert, 'insert', context.model)
1429
- const conflict = onConflictOf(context, options, grant.action, row)
2334
+ const conflict = onConflictOf(context, options, [grant.action], row)
1430
2335
  if (scope.container === undefined) {
1431
2336
  // The object does not exist yet; this only refuses a chain the table has no column for.
1432
2337
  linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
1433
2338
  stampInsert(context, grant, row, scope.key, grant.id)
1434
- return { row, destination: undefined, conflict }
2339
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2340
+ // No destination to check again after the write, so a condition with a path holds nothing here.
2341
+ narrowedDestination(context, grant, row, false)
2342
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
1435
2343
  }
1436
- stampInsert(context, grant, row, scope.key, Bun.randomUUIDv7())
1437
- for (const { link, value } of linkValues(context.model.name, context.model.chain, grant)) {
1438
- row.set(link.column, value)
1439
- }
1440
- return { row, destination: grant, conflict }
2344
+ stampInsert(context, grant, row, scope.key, uuidv7())
2345
+ stampChain(row, linkValues(context.model.name, context.model.chain, grant))
2346
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2347
+ const held = narrowedDestination(context, grant, row, true)
2348
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
1441
2349
  }
1442
2350
 
1443
2351
  /** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
1444
2352
  export function prepareApplicationInsert(context: TableContext, capability: unknown, values: unknown, options?: unknown): PreparedInsert {
1445
- const grant = appGrant(context, capability, 'insert')
2353
+ const { grant, actions } = appGrant(context, capability, 'insert')
2354
+ // Every insert action writes the table's one insert list, so each held one writes all of `values`: only their conditions differ.
1446
2355
  const row = readValues(values, context.model.insert, 'insert', context.model)
1447
- const conflict = onConflictOf(context, options, grant.action, row)
1448
- stampInsert(context, grant, row, keyOf(context.model), Bun.randomUUIDv7())
1449
- return { row, destination: undefined, conflict }
2356
+ // Only an insert action that also updates may update on a conflict: never one action's insert with another's update.
2357
+ const declared = onConflictOf(context, options, actions, row)
2358
+ stampInsert(context, grant, row, keyOf(context.model), uuidv7())
2359
+ const conflict = declared?.mode === 'update' ? upsertingActions(context.model, declared, row) : declared
2360
+ const judged = checkInserted(context, conflict?.mode === 'update' ? conflict.actions : actions, grant.principal, row)
2361
+ return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
2362
+ }
2363
+
2364
+ /**
2365
+ * An upsert under several actions that each insert and update: only those whose own condition admits the inserted row
2366
+ * may update the conflicting one, so the update runs under an action whose insert alone was allowed. A condition that
2367
+ * follows a path is judged only in the transaction, after the update chose its actions, so several such are refused.
2368
+ */
2369
+ function upsertingActions(model: TableModel, conflict: OnConflict, row: ReadonlyMap<string, Primitive | null>): OnConflict {
2370
+ if (conflict.actions.length < 2) {
2371
+ return conflict
2372
+ }
2373
+ const now = new Date()
2374
+ const admitting: string[] = []
2375
+ for (let index = 0; index < conflict.actions.length; index++) {
2376
+ const action = conflict.actions[index] ?? ''
2377
+ const condition = ownEntry(model.when, action)
2378
+ if (condition !== undefined && readPaths(condition).length > 0) {
2379
+ throw new CapabilityError(
2380
+ 'unenforceable',
2381
+ `an insert into ${model.name} that updates on a conflict under ${
2382
+ conflict.actions.join(', ')
2383
+ } would pair a condition that follows a path with another action's: upsert from an endpoint of one of them`,
2384
+ )
2385
+ }
2386
+ if (condition === undefined || rowSatisfies(condition, row, now)) {
2387
+ admitting[admitting.length] = action
2388
+ }
2389
+ }
2390
+ // None admits the row: keep them all, and the insert's own check refuses it.
2391
+ return admitting.length === 0
2392
+ ? conflict
2393
+ : freeze({ columns: conflict.columns, mode: conflict.mode, updates: conflict.updates, actions: freeze(admitting) })
1450
2394
  }
1451
2395
 
1452
2396
  /** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
@@ -1454,44 +2398,574 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
1454
2398
  const scope = childScope(context)
1455
2399
  const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
1456
2400
  const row = readValues(values, context.model.insert, 'insert', context.model)
1457
- const conflict = onConflictOf(context, options, grant.action, row)
1458
- stampInsert(context, grant, row, scope.key, Bun.randomUUIDv7())
1459
- for (const { link, value } of linkValues(context.model.name, context.model.chain, grant)) {
1460
- row.set(link.column, value)
2401
+ const conflict = onConflictOf(context, options, [grant.action], row)
2402
+ stampInsert(context, grant, row, scope.key, uuidv7())
2403
+ stampChain(row, linkValues(context.model.name, context.model.chain, grant))
2404
+ const judged = checkInserted(context, [grant.action], grant.principal, row)
2405
+ const held = narrowedDestination(context, grant, row, true)
2406
+ return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
2407
+ }
2408
+
2409
+ const DAY_MS = 86_400_000
2410
+
2411
+ /**
2412
+ * An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
2413
+ * its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
2414
+ * ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
2415
+ * that follows a path is answered for the transaction to judge.
2416
+ */
2417
+ function checkInserted(
2418
+ context: TableContext,
2419
+ actions: readonly string[],
2420
+ principal: string,
2421
+ row: ReadonlyMap<string, Primitive | null>,
2422
+ ): JudgedInsert | undefined {
2423
+ const model = context.model
2424
+ const now = new Date()
2425
+ const judged = insertCondition(model, actions, row, now)
2426
+ for (let index = 0; index < model.confers.length; index++) {
2427
+ const source = model.confers[index]
2428
+ if (source === undefined) {
2429
+ continue
2430
+ }
2431
+ const assign = source.assign
2432
+ if (assign === undefined) {
2433
+ throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
2434
+ }
2435
+ // A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
2436
+ if (!assign.self && source.principalPath === undefined && row.get(source.principal) === principal) {
2437
+ throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
2438
+ }
2439
+ if (assign.maxDays !== undefined && source.expires !== undefined) {
2440
+ const value = row.get(source.expires)
2441
+ const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
2442
+ if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
2443
+ throw new ConflictError(
2444
+ `a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
2445
+ )
2446
+ }
2447
+ }
2448
+ }
2449
+ return judged
2450
+ }
2451
+
2452
+ /**
2453
+ * The insert actions' condition on the row, as one role holding `actions` is narrowed: a row any of them admits passes,
2454
+ * and one without a condition admits every row. A pathless condition is judged here; one that follows a path is
2455
+ * answered for the transaction to judge, which holds one such condition only, so several are refused.
2456
+ */
2457
+ function insertCondition(
2458
+ model: TableModel,
2459
+ actions: readonly string[],
2460
+ row: ReadonlyMap<string, Primitive | null>,
2461
+ now: Date,
2462
+ ): JudgedInsert | undefined {
2463
+ const pathed: JudgedInsert[] = []
2464
+ for (let index = 0; index < actions.length; index++) {
2465
+ const action = actions[index]
2466
+ if (action === undefined) continue
2467
+ const condition = ownEntry(model.when, action)
2468
+ if (condition === undefined) {
2469
+ return undefined
2470
+ }
2471
+ if (readPaths(condition).length > 0) {
2472
+ pathed[pathed.length] = { action, condition }
2473
+ } else if (rowSatisfies(condition, row, now)) {
2474
+ return undefined
2475
+ }
2476
+ }
2477
+ const [only, ...more] = pathed
2478
+ if (only === undefined) {
2479
+ throw new ConflictError(`the row is outside what ${actions.join(' or ')} inserts into ${model.name}`)
2480
+ }
2481
+ if (more.length > 0) {
2482
+ throw new CapabilityError(
2483
+ 'unenforceable',
2484
+ `an insert into ${model.name} under ${
2485
+ actions.join(', ')
2486
+ } would be judged by several conditions that follow paths: insert from an endpoint of one of them`,
2487
+ )
2488
+ }
2489
+ return only
2490
+ }
2491
+
2492
+ /**
2493
+ * The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
2494
+ * and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
2495
+ * the transaction to judge (`judgeNarrowed`), or, without a destination to check again (`defer` false), held to fail. A Ref held by nothing else then is refused (409): the relation's membership
2496
+ * is never judged on the written row, so the row never counts towards its own insert.
2497
+ */
2498
+ function narrowedDestination(
2499
+ context: TableContext,
2500
+ grant: RefGrant,
2501
+ row: ReadonlyMap<string, Primitive | null>,
2502
+ defer: boolean,
2503
+ ): { readonly destination: RefGrant; readonly narrowed: readonly NarrowedInsert[] } {
2504
+ const now = new Date()
2505
+ const kept: RelationHold[] = []
2506
+ const narrowed: NarrowedInsert[] = []
2507
+ for (let index = 0; index < grant.relations.length; index++) {
2508
+ const hold = grant.relations[index]
2509
+ if (hold === undefined) continue
2510
+ const relation = hold.relation
2511
+ const condition = relationCondition(context.model, relation, grant.action)
2512
+ const pathed = condition !== undefined && readPaths(condition).length > 0
2513
+ if (condition !== undefined && pathed && defer && !judgesRelation(narrowed, relation)) {
2514
+ narrowed[narrowed.length] = { relation, condition }
2515
+ }
2516
+ if (condition === undefined || (pathed ? defer : rowSatisfies(condition, row, now))) {
2517
+ kept[kept.length] = hold
2518
+ }
2519
+ }
2520
+ if (kept.length === grant.relations.length) {
2521
+ return { destination: grant, narrowed }
2522
+ }
2523
+ if (kept.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2524
+ throw new ConflictError(`the row is outside what ${grant.action} inserts into ${context.model.name} through its relations`)
2525
+ }
2526
+ return { destination: { ...grant, relations: kept }, narrowed }
2527
+ }
2528
+
2529
+ /** Whether `narrowed` already judges `relation`: two holds of one relation are judged once. */
2530
+ function judgesRelation(narrowed: readonly NarrowedInsert[], relation: string): boolean {
2531
+ for (let index = 0; index < narrowed.length; index++) {
2532
+ if (narrowed[index]?.relation === relation) return true
2533
+ }
2534
+ return false
2535
+ }
2536
+
2537
+ /**
2538
+ * What held an insert's destination before the write, apart from the relations narrowed by a path: the rest of the
2539
+ * `Ref`, and, with several such relations, each of them alone. Decided before the row exists, so it never counts it.
2540
+ */
2541
+ interface NarrowedHolds {
2542
+ readonly rest: boolean
2543
+ readonly alone: readonly string[]
2544
+ }
2545
+
2546
+ /** `NarrowedHolds` of a prepared insert, locked `for share` in its transaction before the write; `undefined` with nothing narrowed. */
2547
+ async function narrowedHolds(
2548
+ transaction: Session,
2549
+ context: TableContext,
2550
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2551
+ paths?: PathRule,
2552
+ ): Promise<NarrowedHolds | undefined> {
2553
+ const destination = prepared?.destination
2554
+ if (prepared === undefined || destination === undefined || prepared.narrowed.length === 0) {
2555
+ return undefined
2556
+ }
2557
+ const relations: string[] = []
2558
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2559
+ const entry = prepared.narrowed[index]
2560
+ if (entry !== undefined) relations[relations.length] = entry.relation
2561
+ }
2562
+ const rest = await heldBy(transaction, context, { ...destination, relations: holdsBesides(destination.relations, relations) }, paths)
2563
+ const alone: string[] = []
2564
+ // One narrowed relation that passes leaves the destination as `lockDestination` found it; only with several may it be another's.
2565
+ for (let index = 0; relations.length > 1 && index < relations.length; index++) {
2566
+ const relation = relations[index] ?? ''
2567
+ const holds: RelationHold[] = []
2568
+ for (let position = 0; position < destination.relations.length; position++) {
2569
+ const hold = destination.relations[position]
2570
+ if (hold !== undefined && hold.relation === relation) holds[holds.length] = hold
2571
+ }
2572
+ if (await heldBy(transaction, context, { ...destination, relations: holds, revealing: [], paths: [] }, paths)) alone[alone.length] = relation
2573
+ }
2574
+ return { rest, alone }
2575
+ }
2576
+
2577
+ /** Whether `grant` holds the destination: with no part left, never. */
2578
+ async function heldBy(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
2579
+ if (grant.relations.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
2580
+ return false
2581
+ }
2582
+ return await destinationHeld(transaction, context, grant, paths)
2583
+ }
2584
+
2585
+ /**
2586
+ * The destination's relations whose condition for the insert follows a path, judged on the row just written as
2587
+ * `judgeInserted` judges `when`. When the row fails one, the insert stands only on what held the destination before the
2588
+ * write without it (`before`): the rest of the `Ref`, or a narrowed relation the row meets that held it alone. Otherwise
2589
+ * the transaction fails with a 409.
2590
+ */
2591
+ async function judgeNarrowed(
2592
+ transaction: Session,
2593
+ context: TableContext,
2594
+ prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
2595
+ before: NarrowedHolds | undefined,
2596
+ key: Primitive | null | undefined,
2597
+ ): Promise<void> {
2598
+ const destination = prepared?.destination
2599
+ if (prepared === undefined || destination === undefined || before === undefined) {
2600
+ return
2601
+ }
2602
+ let failed = false
2603
+ let held = before.rest
2604
+ for (let index = 0; index < prepared.narrowed.length; index++) {
2605
+ const entry = prepared.narrowed[index]
2606
+ if (entry === undefined) continue
2607
+ if (!(await rowMeets(transaction, context, destination.action, entry.condition, key))) {
2608
+ failed = true
2609
+ } else if (includes(before.alone, entry.relation)) {
2610
+ held = true
2611
+ }
2612
+ }
2613
+ if (failed && !held) {
2614
+ transaction.fail()
2615
+ throw new ConflictError(`the row is outside what ${destination.action} inserts into ${context.model.name} through its relations`)
2616
+ }
2617
+ }
2618
+
2619
+ /**
2620
+ * An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
2621
+ * held the row's foreign keys, so a path reads only the rows they name in the row's tenant. Every row each read path
2622
+ * reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
2623
+ * before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
2624
+ * so it commits nothing even when the handler catches the refusal.
2625
+ */
2626
+ async function judgeInserted(
2627
+ transaction: Session,
2628
+ context: TableContext,
2629
+ judged: JudgedInsert | undefined,
2630
+ key: Primitive | null | undefined,
2631
+ ): Promise<void> {
2632
+ if (judged === undefined) {
2633
+ return
2634
+ }
2635
+ if (!(await rowMeets(transaction, context, judged.action, judged.condition, key))) {
2636
+ transaction.fail()
2637
+ throw new ConflictError(`the row is outside what ${judged.action} inserts into ${context.model.name}`)
2638
+ }
2639
+ }
2640
+
2641
+ /**
2642
+ * Whether the row just written meets `condition`, in the insert's transaction: every row each of its paths reaches is
2643
+ * locked `FOR SHARE` first, then the condition is judged as a read of the row judges it.
2644
+ */
2645
+ async function rowMeets(
2646
+ transaction: Session,
2647
+ context: TableContext,
2648
+ action: string,
2649
+ condition: ConditionModel,
2650
+ key: Primitive | null | undefined,
2651
+ ): Promise<boolean> {
2652
+ const model = context.model
2653
+ if (key === undefined || key === null) {
2654
+ throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
2655
+ }
2656
+ const paths = readPaths(condition)
2657
+ for (let index = 0; index < paths.length; index++) {
2658
+ const steps = paths[index] ?? []
2659
+ // The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
2660
+ let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
2661
+ const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
2662
+ for (let position = 0; position < steps.length; position++) {
2663
+ const step = steps[position]
2664
+ if (step === undefined) continue
2665
+ const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
2666
+ await transaction.run(lockNode(step.table, step.to, scope), {
2667
+ root: 'SelectQueryNode',
2668
+ table: step.table,
2669
+ joins: {},
2670
+ scope,
2671
+ lock: 'share',
2672
+ subqueries: withColumns(context.subqueries, walked),
2673
+ })
2674
+ const next = steps[position + 1]
2675
+ if (next !== undefined) {
2676
+ reached = subquery(step.table, next.from, scope)
2677
+ walked[step.table] = [...(walked[step.table] ?? []), next.from]
2678
+ }
2679
+ }
2680
+ }
2681
+ const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
2682
+ const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
2683
+ root: 'SelectQueryNode',
2684
+ table: model.name,
2685
+ joins: {},
2686
+ scope,
2687
+ subqueries: context.subqueries,
2688
+ })
2689
+ return rows.length > 0
2690
+ }
2691
+
2692
+ /** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
2693
+ function withColumns(
2694
+ admitted: Readonly<Record<string, readonly string[]>>,
2695
+ more: Readonly<Record<string, readonly string[]>>,
2696
+ ): Readonly<Record<string, readonly string[]>> {
2697
+ const merged: Record<string, readonly string[]> = { ...admitted }
2698
+ const tables = ownKeys(more)
2699
+ for (let index = 0; index < tables.length; index++) {
2700
+ const table = tables[index] ?? ''
2701
+ setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
2702
+ }
2703
+ return merged
2704
+ }
2705
+
2706
+ /** Writes each chain column the destination `Ref` settles into an insert's row. */
2707
+ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
2708
+ for (let index = 0; index < values.length; index++) {
2709
+ const entry = values[index]
2710
+ if (entry !== undefined) {
2711
+ row.set(entry.link.column, entry.value)
2712
+ }
1461
2713
  }
1462
- return { row, destination: grant, conflict }
1463
2714
  }
1464
2715
 
1465
2716
  /** A prepared insert, with its conflict handling when the caller named one. */
1466
2717
  export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
1467
2718
  const conflict = prepared.conflict
1468
2719
  if (conflict === undefined) {
1469
- return insertRow(context, run, prepared.row, prepared.destination)
2720
+ return insertRow(context, run, prepared.row, prepared)
1470
2721
  }
1471
2722
  return run.write(async (transaction) => {
1472
2723
  if (prepared.destination !== undefined) {
1473
2724
  await lockDestination(transaction, context, prepared.destination)
1474
2725
  }
1475
- return insertOnConflict(context, run, transaction, prepared.row, conflict)
2726
+ const before = await narrowedHolds(transaction, context, prepared)
2727
+ await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
2728
+ await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
2729
+ await checkMemberRevealAssign(transaction, context, prepared.writer, prepared.row)
2730
+ await checkPathWriters(transaction, context, prepared.writer, prepared.row)
2731
+ const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
2732
+ // A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
2733
+ if (written['inserted'] === true) {
2734
+ await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
2735
+ await judgeNarrowed(transaction, context, prepared, before, prepared.row.get(keyOf(context.model)))
2736
+ }
2737
+ return written
1476
2738
  })
1477
2739
  }
1478
2740
 
2741
+ /**
2742
+ * A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
2743
+ * row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
2744
+ * stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
2745
+ */
2746
+ async function checkPrincipalAssign(
2747
+ transaction: Session,
2748
+ context: TableContext,
2749
+ writer: string,
2750
+ row: ReadonlyMap<string, Primitive | null>,
2751
+ ): Promise<void> {
2752
+ const model = context.model
2753
+ for (let index = 0; index < model.confers.length; index++) {
2754
+ const source = model.confers[index]
2755
+ const path = source?.principalPath
2756
+ const value = source === undefined ? undefined : row.get(source.principal)
2757
+ if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
2758
+ continue
2759
+ }
2760
+ const keyed = equals(path.table, path.key, value)
2761
+ await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
2762
+ const named = allOf([keyed, equals(path.table, path.column, writer)])
2763
+ const rows = await transaction.run(locateNode(path.table, [path.key], named), {
2764
+ root: 'SelectQueryNode',
2765
+ table: path.table,
2766
+ joins: {},
2767
+ scope: named,
2768
+ })
2769
+ if (rows.length > 0) {
2770
+ throw new ConflictError(
2771
+ `a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
2772
+ )
2773
+ }
2774
+ }
2775
+ }
2776
+
2777
+ /**
2778
+ * An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
2779
+ * insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
2780
+ * the relation is at. One guarded select per such reveal, in the insert's transaction.
2781
+ */
2782
+ async function checkRevealAssign(
2783
+ transaction: Session,
2784
+ context: TableContext,
2785
+ writer: string,
2786
+ row: ReadonlyMap<string, Primitive | null>,
2787
+ ): Promise<void> {
2788
+ const model = context.model
2789
+ const now = new Date()
2790
+ for (let index = 0; index < model.reveals.length; index++) {
2791
+ const reveal = model.reveals[index]
2792
+ const path = reveal?.path
2793
+ const value = path === undefined ? undefined : row.get(path.column)
2794
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
2795
+ const source = relationSource(context.relations, reveal.relation)
2796
+ const tests: OperationNode[] = []
2797
+ const rest: OperationNode[] = [...activeRow(source, now)]
2798
+ if (source.dimension === path.dimension) {
2799
+ tests[tests.length] = equals(source.table, source.node, value)
2800
+ } else {
2801
+ const link = linkOf(path.chain, source.dimension)
2802
+ if (link === undefined) continue
2803
+ const above = subquery(path.table, link.column, equals(path.table, path.key, value))
2804
+ rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
2805
+ }
2806
+ // The principal test comes last: an equality, or a path's membership after the node's equality.
2807
+ tests[tests.length] = namesPrincipal(source, writer)
2808
+ const address = allOf(tests)
2809
+ const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
2810
+ const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
2811
+ root: 'SelectQueryNode',
2812
+ table: source.table,
2813
+ joins: {},
2814
+ scope,
2815
+ subqueries: context.subqueries,
2816
+ })
2817
+ if (rows.length > 0) {
2818
+ throw new ConflictError(
2819
+ `a row of ${model.name} names in ${path.column} a node where its writer holds ${reveal.relation}, which the reveal's assign.self does not allow`,
2820
+ )
2821
+ }
2822
+ }
2823
+ }
2824
+
2825
+ /**
2826
+ * An inserted row whose path column a member reveal matches through, under the reveal's `assign`: without `self`, the
2827
+ * insert is refused while its writer holds a grant the reveal counts (one of its actions, at the node itself) at the
2828
+ * node the column names. The grants are the request's own; the database compares them with the node's key, so every
2829
+ * spelling of a key it reads as one (a `uuid`) is that node. Work with no request caller has none to judge, and is
2830
+ * refused.
2831
+ */
2832
+ async function checkMemberRevealAssign(
2833
+ transaction: Session,
2834
+ context: TableContext,
2835
+ writer: string,
2836
+ row: ReadonlyMap<string, Primitive | null>,
2837
+ ): Promise<void> {
2838
+ const model = context.model
2839
+ const authority = runtimeOf(context.connection).capabilities
2840
+ for (let index = 0; index < model.memberReveals.length; index++) {
2841
+ const reveal = model.memberReveals[index]
2842
+ const path = reveal?.path
2843
+ const value = path === undefined ? undefined : row.get(path.column)
2844
+ if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || value === undefined || value === null) {
2845
+ continue
2846
+ }
2847
+ for (let position = 0; position < reveal.actions.length; position++) {
2848
+ const action = reveal.actions[position] ?? ''
2849
+ const standing = authority.standing?.(path.dimension, action)
2850
+ if (standing === undefined || standing.principal !== writer) {
2851
+ throw new ConflictError(
2852
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} its member reveal reveals to, and its writer's grants cannot be judged under assign without self: work with no request caller`,
2853
+ )
2854
+ }
2855
+ if (standing.values === 'all' || standing.values.length === 0) continue
2856
+ const scope = AndNode.create(equals(path.table, path.key, value), inList(path.table, path.key, standing.values))
2857
+ const rows = await transaction.run(locateNode(path.table, [path.key], scope), {
2858
+ root: 'SelectQueryNode',
2859
+ table: path.table,
2860
+ joins: {},
2861
+ scope,
2862
+ })
2863
+ if (rows.length > 0) {
2864
+ throw new ConflictError(
2865
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer holds a grant the member reveal counts, which the reveal's assign.self does not allow`,
2866
+ )
2867
+ }
2868
+ }
2869
+ }
2870
+ }
2871
+
2872
+ /**
2873
+ * An inserted row's path column that hands out actions (`writeThrough`): its writer must hold every one of them at the
2874
+ * node the column names, as a grant there or above it, a relation row naming it there (of a relation no `relationWhen`
2875
+ * narrows for the action), or a revealing row. The node's
2876
+ * row is locked `FOR SHARE` first, so it stays where it lies until the commit, and so is each row the writer holds it
2877
+ * through; IAM grants are the request's own. Judged before the insert, so the inserted row never counts. A writer
2878
+ * outside the bound, or work with no caller, is a 409 and nothing is written.
2879
+ */
2880
+ async function checkPathWriters(
2881
+ transaction: Session,
2882
+ context: TableContext,
2883
+ writer: string,
2884
+ row: ReadonlyMap<string, Primitive | null>,
2885
+ ): Promise<void> {
2886
+ const model = context.model
2887
+ const authority = runtimeOf(context.connection).capabilities
2888
+ for (let index = 0; index < context.writers.length; index++) {
2889
+ const bound = context.writers[index]
2890
+ const value = bound === undefined ? undefined : row.get(bound.path.column)
2891
+ if (bound === undefined || value === undefined || value === null) continue
2892
+ const { path, owner } = bound
2893
+ const refused = (action: string) =>
2894
+ new ConflictError(
2895
+ `a row of ${model.name} names in ${path.column} a ${path.dimension} where its writer does not hold ${action}, which the path hands out (writeThrough)`,
2896
+ )
2897
+ const keyed = equals(owner.name, keyOf(owner), value)
2898
+ const locked = await transaction.run(lockNode(owner.name, keyOf(owner), keyed), {
2899
+ root: 'SelectQueryNode',
2900
+ table: owner.name,
2901
+ joins: {},
2902
+ scope: keyed,
2903
+ lock: 'share',
2904
+ })
2905
+ const chain = locked.length === 0 ? null : await chainOf(owner, transaction, String(value))
2906
+ for (let position = 0; position < bound.actions.length; position++) {
2907
+ const action = bound.actions[position] ?? ''
2908
+ const standing = authority.standing?.(path.dimension, action)
2909
+ if (chain === null || standing === undefined || standing.principal !== writer) throw refused(action)
2910
+ if (holdsByGrant(standing, String(value), chain)) continue
2911
+ const holding: RefGrant = {
2912
+ kind: 'ref',
2913
+ dimension: path.dimension,
2914
+ action,
2915
+ principal: writer,
2916
+ id: String(value),
2917
+ chain,
2918
+ relations: unnarrowed(context.relations, standing.relations, action),
2919
+ revealing: standing.revealing,
2920
+ paths: [],
2921
+ }
2922
+ if (!(await holdingRowLocked(transaction, context, holding))) throw refused(action)
2923
+ }
2924
+ }
2925
+ }
2926
+
2927
+ /**
2928
+ * Of `relations`, those no table's `relationWhen` narrows for `action`: a relation that holds the action on some rows only
2929
+ * does not bound a writer who hands it out at a node.
2930
+ */
2931
+ function unnarrowed(relations: RelationSources, held: readonly RelationHold[], action: string): readonly RelationHold[] {
2932
+ const kept: RelationHold[] = []
2933
+ for (let index = 0; index < held.length; index++) {
2934
+ const hold = held[index]
2935
+ if (hold !== undefined && !includes(knownRelation(relations, hold.relation).narrowed, action)) kept[kept.length] = hold
2936
+ }
2937
+ return kept
2938
+ }
2939
+
2940
+ /** Whether `standing`'s grants hold its action at `node`: everywhere, there, or at a container `chain` places it in. */
2941
+ function holdsByGrant(standing: WithinGrant, node: string, chain: ReadonlyMap<string, string>): boolean {
2942
+ if (standing.values === 'all' || includes(standing.values, node)) {
2943
+ return true
2944
+ }
2945
+ for (let index = 0; index < standing.containers.length; index++) {
2946
+ const container = standing.containers[index]
2947
+ const at = container === undefined ? undefined : chain.get(container.dimension)
2948
+ if (container !== undefined && at !== undefined && includes(container.values, at)) return true
2949
+ }
2950
+ return false
2951
+ }
2952
+
1479
2953
  /** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
1480
2954
  export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
1481
2955
  const prepared = prepareDimensionInsert(context, target, values)
1482
- return insertRow(context, run, prepared.row, prepared.destination)
2956
+ return insertRow(context, run, prepared.row, prepared)
1483
2957
  }
1484
2958
 
1485
2959
  /** An application table's insert, for an `app` capability of its insert action. */
1486
2960
  export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
1487
2961
  const prepared = prepareApplicationInsert(context, capability, values)
1488
- return insertRow(context, run, prepared.row, prepared.destination)
2962
+ return insertRow(context, run, prepared.row, prepared)
1489
2963
  }
1490
2964
 
1491
2965
  /** `ChildTable.insert` over a capability nobody type-checked. */
1492
2966
  export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
1493
2967
  const prepared = prepareChildInsert(context, parent, values)
1494
- return insertRow(context, run, prepared.row, prepared.destination)
2968
+ return insertRow(context, run, prepared.row, prepared)
1495
2969
  }
1496
2970
 
1497
2971
  type ReadAction<P, T> = ActionOf<P, T, 'read'>
@@ -1551,7 +3025,9 @@ export class DimensionTable<DB, P, T extends string> {
1551
3025
  /**
1552
3026
  * Moves the object to another container: the delete action at the source, the insert action at the target,
1553
3027
  * whose chain is checked against the database. Every chain column changes; children that copy them follow
1554
- * through `ON UPDATE CASCADE` on their composite foreign key. Answers the acknowledgement and the new chain.
3028
+ * through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
3029
+ * condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
3030
+ * Answers the acknowledgement and the new chain.
1555
3031
  */
1556
3032
  async move(
1557
3033
  ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
@@ -1562,12 +3038,42 @@ export class DimensionTable<DB, P, T extends string> {
1562
3038
  if (container === undefined) {
1563
3039
  throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
1564
3040
  }
1565
- const scope = objectPredicate(context, ref, 'delete')
3041
+ if (delegates(context.model)) {
3042
+ throw new CapabilityError(
3043
+ 'table_kind',
3044
+ `${context.model.name} hands out access, so a row is never moved: insert a new one`,
3045
+ )
3046
+ }
3047
+ // A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
1566
3048
  const target = refGrant(context, to, container.dimension, 'insert')
3049
+ if (refGrant(context, ref, dimensionScope(context.model).dimension, 'delete').paths.length > 0 || target.paths.length > 0) {
3050
+ throw new CapabilityError(
3051
+ 'unenforceable',
3052
+ `a Ref held through a secondary path never moves a row of ${context.model.name}: a move follows containment`,
3053
+ )
3054
+ }
3055
+ const scope = objectPredicate(context, ref, 'delete', noPath)
1567
3056
  const values = linkValues(context.model.name, context.model.chain, target)
1568
- const changes = new Map<string, Primitive | null>(values.map(({ link, value }) => [link.column, value]))
1569
- const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, target)
1570
- return { ...acknowledged, chain: Object.fromEntries(values.map(({ link, value }) => [link.dimension, value])) }
3057
+ const changes = new Map<string, Primitive | null>()
3058
+ stampChain(changes, values)
3059
+ const chain: Record<string, string> = {}
3060
+ for (let index = 0; index < values.length; index++) {
3061
+ const entry = values[index]
3062
+ if (entry !== undefined) {
3063
+ setOwn(chain, entry.link.dimension, entry.value)
3064
+ }
3065
+ }
3066
+ const condition = ownEntry(context.model.when, target.action)
3067
+ const narrowed: NarrowedInsert[] = []
3068
+ for (let index = 0; index < target.relations.length; index++) {
3069
+ const relation = target.relations[index]?.relation ?? ''
3070
+ const narrowing = relationCondition(context.model, relation, target.action)
3071
+ if (narrowing !== undefined && !judgesRelation(narrowed, relation)) narrowed[narrowed.length] = { relation, condition: narrowing }
3072
+ }
3073
+ const judged = condition === undefined ? undefined : { action: target.action, condition }
3074
+ const moved: MovedRow = { destination: target, judged, narrowed }
3075
+ const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, moved)
3076
+ return { ...acknowledged, chain }
1571
3077
  }
1572
3078
 
1573
3079
  async aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(
@@ -1669,7 +3175,7 @@ function probeRunner(context: TableContext): { readonly run: Runner; readonly he
1669
3175
  }
1670
3176
 
1671
3177
  /**
1672
- * One table's operations without the store types, for `@fabrika/db/testing` only: the generated isolation tests address
3178
+ * One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
1673
3179
  * a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
1674
3180
  * `key`, a dimension row by its capability alone.
1675
3181
  */
@@ -1697,15 +3203,19 @@ function probeOf(context: TableContext): TableProbe {
1697
3203
  }
1698
3204
  return objectPredicate(context, capability, operation)
1699
3205
  }
3206
+ const app = (capability: unknown): boolean => runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app'
1700
3207
  // An `app` capability reads every row through ctx.db.app: its rows with appRead, its counts with appCount too.
1701
3208
  const list = (capability: unknown, reach: AppReach): OperationNode | undefined => {
1702
- if (runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app') {
3209
+ if (app(capability)) {
1703
3210
  return appRecordPredicate(context, capability, reach)
1704
3211
  }
1705
3212
  return child ? childListPredicate(context, capability, 'read') : dimensionListPredicate(context, capability, 'read')
1706
3213
  }
1707
- // A capability reads the columns of its own action, as ctx.db does.
1708
- const visible = (capability: unknown): readonly string[] => visibleFor(context.model, heldAction(context, capability))
3214
+ // A capability reads the columns of its own action, as ctx.db does; an `app` one those its reaching actions read alone.
3215
+ const visible = (capability: unknown): readonly string[] =>
3216
+ app(capability)
3217
+ ? visibleThrough(context.model, appRecordRead(context, capability, 'rows').reach)
3218
+ : visibleFor(context.model, heldAction(context, capability))
1709
3219
  const { run, held } = probeRunner(context)
1710
3220
  return freeze({
1711
3221
  mode: child ? 'child' : 'dimension',
@@ -1716,12 +3226,12 @@ function probeOf(context: TableContext): TableProbe {
1716
3226
  context,
1717
3227
  list(capability, 'rows'),
1718
3228
  finishSelect(start, start),
1719
- heldAction(context, capability),
3229
+ soleAction(context, capability),
1720
3230
  visible(capability),
1721
3231
  )
1722
3232
  },
1723
3233
  group: async (capability: unknown, columns: readonly string[]) =>
1724
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(
3234
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(
1725
3235
  context,
1726
3236
  run,
1727
3237
  list(capability, 'rows'),
@@ -1777,8 +3287,7 @@ function appProbeOf(context: TableContext): TableProbe {
1777
3287
  mode: 'app',
1778
3288
  get: async (capability: unknown, key?: string) => {
1779
3289
  if (scoped(capability)) {
1780
- scopedApplicationRead(context, capability)
1781
- return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
3290
+ return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
1782
3291
  }
1783
3292
  return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
1784
3293
  },
@@ -1788,12 +3297,12 @@ function appProbeOf(context: TableContext): TableProbe {
1788
3297
  context,
1789
3298
  every(capability),
1790
3299
  finishSelect(start, start),
1791
- heldAction(context, capability),
3300
+ soleAction(context, capability),
1792
3301
  )
1793
3302
  },
1794
3303
  count,
1795
3304
  group: async (capability: unknown, columns: readonly string[]) =>
1796
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
3305
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
1797
3306
  groupBy: columns,
1798
3307
  count: true,
1799
3308
  }),
@@ -1827,11 +3336,11 @@ function destinationOf(models: TableModels, model: TableModel, parent: TableMode
1827
3336
 
1828
3337
  /** What a select or an aggregate of a capability that reads `visible` may name: those columns, and no join. */
1829
3338
  export function actionShape(model: TableModel, visible: readonly string[]): TableShape {
1830
- return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates })
3339
+ return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates, json: model.json })
1831
3340
  }
1832
3341
 
1833
3342
  function shapeOf(model: TableModel, joinable: Readonly<Record<string, JoinShape>>): TableShape {
1834
- return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates })
3343
+ return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates, json: model.json })
1835
3344
  }
1836
3345
 
1837
3346
  function joinShapes(models: TableModels, parent: TableModel): Readonly<Record<string, JoinShape>> {
@@ -1879,6 +3388,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
1879
3388
  export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1880
3389
  const models = tableModels(tables)
1881
3390
  const connection: Connection = { runtime: undefined }
3391
+ const layer = layerReach(models)
3392
+ const { relations, members, subqueries } = layer
1882
3393
 
1883
3394
  function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
1884
3395
  const model = typeof table === 'string' ? modelOf(models, table) : undefined
@@ -1890,6 +3401,15 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1890
3401
 
1891
3402
  function contextOf(model: TableModel): TableContext {
1892
3403
  const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
3404
+ const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
3405
+ ? freeze({
3406
+ column: model.scope.column,
3407
+ table: parent.name,
3408
+ key: parent.scope.key,
3409
+ access: viewAccessLinks(model, model.scope.key),
3410
+ context: contextOf(freeze({ ...parent, when: freeze({}), relationWhen: freeze({}) })),
3411
+ })
3412
+ : undefined
1893
3413
  const joinable = joinShapes(models, model)
1894
3414
  const joins: Record<string, readonly ForeignKeyPair[]> = {}
1895
3415
  const children = ownKeys(joinable)
@@ -1900,8 +3420,35 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1900
3420
  setOwn(joins, child, join.on)
1901
3421
  }
1902
3422
  }
3423
+ const childModels: Record<string, TableModel> = {}
3424
+ for (let index = 0; index < children.length; index++) {
3425
+ const child = modelOf(models, children[index] ?? '')
3426
+ if (child !== undefined) {
3427
+ setOwn(childModels, child.name, child)
3428
+ }
3429
+ }
1903
3430
  const shape = shapeOf(model, joinable)
1904
- return freeze({ model, parent, destination: destinationOf(models, model, parent), shape, joins: freeze(joins), connection })
3431
+ const writers: PathBound[] = []
3432
+ const declared = pathWriters(models, model)
3433
+ for (let index = 0; index < declared.length; index++) {
3434
+ const writer = declared[index]
3435
+ const owner = writer === undefined ? undefined : modelOf(models, writer.path.table)
3436
+ if (writer !== undefined && owner !== undefined) writers[writers.length] = freeze({ ...writer, owner })
3437
+ }
3438
+ return freeze({
3439
+ model,
3440
+ parent,
3441
+ destination: destinationOf(models, model, parent),
3442
+ shape,
3443
+ joins: freeze(joins),
3444
+ children: freeze(childModels),
3445
+ connection,
3446
+ relations,
3447
+ members,
3448
+ subqueries,
3449
+ through,
3450
+ writers: freeze(writers),
3451
+ })
1905
3452
  }
1906
3453
 
1907
3454
  const database: ScopedDatabase<DB, P> = Object.freeze({ tables: tablePolicies(tables) })
@@ -1917,17 +3464,44 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1917
3464
  }
1918
3465
  return probeOf(contextFor(table, mode))
1919
3466
  },
1920
- bind(runtime: DataLayerRuntime): Locator {
3467
+ bind(runtime: DataLayerRuntime): ProvisionalBinding {
1921
3468
  if (connection.runtime !== undefined) {
1922
3469
  throw new CapabilityError('layer_unbound', 'the data layer is already connected; only the framework connects it, once, at boot')
1923
3470
  }
1924
- const bound: DataLayerRuntime = freeze({ database: runtime.database, capabilities: runtime.capabilities, readOnly: runtime.readOnly })
3471
+ const bound: DataLayerRuntime = freeze({
3472
+ database: runtime.database,
3473
+ capabilities: runtime.capabilities,
3474
+ readOnly: runtime.readOnly,
3475
+ projectWakes: runtime.projectWakes,
3476
+ })
1925
3477
  connection.runtime = bound
1926
- return async (dimension, id, using) => locateObject(models, bound, dimension, id, using)
3478
+ return freeze({
3479
+ locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
3480
+ relates: async (relation: string, node: string, principal: string) =>
3481
+ relationHolds(models, relations, subqueries, bound, relation, node, principal),
3482
+ reveals: async (relation: string, dimension: string, node: string, principal: string, action: string) =>
3483
+ revealHolds(relations, subqueries, bound, relation, dimension, node, principal, action),
3484
+ holdsThrough: async (
3485
+ dimension: string,
3486
+ id: string,
3487
+ action: string,
3488
+ principal: string,
3489
+ relations: readonly RelationHold[],
3490
+ paths: readonly ContainerGrant[],
3491
+ ) => heldThroughPaths(models, layer, bound, dimension, id, action, principal, relations, paths),
3492
+ revealsToMembers: async (revealing: string, values: readonly string[], dimension: string, node: string, action: string) =>
3493
+ membersRevealed(members, subqueries, bound, revealing, values, dimension, node, action),
3494
+ release() {
3495
+ if (connection.runtime === bound) {
3496
+ connection.runtime = undefined
3497
+ }
3498
+ },
3499
+ })
1927
3500
  },
1928
3501
  framework: freeze({
1929
3502
  webhooks: webhookTables(() => runtimeOf(connection)),
1930
- jobs: jobLeases(() => runtimeOf(connection)),
3503
+ jobs: jobLeases(() => runtimeOf(connection), leaseProjection(() => runtimeOf(connection))),
3504
+ wakes: jobWakes(() => runtimeOf(connection)),
1931
3505
  admissions: admissions(() => runtimeOf(connection)),
1932
3506
  files: storedFiles(() => runtimeOf(connection)),
1933
3507
  }),
@@ -1949,6 +3523,150 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1949
3523
  return database
1950
3524
  }
1951
3525
 
3526
+ /**
3527
+ * Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
3528
+ * node column, a condition path's target by its key), which the guard admits and nothing else.
3529
+ */
3530
+ function layerReach(
3531
+ models: TableModels,
3532
+ ): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
3533
+ const relations: Record<string, LayerRelation | AccessRelation> = {}
3534
+ const members: Record<string, MemberRevealModel[]> = {}
3535
+ const selected: Record<string, string[]> = {}
3536
+ const select = (table: string, column: string): void => {
3537
+ const columns = ownEntry(selected, table) ?? []
3538
+ if (!includes(columns, column)) columns[columns.length] = column
3539
+ setOwn(selected, table, columns)
3540
+ }
3541
+ const names = ownKeys(models)
3542
+ const reveals: Record<string, RevealModel[]> = {}
3543
+ const narrowed: Record<string, string[]> = {}
3544
+ for (let index = 0; index < names.length; index++) {
3545
+ const model = modelOf(models, names[index] ?? '')
3546
+ const conditioned = model === undefined ? [] : ownKeys(model.relationWhen)
3547
+ for (let position = 0; model !== undefined && position < conditioned.length; position++) {
3548
+ const relation = conditioned[position] ?? ''
3549
+ const conditions = ownEntry(model.relationWhen, relation) ?? {}
3550
+ const actions = ownKeys(conditions)
3551
+ const listed = ownEntry(narrowed, relation) ?? []
3552
+ for (let next = 0; next < actions.length; next++) {
3553
+ const action = actions[next] ?? ''
3554
+ if (!includes(listed, action)) listed[listed.length] = action
3555
+ const condition = ownEntry(conditions, action)
3556
+ if (condition !== undefined) addReach(condition, select)
3557
+ }
3558
+ setOwn(narrowed, relation, listed)
3559
+ }
3560
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
3561
+ const reveal = model.reveals[position]
3562
+ if (reveal === undefined) continue
3563
+ const listed = ownEntry(reveals, reveal.relation) ?? []
3564
+ listed[listed.length] = reveal
3565
+ setOwn(reveals, reveal.relation, listed)
3566
+ select(reveal.table, reveal.column)
3567
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3568
+ }
3569
+ for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
3570
+ const reveal = model.memberReveals[position]
3571
+ if (reveal === undefined) continue
3572
+ const listed = ownEntry(members, reveal.source) ?? []
3573
+ listed[listed.length] = reveal
3574
+ setOwn(members, reveal.source, listed)
3575
+ select(reveal.table, reveal.column)
3576
+ if (reveal.when !== undefined) addReach(reveal.when, select)
3577
+ }
3578
+ }
3579
+ for (let index = 0; index < names.length; index++) {
3580
+ const model = modelOf(models, names[index] ?? '')
3581
+ if (model === undefined) continue
3582
+ for (let position = 0; position < model.confers.length; position++) {
3583
+ const source = model.confers[position]
3584
+ if (source === undefined) continue
3585
+ const revealed = ownEntry(reveals, source.relation) ?? []
3586
+ const placed: Record<string, Readonly<Record<string, string>>> = {}
3587
+ setOwn(placed, model.name, placementOf(model))
3588
+ for (let next = 0; next < revealed.length; next++) {
3589
+ const table = revealed[next]?.table ?? ''
3590
+ const at = modelOf(models, table)
3591
+ if (at !== undefined) setOwn(placed, table, placementOf(at))
3592
+ }
3593
+ setOwn(
3594
+ relations,
3595
+ source.relation,
3596
+ freeze({
3597
+ ...source,
3598
+ kind: 'source',
3599
+ reveals: freeze(revealed),
3600
+ narrowed: freeze(ownEntry(narrowed, source.relation) ?? []),
3601
+ placed: freeze(placed),
3602
+ }),
3603
+ )
3604
+ select(source.table, source.node)
3605
+ if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
3606
+ if (source.when !== undefined) addReach(source.when, select)
3607
+ }
3608
+ for (let position = 0; position < model.access.length; position++) {
3609
+ const access = model.access[position]
3610
+ if (access === undefined) continue
3611
+ select(access.view, access.row)
3612
+ }
3613
+ for (let position = 0; position < model.readThrough.length; position++) {
3614
+ const path = model.readThrough[position]
3615
+ if (path === undefined) continue
3616
+ select(path.table, path.key)
3617
+ if (path.via !== undefined) select(path.via.table, path.via.key)
3618
+ for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
3619
+ }
3620
+ const actions = ownKeys(model.when)
3621
+ for (let position = 0; position < actions.length; position++) {
3622
+ const condition = ownEntry(model.when, actions[position] ?? '')
3623
+ if (condition !== undefined) addReach(condition, select)
3624
+ }
3625
+ }
3626
+ // A relation no table confers is served by the access views alone; a table that confers it adds them to its source.
3627
+ for (let index = 0; index < names.length; index++) {
3628
+ const model = modelOf(models, names[index] ?? '')
3629
+ for (let position = 0; model !== undefined && position < model.access.length; position++) {
3630
+ const access = model.access[position]
3631
+ if (access === undefined || ownEntry(relations, access.relation) !== undefined) continue
3632
+ const relation = access.relation
3633
+ setOwn(
3634
+ relations,
3635
+ relation,
3636
+ freeze({ kind: 'access', relation, dimension: access.dimension, narrowed: freeze(ownEntry(narrowed, relation) ?? []) }),
3637
+ )
3638
+ }
3639
+ }
3640
+ const subqueries: Record<string, readonly string[]> = {}
3641
+ const tablesRead = ownKeys(selected)
3642
+ for (let index = 0; index < tablesRead.length; index++) {
3643
+ const table = tablesRead[index] ?? ''
3644
+ setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
3645
+ }
3646
+ const revealing: Record<string, readonly MemberRevealModel[]> = {}
3647
+ const sources = ownKeys(members)
3648
+ for (let index = 0; index < sources.length; index++) {
3649
+ const source = sources[index] ?? ''
3650
+ setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
3651
+ }
3652
+ return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
3653
+ }
3654
+
3655
+ /** `model`'s column for each dimension a row of it lies at: its key at its own dimension, then each link of its chain. */
3656
+ function placementOf(model: TableModel): Readonly<Record<string, string>> {
3657
+ const placed: Record<string, string> = {}
3658
+ if (model.scope.mode === 'dimension') setOwn(placed, model.scope.dimension, model.scope.key)
3659
+ for (let index = 0; index < model.chain.length; index++) {
3660
+ const link = model.chain[index]
3661
+ if (link !== undefined && ownEntry(placed, link.dimension) === undefined) setOwn(placed, link.dimension, link.column)
3662
+ }
3663
+ return freeze(placed)
3664
+ }
3665
+
3666
+ function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
3667
+ conditionReach(condition, select)
3668
+ }
3669
+
1952
3670
  /** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
1953
3671
  function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
1954
3672
  const side = frameworkSideOf(database)
@@ -1991,6 +3709,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
1991
3709
  return undefined
1992
3710
  }
1993
3711
 
3712
+ /**
3713
+ * Whether an access view of `relation` lists `node` for `principal`: a guarded select of the row of the table that owns
3714
+ * the relation's dimension, by its key, under the access term. Only a principal-bound view answers; one bound to a
3715
+ * member node lists nothing for a hold anywhere, which is all `relates` asks about.
3716
+ */
3717
+ async function accessHolds(
3718
+ models: TableModels,
3719
+ subqueries: Readonly<Record<string, readonly string[]>>,
3720
+ runtime: DataLayerRuntime,
3721
+ relation: string,
3722
+ dimension: string,
3723
+ node: string,
3724
+ principal: string,
3725
+ ): Promise<boolean> {
3726
+ const names = ownKeys(models)
3727
+ for (let index = 0; index < names.length; index++) {
3728
+ const model = modelOf(models, names[index] ?? '')
3729
+ if (model === undefined || model.scope.mode !== 'dimension' || model.scope.dimension !== dimension) continue
3730
+ const terms = relationTerms(
3731
+ { [relation]: freeze({ kind: 'access', relation, dimension, narrowed: freeze([]) }) },
3732
+ model,
3733
+ { relation, inside: null },
3734
+ principal,
3735
+ '',
3736
+ new Date(),
3737
+ noPath,
3738
+ )
3739
+ if (terms.length === 0) continue
3740
+ const scope = AndNode.create(equals(model.name, keyOf(model), node), anyOf(terms))
3741
+ const context: GuardContext = { root: 'SelectQueryNode', table: model.name, joins: {}, scope, subqueries }
3742
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(model.name, [keyOf(model)], scope), context)
3743
+ if (rows.length > 0) return true
3744
+ }
3745
+ return false
3746
+ }
3747
+
1994
3748
  /** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
1995
3749
  function locatedOwner(models: TableModels, dimension: unknown): TableModel {
1996
3750
  const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
@@ -2000,6 +3754,298 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
2000
3754
  return owner
2001
3755
  }
2002
3756
 
3757
+ /** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
3758
+ async function relationHolds(
3759
+ models: TableModels,
3760
+ relations: RelationSources,
3761
+ subqueries: Readonly<Record<string, readonly string[]>>,
3762
+ runtime: DataLayerRuntime,
3763
+ relation: string,
3764
+ node: string,
3765
+ principal: string,
3766
+ ): Promise<boolean> {
3767
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3768
+ throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
3769
+ }
3770
+ const known = knownRelation(relations, relation)
3771
+ if (known.kind === 'access') {
3772
+ return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
3773
+ }
3774
+ const source = relationSource(relations, relation)
3775
+ const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
3776
+ const active = activeRow(source, new Date())
3777
+ const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
3778
+ const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
3779
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
3780
+ // A relation with a source table may also name access views: the same term answers through them.
3781
+ return rows.length > 0 || accessHolds(models, subqueries, runtime, relation, source.dimension, node, principal)
3782
+ }
3783
+
3784
+ /**
3785
+ * Locks the first row that holds `grant`'s action for its principal at its object or a container on its chain, if any:
3786
+ * a source row naming it there, a row the relation reaches that reveals that node, or a row at a node the Ref's
3787
+ * revealing grants name that reveals it to its members.
3788
+ */
3789
+ async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
3790
+ const now = new Date()
3791
+ const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
3792
+ const candidates: { table: string; column: string; scope: OperationNode }[] = []
3793
+ for (let index = 0; index < grant.revealing.length; index++) {
3794
+ const revealing = grant.revealing[index]
3795
+ const reveals = revealing === undefined ? [] : ownEntry(context.members, revealing.dimension) ?? []
3796
+ for (let position = 0; revealing !== undefined && position < reveals.length; position++) {
3797
+ const reveal = reveals[position]
3798
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3799
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3800
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3801
+ if (reveal === undefined || revealed === undefined || revealing.values.length === 0) continue
3802
+ candidates[candidates.length] = { table: reveal.table, column: reveal.key, scope: memberAddress(reveal, revealing.values, revealed, now) }
3803
+ }
3804
+ }
3805
+ for (let index = 0; index < grant.relations.length; index++) {
3806
+ const hold = grant.relations[index]
3807
+ // An access view's base rows are not the data layer's to lock (ADR-0076): such a hold holds no destination here.
3808
+ if (hold === undefined || knownRelation(context.relations, hold.relation).kind === 'access') continue
3809
+ const source = relationSource(context.relations, hold.relation)
3810
+ const node = nodeOf(source.dimension)
3811
+ const sourceInside = insideRow(source, source.table, hold)
3812
+ if (node !== undefined && sourceInside !== null) {
3813
+ const parts = [equals(source.table, source.node, node), namesPrincipal(source, grant.principal)]
3814
+ if (sourceInside !== undefined) parts[parts.length] = sourceInside
3815
+ const address = allOf(parts)
3816
+ const active = activeRow(source, now)
3817
+ candidates[candidates.length] = {
3818
+ table: source.table,
3819
+ column: source.node,
3820
+ scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
3821
+ }
3822
+ }
3823
+ for (let position = 0; position < source.reveals.length; position++) {
3824
+ const reveal = source.reveals[position]
3825
+ const held = reveal !== undefined && includes(reveal.actions, grant.action)
3826
+ && (reveal.path === undefined || includes(reveal.path.writes, grant.action))
3827
+ const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
3828
+ const revealInside = reveal === undefined ? null : insideRow(source, reveal.table, hold)
3829
+ if (reveal !== undefined && revealed !== undefined && revealInside !== null) {
3830
+ const address = revealAddress(source, reveal, revealed, grant.principal, now)
3831
+ candidates[candidates.length] = {
3832
+ table: reveal.table,
3833
+ column: reveal.column,
3834
+ scope: revealInside === undefined ? address : allOf([address, revealInside]),
3835
+ }
3836
+ }
3837
+ }
3838
+ }
3839
+ for (let position = 0; position < candidates.length; position++) {
3840
+ const candidate = candidates[position]
3841
+ if (candidate === undefined) continue
3842
+ const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
3843
+ root: 'SelectQueryNode',
3844
+ table: candidate.table,
3845
+ joins: {},
3846
+ scope: candidate.scope,
3847
+ lock: 'share',
3848
+ subqueries: context.subqueries,
3849
+ })
3850
+ if (rows.length > 0) return true
3851
+ }
3852
+ return false
3853
+ }
3854
+
3855
+ /**
3856
+ * What a row of `table` (the relation's source or a reveal's table) must meet to hold under `hold`: nothing
3857
+ * (`undefined`) for a hold anywhere, its column for the hold's dimension among the hold's values for one inside a node,
3858
+ * and null when it has no such column, so it is not inside and holds nothing.
3859
+ */
3860
+ function insideRow(source: LayerRelation, table: string, hold: RelationHold): OperationNode | undefined | null {
3861
+ if (hold.inside === null) {
3862
+ return undefined
3863
+ }
3864
+ const placed = ownEntry(source.placed, table)
3865
+ const column = placed === undefined ? undefined : ownEntry(placed, hold.inside.dimension)
3866
+ return column === undefined || hold.inside.values.length === 0 ? null : isIn(table, column, valueList(hold.inside.values))
3867
+ }
3868
+
3869
+ /** `R.<ancestor> = $node and (R.<key> in (values) and <when>)`: a row at a node `values` name that reveals `node` now. */
3870
+ function memberAddress(reveal: MemberRevealModel, values: readonly string[], node: string, now: Date): OperationNode {
3871
+ const named = inList(reveal.table, reveal.key, values)
3872
+ const held = reveal.when === undefined ? named : allOf([named, conditionNode(reveal.table, reveal.when, now)])
3873
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(held))
3874
+ }
3875
+
3876
+ /** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
3877
+ function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
3878
+ const revealed = BinaryOperationNode.create(
3879
+ column(reveal.table, reveal.column),
3880
+ OperatorNode.create('in'),
3881
+ revealedNodes(source, reveal, principal, now),
3882
+ )
3883
+ return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
3884
+ }
3885
+
3886
+ /** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
3887
+ async function revealHolds(
3888
+ relations: RelationSources,
3889
+ subqueries: Readonly<Record<string, readonly string[]>>,
3890
+ runtime: DataLayerRuntime,
3891
+ relation: string,
3892
+ dimension: string,
3893
+ node: string,
3894
+ principal: string,
3895
+ action: string,
3896
+ ): Promise<boolean> {
3897
+ if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
3898
+ throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
3899
+ }
3900
+ const source = relationSource(relations, relation)
3901
+ for (let index = 0; index < source.reveals.length; index++) {
3902
+ const reveal = source.reveals[index]
3903
+ // A reveal matched through a secondary path holds a Ref's action only where the path holds it (`writeThrough`).
3904
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3905
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3906
+ const address = revealAddress(source, reveal, node, principal, new Date())
3907
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
3908
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
3909
+ if (rows.length > 0) return true
3910
+ }
3911
+ return false
3912
+ }
3913
+
3914
+ /**
3915
+ * Of `values`, nodes of `revealing` at which the caller holds `action`, the ones whose row reveals `node` of `dimension`
3916
+ * for it now: one guarded select per member reveal of `revealing` to `dimension` that lists `action`.
3917
+ */
3918
+ async function membersRevealed(
3919
+ members: MemberReveals,
3920
+ subqueries: Readonly<Record<string, readonly string[]>>,
3921
+ runtime: DataLayerRuntime,
3922
+ revealing: string,
3923
+ values: readonly string[],
3924
+ dimension: string,
3925
+ node: string,
3926
+ action: string,
3927
+ ): Promise<readonly string[]> {
3928
+ if (typeof node !== 'string' || node.length === 0 || !isArray(values) || values.length > MAX_WITHIN_VALUES) {
3929
+ throw new QueryRefusedError('row_address', `a node ${revealing} reveals is addressed by its node and at most ${MAX_WITHIN_VALUES} grants`)
3930
+ }
3931
+ for (let index = 0; index < values.length; index++) {
3932
+ if (typeof values[index] !== 'string' || values[index] === '') {
3933
+ throw new QueryRefusedError('row_address', `a grant at ${revealing} names its node, a non-empty string`)
3934
+ }
3935
+ }
3936
+ const reveals = ownEntry(members, revealing) ?? []
3937
+ const found: string[] = []
3938
+ for (let index = 0; values.length > 0 && index < reveals.length; index++) {
3939
+ const reveal = reveals[index]
3940
+ if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
3941
+ if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
3942
+ const scope = memberAddress(reveal, values, node, new Date())
3943
+ const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope, subqueries }
3944
+ // Grouped, not limited: through a path many rows name one grant's node, and every grant matched is carried.
3945
+ const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(valuesNode(reveal.table, reveal.key, scope), context)
3946
+ for (let position = 0; position < rows.length; position++) {
3947
+ const key = ownEntry(rows[position] ?? {}, reveal.key)
3948
+ if (typeof key === 'string' && !includes(found, key)) found[found.length] = key
3949
+ }
3950
+ }
3951
+ return freeze(found)
3952
+ }
3953
+
3954
+ /**
3955
+ * Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
3956
+ * through a relation row, a reveal or a secondary path that holds the action for a `Ref` (`writeThrough`): one guarded
3957
+ * select per candidate. What `on` and `in` mint a `Ref` held through a path with, and through a relation held inside a
3958
+ * node: the statement compares the object's column for the node's dimension with the held values, and the relation
3959
+ * comes back held inside the node that column stores, so every spelling the database equates is one node.
3960
+ */
3961
+ async function heldThroughPaths(
3962
+ models: TableModels,
3963
+ layer: ReturnType<typeof layerReach>,
3964
+ runtime: DataLayerRuntime,
3965
+ dimension: string,
3966
+ id: string,
3967
+ action: string,
3968
+ principal: string,
3969
+ relations: readonly RelationHold[],
3970
+ paths: readonly ContainerGrant[],
3971
+ ): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }> {
3972
+ const owner = locatedOwner(models, dimension)
3973
+ if (typeof id !== 'string' || id.length === 0 || typeof principal !== 'string' || principal.length === 0 || typeof action !== 'string') {
3974
+ throw new QueryRefusedError('row_address', `a ${dimension} held through a path is addressed by its key, the principal and the action`)
3975
+ }
3976
+ let count = 0
3977
+ const grantOf = (grant: unknown, what: string): ContainerGrant => {
3978
+ const at: unknown = typeof grant === 'object' && grant !== null ? ownDescriptor(grant, 'dimension')?.value : undefined
3979
+ const values = typeof grant === 'object' && grant !== null
3980
+ ? parseList(ownDescriptor(grant, 'values')?.value, (value) => {
3981
+ if (typeof value !== 'string' || value === '') throw new QueryRefusedError('row_address', 'a grant names its node, a non-empty string')
3982
+ return value
3983
+ })
3984
+ : undefined
3985
+ if (typeof at !== 'string' || values === undefined) {
3986
+ throw new QueryRefusedError('row_address', `${what} names its dimension and its nodes`)
3987
+ }
3988
+ count += values.length
3989
+ return freeze({ dimension: at, values: freeze(values) })
3990
+ }
3991
+ const named = parseList(relations, (hold): RelationHold => {
3992
+ const relation: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'relation')?.value : undefined
3993
+ const inside: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'inside')?.value : undefined
3994
+ if (typeof relation !== 'string') throw new QueryRefusedError('row_address', 'a relation is named by its name')
3995
+ return freeze({ relation, inside: inside === null ? null : grantOf(inside, 'a relation held inside a node') })
3996
+ })
3997
+ const grants = parseList(paths, (grant): ContainerGrant => grantOf(grant, 'a grant of a path'))
3998
+ if (named === undefined || grants === undefined) {
3999
+ throw new QueryRefusedError('row_address', 'the candidates of a path are plain arrays')
4000
+ }
4001
+ if (count > MAX_WITHIN_VALUES) {
4002
+ throw new QueryRefusedError('row_address', `the grants of a path carry at most ${MAX_WITHIN_VALUES} nodes`)
4003
+ }
4004
+ const now = new Date()
4005
+ const session = sessionOf(runtime)
4006
+ const reached = async (
4007
+ terms: readonly OperationNode[],
4008
+ column: string,
4009
+ inside?: readonly string[],
4010
+ ): Promise<Readonly<Record<string, unknown>> | undefined> => {
4011
+ if (terms.length === 0) return undefined
4012
+ const found = AndNode.create(equals(owner.name, keyOf(owner), id), anyOf(terms))
4013
+ // A member-bound access term is not narrowed to the node (ADR-0076): the object's own column is, as the database compares it.
4014
+ const scope = inside === undefined ? found : AndNode.create(found, ParensNode.create(isIn(owner.name, column, valueList(inside))))
4015
+ const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, subqueries: layer.subqueries }
4016
+ const columns = column === keyOf(owner) ? [column] : [keyOf(owner), column]
4017
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
4018
+ return row
4019
+ }
4020
+ const held: RelationHold[] = []
4021
+ for (let index = 0; index < named.length; index++) {
4022
+ const hold = named[index]
4023
+ if (hold === undefined) continue
4024
+ const column = hold.inside === null ? keyOf(owner) : nodeColumnOf(owner, hold.inside.dimension)
4025
+ const row = column === undefined
4026
+ ? undefined
4027
+ : await reached(relationTerms(layer.relations, owner, hold, principal, action, now, heldThrough(action)), column, hold.inside?.values)
4028
+ if (row === undefined || column === undefined) continue
4029
+ if (hold.inside === null) {
4030
+ held[held.length] = hold
4031
+ continue
4032
+ }
4033
+ const node = ownEntry(row, column)
4034
+ if (typeof node !== 'string') {
4035
+ throw new PolicyError(`${owner.name}.${column} came back as ${typeof node}; a containment column holds its scope value as text`)
4036
+ }
4037
+ held[held.length] = freeze({ relation: hold.relation, inside: freeze({ dimension: hold.inside.dimension, values: freeze([node]) }) })
4038
+ }
4039
+ const through: ContainerGrant[] = []
4040
+ for (let index = 0; index < grants.length; index++) {
4041
+ const grant = grants[index]
4042
+ if (grant !== undefined && (await reached(pathTerms(owner, [grant], heldThrough(action)), keyOf(owner))) !== undefined) {
4043
+ through[through.length] = grant
4044
+ }
4045
+ }
4046
+ return freeze({ relations: freeze(held), paths: freeze(through) })
4047
+ }
4048
+
2003
4049
  /** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
2004
4050
  async function locateObject(
2005
4051
  models: TableModels,
@@ -2012,6 +4058,11 @@ async function locateObject(
2012
4058
  if (typeof id !== 'string' || id.length === 0) {
2013
4059
  throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
2014
4060
  }
4061
+ return chainOf(owner, using ?? sessionOf(runtime), id)
4062
+ }
4063
+
4064
+ /** The containers of `owner`'s row keyed `id`, by dimension, read in `session`; `null` for no such row. */
4065
+ async function chainOf(owner: TableModel, session: Session, id: string): Promise<ReadonlyMap<string, string> | null> {
2015
4066
  const key = keyOf(owner)
2016
4067
  const scope = equals(owner.name, key, id)
2017
4068
  const columns: string[] = [key]
@@ -2019,7 +4070,7 @@ async function locateObject(
2019
4070
  columns[columns.length] = owner.chain[index]?.column ?? ''
2020
4071
  }
2021
4072
  const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
2022
- const [row] = await (using ?? sessionOf(runtime)).run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
4073
+ const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
2023
4074
  if (row === undefined) {
2024
4075
  return null
2025
4076
  }