@fabrika/db 0.9.0-dev.6 → 0.9.0-dev.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +9 -5
- package/src/authority.ts +560 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +51 -2
- package/src/codegen-sqlite.ts +59 -11
- package/src/codegen.ts +181 -42
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/description.ts +55 -9
- package/src/errors.ts +8 -4
- package/src/file-columns.ts +52 -10
- package/src/framework.ts +5 -2
- package/src/guard.ts +365 -15
- package/src/index.ts +8 -0
- package/src/job-leases.ts +19 -2
- package/src/job-wakes.ts +183 -33
- package/src/json.ts +124 -0
- package/src/list-cursor.ts +82 -0
- package/src/migrations-sqlite.ts +93 -0
- package/src/migrations.ts +99 -0
- package/src/nodes.ts +33 -14
- package/src/notifications.ts +152 -0
- package/src/orm-types.ts +208 -74
- package/src/orm.ts +417 -158
- package/src/policy.ts +1973 -141
- package/src/push-subscriptions.ts +287 -0
- package/src/registry.ts +50 -1
- package/src/request-receipts.ts +107 -0
- package/src/sql.ts +39 -11
- package/src/sqlite-migrate.ts +102 -1
- package/src/sqlite.ts +46 -1
- package/src/store.ts +1933 -168
- package/src/tables.ts +156 -6
- package/src/temporal.ts +8 -1
- package/src/testing-shared.ts +758 -140
- package/src/testing-sqlite.ts +212 -40
- package/src/testing.ts +151 -22
- package/src/vocabulary-tables.ts +159 -27
- package/types/src/authority.d.ts +147 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +50 -2
- package/types/src/codegen-sqlite.d.ts +8 -1
- package/types/src/codegen.d.ts +54 -10
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/description.d.ts +31 -9
- package/types/src/errors.d.ts +7 -4
- package/types/src/file-columns.d.ts +6 -4
- package/types/src/framework.d.ts +5 -2
- package/types/src/guard.d.ts +24 -0
- package/types/src/index.d.ts +4 -3
- package/types/src/job-leases.d.ts +8 -1
- package/types/src/job-wakes.d.ts +28 -5
- package/types/src/json.d.ts +18 -0
- package/types/src/list-cursor.d.ts +13 -0
- package/types/src/migrations.d.ts +5 -0
- package/types/src/nodes.d.ts +5 -1
- package/types/src/notifications.d.ts +37 -0
- package/types/src/orm-types.d.ts +165 -73
- package/types/src/orm.d.ts +21 -0
- package/types/src/policy.d.ts +347 -23
- package/types/src/push-subscriptions.d.ts +49 -0
- package/types/src/registry.d.ts +36 -1
- package/types/src/request-receipts.d.ts +22 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/sqlite-migrate.d.ts +32 -0
- package/types/src/store.d.ts +118 -31
- package/types/src/tables.d.ts +8 -2
- package/types/src/temporal.d.ts +4 -1
- package/types/src/testing-shared.d.ts +112 -23
- package/types/src/testing-sqlite.d.ts +17 -2
- package/types/src/testing.d.ts +1 -1
- package/types/src/vocabulary-tables.d.ts +169 -22
package/src/store.ts
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
import { uuidv7 } from '@fabrika/platform'
|
|
2
|
-
import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
|
|
2
|
+
import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, type ReturningNode, ValueNode } from 'kysely'
|
|
3
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'
|
|
4
34
|
import {
|
|
5
35
|
defineValue,
|
|
6
36
|
freeze,
|
|
@@ -25,21 +55,29 @@ import {
|
|
|
25
55
|
type AppGrant,
|
|
26
56
|
type CapabilityAuthority,
|
|
27
57
|
type CapabilityGrant,
|
|
58
|
+
type ContainerGrant,
|
|
28
59
|
describeGrant,
|
|
29
60
|
MAX_WITHIN_VALUES,
|
|
30
61
|
type Ref,
|
|
31
62
|
type RefGrant,
|
|
63
|
+
type RelationHold,
|
|
32
64
|
type Within,
|
|
33
65
|
type WithinGrant,
|
|
34
66
|
} from './capability'
|
|
67
|
+
import { conditionNode, subquery } from './condition-nodes'
|
|
68
|
+
import { type ConditionModel, conditionReach, readPaths, rowSatisfies } from './conditions'
|
|
35
69
|
import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
|
|
36
70
|
import {
|
|
71
|
+
type ComparableColumn,
|
|
72
|
+
comparableColumnOf,
|
|
37
73
|
type Compare,
|
|
38
74
|
type Condition,
|
|
39
75
|
type Contains,
|
|
76
|
+
finishFilter,
|
|
40
77
|
finishSelect,
|
|
41
78
|
isPrimitive,
|
|
42
79
|
type JoinShape,
|
|
80
|
+
type JoinState,
|
|
43
81
|
type NoColumns,
|
|
44
82
|
type Primitive,
|
|
45
83
|
type ScopedSelect,
|
|
@@ -51,9 +89,10 @@ import { CapabilityError, ConflictError, NotFoundError, PolicyError, QueryRefuse
|
|
|
51
89
|
import { answerFiles, type FileBinding, fileValue, referenceFiles, rowScope, storedRowScope } from './file-columns'
|
|
52
90
|
import { fileReference } from './file-references'
|
|
53
91
|
import { webhookTables } from './framework-tables'
|
|
54
|
-
import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
|
|
92
|
+
import type { ForeignKeyPair, GuardContext, RootKind, ViewAccessLink, ViewParentLink } from './guard'
|
|
55
93
|
import { fencedTransaction, jobLeases } from './job-leases'
|
|
56
94
|
import { jobWakes, leaseProjection } from './job-wakes'
|
|
95
|
+
import { jsonInput } from './json'
|
|
57
96
|
import { linksPredicate, type LinkValue, linkValues } from './links'
|
|
58
97
|
import {
|
|
59
98
|
acknowledgement,
|
|
@@ -74,7 +113,10 @@ import {
|
|
|
74
113
|
scopedWhere,
|
|
75
114
|
selectNode,
|
|
76
115
|
updateNode,
|
|
116
|
+
valueList,
|
|
117
|
+
valuesNode,
|
|
77
118
|
} from './nodes'
|
|
119
|
+
import { notifications } from './notifications'
|
|
78
120
|
import { dataAccess } from './orm'
|
|
79
121
|
import {
|
|
80
122
|
type Acknowledgement,
|
|
@@ -82,28 +124,41 @@ import {
|
|
|
82
124
|
type ChildTableName,
|
|
83
125
|
type Container,
|
|
84
126
|
type ContainerOf,
|
|
127
|
+
delegates,
|
|
85
128
|
type DimensionOf,
|
|
86
129
|
type DimensionTableName,
|
|
87
130
|
includes,
|
|
88
131
|
type InsertValues,
|
|
89
132
|
type JoinableChildren,
|
|
90
133
|
type ListDimensionOf,
|
|
134
|
+
type MemberRevealModel,
|
|
91
135
|
modelOf,
|
|
92
136
|
type MoveAcknowledgement,
|
|
93
137
|
namesAction,
|
|
138
|
+
nodeColumnOf,
|
|
94
139
|
type Operation,
|
|
95
140
|
type ParentOf,
|
|
141
|
+
type PathWriter,
|
|
142
|
+
pathWriters,
|
|
96
143
|
type PolicyRow,
|
|
144
|
+
type ReadReach,
|
|
145
|
+
type RevealModel,
|
|
146
|
+
type SecondaryPath,
|
|
97
147
|
type TableModel,
|
|
98
148
|
type TableModels,
|
|
99
149
|
tableModels,
|
|
100
150
|
type Tables,
|
|
151
|
+
updatableBy,
|
|
152
|
+
updatableByAny,
|
|
101
153
|
updateActions,
|
|
102
154
|
type UpdateValues,
|
|
103
155
|
type VersionArguments,
|
|
104
156
|
visibleFor,
|
|
157
|
+
visibleThrough,
|
|
105
158
|
} from './policy'
|
|
159
|
+
import { pushSubscriptions } from './push-subscriptions'
|
|
106
160
|
import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
|
|
161
|
+
import { requestReceipts } from './request-receipts'
|
|
107
162
|
import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
|
|
108
163
|
import { storedFiles, storedFilesMetadata } from './stored-files'
|
|
109
164
|
import { type TablePolicies, tablePolicies } from './tables'
|
|
@@ -136,6 +191,36 @@ export interface TableContext {
|
|
|
136
191
|
/** The model of each child a select may join, by its table name. */
|
|
137
192
|
readonly children: Readonly<Record<string, TableModel>>
|
|
138
193
|
readonly connection: Connection
|
|
194
|
+
/** Every relation of the layer with its source table: what a relation term of any table reads. */
|
|
195
|
+
readonly relations: RelationSources
|
|
196
|
+
/** Every member reveal of the layer, by the dimension whose grants it reveals to: what a `Within`'s read adds. */
|
|
197
|
+
readonly members: MemberReveals
|
|
198
|
+
/** The tables a scope predicate's subqueries read, each with the column they select: what the guard admits. */
|
|
199
|
+
readonly subqueries: Readonly<Record<string, readonly string[]>>
|
|
200
|
+
/** A child view's parent, which every capability reads the view's rows through; `undefined` for any other table. */
|
|
201
|
+
readonly through: ViewParent | undefined
|
|
202
|
+
/** The path columns whose insert hands out actions, each with the table owning the node it names (`pathWriters`). */
|
|
203
|
+
readonly writers: readonly PathBound[]
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** A path column an insert writes under its bound, and the table that owns the dimension it names. */
|
|
207
|
+
export interface PathBound extends PathWriter {
|
|
208
|
+
readonly owner: TableModel
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** A child view's parent link, with the parent's context: its model without conditions, as only the view's own narrow a read. */
|
|
212
|
+
export interface ViewParent extends ViewParentLink {
|
|
213
|
+
readonly context: TableContext
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** A child view's access views, as the guard admits them on its statements: its key in each view's row column. */
|
|
217
|
+
function viewAccessLinks(model: TableModel, key: string): readonly ViewAccessLink[] {
|
|
218
|
+
const links: ViewAccessLink[] = []
|
|
219
|
+
for (let index = 0; index < model.access.length; index++) {
|
|
220
|
+
const access = model.access[index]
|
|
221
|
+
if (access !== undefined) links[links.length] = freeze({ key, view: access.view, row: access.row })
|
|
222
|
+
}
|
|
223
|
+
return freeze(links)
|
|
139
224
|
}
|
|
140
225
|
|
|
141
226
|
/** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
|
|
@@ -145,7 +230,7 @@ export function dialectOf(context: TableContext): SqlDialect {
|
|
|
145
230
|
|
|
146
231
|
/** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
|
|
147
232
|
export function rowColumnsOf(model: TableModel): RowColumns {
|
|
148
|
-
return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans }
|
|
233
|
+
return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json }
|
|
149
234
|
}
|
|
150
235
|
|
|
151
236
|
/** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
|
|
@@ -296,13 +381,17 @@ function withinGrant(context: TableContext, capability: unknown, dimension: stri
|
|
|
296
381
|
return grant
|
|
297
382
|
}
|
|
298
383
|
|
|
299
|
-
/**
|
|
384
|
+
/**
|
|
385
|
+
* The links that lie above the `Within`'s own dimension: the only columns a container grant may filter on. A dimension
|
|
386
|
+
* table's own dimension counts, so its containers lie above a `Within` of it.
|
|
387
|
+
*/
|
|
300
388
|
function linksAbove(model: TableModel, dimension: string): readonly Container[] {
|
|
301
|
-
|
|
302
|
-
|
|
389
|
+
const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
|
|
390
|
+
for (let index = 0; index < links.length; index++) {
|
|
391
|
+
if (links[index]?.dimension === dimension) {
|
|
303
392
|
const above: Container[] = []
|
|
304
|
-
for (let position = index + 1; position <
|
|
305
|
-
const link =
|
|
393
|
+
for (let position = index + 1; position < links.length; position++) {
|
|
394
|
+
const link = links[position]
|
|
306
395
|
if (link !== undefined) {
|
|
307
396
|
above[above.length] = link
|
|
308
397
|
}
|
|
@@ -380,6 +469,9 @@ function withinCount(grant: WithinGrant): number {
|
|
|
380
469
|
for (let index = 0; index < grant.contained.length; index++) {
|
|
381
470
|
count += grant.contained[index]?.values.length ?? 0
|
|
382
471
|
}
|
|
472
|
+
for (let index = 0; index < grant.revealing.length; index++) {
|
|
473
|
+
count += grant.revealing[index]?.values.length ?? 0
|
|
474
|
+
}
|
|
383
475
|
return count
|
|
384
476
|
}
|
|
385
477
|
|
|
@@ -388,9 +480,11 @@ function withinCount(grant: WithinGrant): number {
|
|
|
388
480
|
* the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
|
|
389
481
|
* answers `[]` without a query.
|
|
390
482
|
*/
|
|
391
|
-
function withinPredicate(
|
|
483
|
+
function withinPredicate(context: TableContext, column: string, grant: WithinGrant, operation: Operation): OperationNode | undefined {
|
|
484
|
+
const model = context.model
|
|
485
|
+
const now = new Date()
|
|
392
486
|
if (grant.values === 'all') {
|
|
393
|
-
return
|
|
487
|
+
return conditioned(model, grant.action, 'all', now)
|
|
394
488
|
}
|
|
395
489
|
const above = linksAbove(model, grant.dimension)
|
|
396
490
|
const predicates: OperationNode[] = []
|
|
@@ -424,7 +518,80 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
|
|
|
424
518
|
if (count > MAX_WITHIN_VALUES) {
|
|
425
519
|
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
|
|
426
520
|
}
|
|
427
|
-
|
|
521
|
+
addRelationTerms(context, grant, operation === 'read', predicates, now)
|
|
522
|
+
if (operation === 'read') addMemberTerms(context, grant, predicates, now)
|
|
523
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/** A `Within`'s read also reaches the rows under a node its member reveals hold the action at; no write does. */
|
|
527
|
+
function addMemberTerms(context: TableContext, grant: WithinGrant, predicates: OperationNode[], now: Date): void {
|
|
528
|
+
const terms = memberTerms(context.members, context.model, grant, now)
|
|
529
|
+
for (let index = 0; index < terms.length; index++) {
|
|
530
|
+
const term = terms[index]
|
|
531
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** The relation terms of a `Within`'s relations; a relation whose dimension this table lies at no node of reaches none of its rows. */
|
|
536
|
+
function addRelationTerms(context: TableContext, grant: WithinGrant, reads: boolean, predicates: OperationNode[], now: Date): void {
|
|
537
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
538
|
+
const hold = grant.relations[index]
|
|
539
|
+
if (hold === undefined) continue
|
|
540
|
+
const terms = relationTerms(
|
|
541
|
+
context.relations,
|
|
542
|
+
context.model,
|
|
543
|
+
hold,
|
|
544
|
+
grant.principal,
|
|
545
|
+
grant.action,
|
|
546
|
+
now,
|
|
547
|
+
reads ? everyPath : noPath,
|
|
548
|
+
)
|
|
549
|
+
for (let position = 0; position < terms.length; position++) {
|
|
550
|
+
const term = terms[position]
|
|
551
|
+
if (term !== undefined) predicates[predicates.length] = term
|
|
552
|
+
}
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
/**
|
|
557
|
+
* The rows a `Within` of a dimension outside the chain reads through `paths`, the ones that reach it: per path
|
|
558
|
+
* `T.<column> in (values)` at the path's own dimension or `T.<column> in (select D.<key> from D where D.<link> in
|
|
559
|
+
* (values))` above it, the same for each container, then the relations' terms. A grant on a dimension inside the
|
|
560
|
+
* Within's lies at no node the column holds, so it reaches no row here.
|
|
561
|
+
*/
|
|
562
|
+
function secondaryPredicate(context: TableContext, paths: readonly SecondaryPath[], grant: WithinGrant): OperationNode | undefined {
|
|
563
|
+
const model = context.model
|
|
564
|
+
const now = new Date()
|
|
565
|
+
if (grant.values === 'all') {
|
|
566
|
+
return conditioned(model, grant.action, 'all', now)
|
|
567
|
+
}
|
|
568
|
+
if (withinCount(grant) > MAX_WITHIN_VALUES) {
|
|
569
|
+
throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${withinCount(grant)}`)
|
|
570
|
+
}
|
|
571
|
+
const predicates: OperationNode[] = []
|
|
572
|
+
for (let index = 0; index < paths.length; index++) {
|
|
573
|
+
const path = paths[index]
|
|
574
|
+
if (path === undefined) continue
|
|
575
|
+
if (grant.values.length > 0) {
|
|
576
|
+
const own = throughPath(model.name, path, grant.dimension, valueList(grant.values))
|
|
577
|
+
if (own !== undefined) predicates[predicates.length] = own
|
|
578
|
+
}
|
|
579
|
+
for (let position = 0; position < grant.containers.length; position++) {
|
|
580
|
+
const container = grant.containers[position]
|
|
581
|
+
if (container === undefined || container.values.length === 0) continue
|
|
582
|
+
const above = throughPath(model.name, path, container.dimension, valueList(container.values))
|
|
583
|
+
if (above === undefined) {
|
|
584
|
+
throw new CapabilityError(
|
|
585
|
+
'unenforceable',
|
|
586
|
+
`the Within of ${grant.dimension} reaches through ${container.dimension}, which ${path.table} carries no column for; the layer cannot enforce it`,
|
|
587
|
+
)
|
|
588
|
+
}
|
|
589
|
+
predicates[predicates.length] = above
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
addRelationTerms(context, grant, true, predicates, now)
|
|
593
|
+
addMemberTerms(context, grant, predicates, now)
|
|
594
|
+
return predicates.length === 0 ? undefined : conditioned(model, grant.action, anyOf(predicates), now)
|
|
428
595
|
}
|
|
429
596
|
|
|
430
597
|
/** The object a Ref of the model's own dimension names, with every link of its chain. */
|
|
@@ -440,23 +607,126 @@ export function selfLinks(model: TableModel): readonly Container[] {
|
|
|
440
607
|
return links
|
|
441
608
|
}
|
|
442
609
|
|
|
443
|
-
/** This object, over the whole chain the Ref carries. */
|
|
444
|
-
export function objectPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode {
|
|
610
|
+
/** This object, over the whole chain the Ref carries; through the secondary paths `paths` admits, by default its action's. */
|
|
611
|
+
export function objectPredicate(context: TableContext, capability: unknown, operation: Operation, paths?: PathRule): OperationNode {
|
|
445
612
|
const scope = dimensionScope(context.model)
|
|
446
613
|
const grant = refGrant(context, capability, scope.dimension, operation)
|
|
447
|
-
return
|
|
614
|
+
return refScope(context, context.model, selfLinks(context.model), grant, new Date(), undefined, paths ?? heldThrough(grant.action))
|
|
448
615
|
}
|
|
449
616
|
|
|
450
617
|
/** Rows of a dimension table within the scope values of its list dimension. */
|
|
451
618
|
export function dimensionListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
452
619
|
const scope = dimensionScope(context.model)
|
|
453
620
|
const grant = withinGrant(context, capability, listDimension(scope), operation)
|
|
454
|
-
return withinPredicate(context
|
|
621
|
+
return withinPredicate(context, scope.container?.column ?? scope.key, grant, operation)
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Rows of a child table that belong to the parent object the Ref names, over the whole chain; with `key`, the one row
|
|
626
|
+
* of them it keys. The key's equality joins the chain's, so the action's condition narrows both.
|
|
627
|
+
*/
|
|
628
|
+
export function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode {
|
|
629
|
+
const row = key === undefined ? undefined : equals(context.model.name, childScope(context).key, key)
|
|
630
|
+
const through = context.through
|
|
631
|
+
if (through !== undefined) {
|
|
632
|
+
const parent = through.context
|
|
633
|
+
const now = new Date()
|
|
634
|
+
const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
|
|
635
|
+
const reached = narrowed.length === 0
|
|
636
|
+
? refScope(parent, parent.model, selfLinks(parent.model), grant, now)
|
|
637
|
+
: splitRefReach(context.model, parent, grant, narrowed, now)
|
|
638
|
+
return viewScope(context.model, through, grant.action, reached, now, row)
|
|
639
|
+
}
|
|
640
|
+
return refScope(context, context.model, context.model.chain, grant, new Date(), row)
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/** Of `holds`, the relations a child view's `relationWhen` narrows for `action`: each reads the parent through a part of its own. */
|
|
644
|
+
function viewNarrowed(view: TableModel, holds: readonly RelationHold[], action: string): readonly string[] {
|
|
645
|
+
const narrowed: string[] = []
|
|
646
|
+
for (let index = 0; index < holds.length; index++) {
|
|
647
|
+
const relation = holds[index]?.relation ?? ''
|
|
648
|
+
if (relationCondition(view, relation, action) !== undefined && !includes(narrowed, relation)) narrowed[narrowed.length] = relation
|
|
649
|
+
}
|
|
650
|
+
return narrowed
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/**
|
|
654
|
+
* A Ref's reach of a view's parent, split by the relations the view narrows: the chain with the terms of its other
|
|
655
|
+
* relations, member reveals and paths, and the chain with each narrowed relation's own terms. A part that reaches no
|
|
656
|
+
* parent row adds nothing; none left is unenforceable, never unconditioned.
|
|
657
|
+
*/
|
|
658
|
+
function splitRefReach(view: TableModel, parent: TableContext, grant: RefGrant, narrowed: readonly string[], now: Date): SplitReach {
|
|
659
|
+
const model = parent.model
|
|
660
|
+
const chain = linksPredicate(model.name, linkValues(model.name, selfLinks(model), grant))
|
|
661
|
+
const paths = heldThrough(grant.action)
|
|
662
|
+
const others = holdsBesides(grant.relations, narrowed)
|
|
663
|
+
const rest: RefGrant = { ...grant, relations: others }
|
|
664
|
+
const restTerms = others.length === 0 && rest.revealing.length === 0 && rest.paths.length === 0 ? [] : gateTerms(parent, model, rest, now, paths)
|
|
665
|
+
const relations: { reached: OperationNode; condition: ConditionModel }[] = []
|
|
666
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
667
|
+
const hold = grant.relations[index]
|
|
668
|
+
const condition = hold === undefined || !includes(narrowed, hold.relation) ? undefined : relationCondition(view, hold.relation, grant.action)
|
|
669
|
+
const terms = hold === undefined || condition === undefined
|
|
670
|
+
? []
|
|
671
|
+
: relationTerms(parent.relations, model, hold, grant.principal, grant.action, now, paths)
|
|
672
|
+
if (condition !== undefined && terms.length > 0) relations[relations.length] = { reached: allOf([chain, anyOf(terms)]), condition }
|
|
673
|
+
}
|
|
674
|
+
if (restTerms.length === 0 && relations.length === 0) {
|
|
675
|
+
throw new CapabilityError(
|
|
676
|
+
'unenforceable',
|
|
677
|
+
`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}`,
|
|
678
|
+
)
|
|
679
|
+
}
|
|
680
|
+
return { rest: restTerms.length === 0 ? undefined : allOf([chain, anyOf(restTerms)]), relations }
|
|
455
681
|
}
|
|
456
682
|
|
|
457
|
-
/**
|
|
458
|
-
|
|
459
|
-
|
|
683
|
+
/**
|
|
684
|
+
* A child view's rows a `Within` reaches: those whose parent row `reach` admits over the parent's context; for `all`,
|
|
685
|
+
* those whose parent row exists. A relation the view narrows (`relationWhen`) reaches the parent through a part of its
|
|
686
|
+
* own, ANDed with the view's condition. The view's own access views list rows beside them. Undefined where nothing is
|
|
687
|
+
* reached: the empty `Within`.
|
|
688
|
+
*/
|
|
689
|
+
function throughParent(
|
|
690
|
+
context: TableContext,
|
|
691
|
+
through: ViewParent,
|
|
692
|
+
grant: WithinGrant,
|
|
693
|
+
reach: (parent: TableContext, grant: WithinGrant) => OperationNode | undefined,
|
|
694
|
+
): OperationNode | undefined {
|
|
695
|
+
const now = new Date()
|
|
696
|
+
if (grant.values === 'all') {
|
|
697
|
+
return viewScope(context.model, through, grant.action, 'all', now)
|
|
698
|
+
}
|
|
699
|
+
const own: OperationNode[] = []
|
|
700
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
701
|
+
const hold = grant.relations[index]
|
|
702
|
+
const terms = hold === undefined ? [] : accessReach(context.model, hold, grant.principal, grant.action, now)
|
|
703
|
+
for (let position = 0; position < terms.length; position++) {
|
|
704
|
+
const term = terms[position]
|
|
705
|
+
if (term !== undefined) own[own.length] = term
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
const narrowed = viewNarrowed(context.model, grant.relations, grant.action)
|
|
709
|
+
if (narrowed.length === 0) {
|
|
710
|
+
const reached = reach(through.context, grant)
|
|
711
|
+
return reached === undefined && own.length === 0 ? undefined : viewScope(context.model, through, grant.action, reached, now, undefined, own)
|
|
712
|
+
}
|
|
713
|
+
const rest = reach(through.context, { ...grant, relations: holdsBesides(grant.relations, narrowed) })
|
|
714
|
+
const relations: { reached: OperationNode; condition: ConditionModel }[] = []
|
|
715
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
716
|
+
const hold = grant.relations[index]
|
|
717
|
+
const condition = hold === undefined || !includes(narrowed, hold.relation)
|
|
718
|
+
? undefined
|
|
719
|
+
: relationCondition(context.model, hold.relation, grant.action)
|
|
720
|
+
const alone: WithinGrant | undefined = hold === undefined
|
|
721
|
+
? undefined
|
|
722
|
+
: { ...grant, values: [], containers: [], contained: [], revealing: [], relations: [hold] }
|
|
723
|
+
const reached = condition === undefined || alone === undefined ? undefined : reach(through.context, alone)
|
|
724
|
+
if (condition !== undefined && reached !== undefined) relations[relations.length] = { reached, condition }
|
|
725
|
+
}
|
|
726
|
+
if (rest === undefined && relations.length === 0 && own.length === 0) {
|
|
727
|
+
return undefined
|
|
728
|
+
}
|
|
729
|
+
return viewScope(context.model, through, grant.action, { rest, relations }, now, undefined, own)
|
|
460
730
|
}
|
|
461
731
|
|
|
462
732
|
export function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined {
|
|
@@ -470,29 +740,38 @@ export function childListPredicate(context: TableContext, capability: unknown, o
|
|
|
470
740
|
throw new CapabilityError('wrong_capability', `a list of ${context.model.name} by its parent needs a Ref or a Within, got ${describeGrant(grant)}`)
|
|
471
741
|
}
|
|
472
742
|
checkGrant(context, grant, listDimension(scope.parent), operation)
|
|
473
|
-
|
|
743
|
+
if (context.through !== undefined) {
|
|
744
|
+
const column = scope.parent.container?.column ?? scope.parent.key
|
|
745
|
+
return throughParent(context, context.through, grant, (parent, part) => withinPredicate(parent, column, part, operation))
|
|
746
|
+
}
|
|
747
|
+
return withinPredicate(context, scope.parent.container?.column ?? scope.column, grant, operation)
|
|
474
748
|
}
|
|
475
749
|
|
|
476
750
|
/**
|
|
477
|
-
*
|
|
478
|
-
*
|
|
751
|
+
* Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
|
|
752
|
+
* chain or a secondary path; a child view through its parent's.
|
|
479
753
|
*/
|
|
480
|
-
export function
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
754
|
+
export function reachedBy(context: TableContext, dimension: string): boolean {
|
|
755
|
+
const model = context.through?.context.model ?? context.model
|
|
756
|
+
return nodeColumnOf(model, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
|
|
760
|
+
export function secondaryPathsOf(model: TableModel, dimension: string): readonly SecondaryPath[] {
|
|
761
|
+
const paths: SecondaryPath[] = []
|
|
762
|
+
for (let index = 0; index < model.readThrough.length; index++) {
|
|
763
|
+
const path = model.readThrough[index]
|
|
764
|
+
if (path !== undefined && (path.dimension === dimension || linkOf(path.chain, dimension) !== undefined)) {
|
|
765
|
+
paths[paths.length] = path
|
|
488
766
|
}
|
|
489
767
|
}
|
|
490
|
-
return
|
|
768
|
+
return paths
|
|
491
769
|
}
|
|
492
770
|
|
|
493
771
|
/**
|
|
494
772
|
* Rows of a table a `Within` of any dimension of its chain lists, by the table's read action: tasks under a `Within` of
|
|
495
|
-
* `org` through their stamped `org_id`, as under one of `project` through `project_id
|
|
773
|
+
* `org` through their stamped `org_id`, as under one of `project` through `project_id`; a `Within` of a dimension the
|
|
774
|
+
* table reaches through a secondary path, through that path's column.
|
|
496
775
|
*/
|
|
497
776
|
export function reachPredicate(context: TableContext, capability: unknown): OperationNode | undefined {
|
|
498
777
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
@@ -501,14 +780,25 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
|
|
|
501
780
|
throw new CapabilityError('wrong_capability', `a list of ${table} needs a Within, got ${describeGrant(grant)}`)
|
|
502
781
|
}
|
|
503
782
|
checkAction(context, 'read', grant.action)
|
|
504
|
-
|
|
505
|
-
if (column === undefined) {
|
|
783
|
+
if (!reachedBy(context, grant.dimension)) {
|
|
506
784
|
throw new CapabilityError(
|
|
507
785
|
'out_of_reach',
|
|
508
|
-
`a Within of ${grant.dimension} does not reach ${table}: its containment chain
|
|
786
|
+
`a Within of ${grant.dimension} does not reach ${table}: neither its containment chain nor a secondary path holds ${grant.dimension}`,
|
|
509
787
|
)
|
|
510
788
|
}
|
|
511
|
-
|
|
789
|
+
if (context.through !== undefined) {
|
|
790
|
+
return throughParent(context, context.through, grant, withinReach)
|
|
791
|
+
}
|
|
792
|
+
return withinReach(context, grant)
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
/** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
|
|
796
|
+
function withinReach(context: TableContext, grant: WithinGrant): OperationNode | undefined {
|
|
797
|
+
const column = nodeColumnOf(context.model, grant.dimension)
|
|
798
|
+
if (column !== undefined) {
|
|
799
|
+
return withinPredicate(context, column, grant, 'read')
|
|
800
|
+
}
|
|
801
|
+
return secondaryPredicate(context, secondaryPathsOf(context.model, grant.dimension), grant)
|
|
512
802
|
}
|
|
513
803
|
|
|
514
804
|
/**
|
|
@@ -527,7 +817,8 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
|
|
|
527
817
|
throw new CapabilityError('table_kind', `a scoped site writes no application table: ${statement} needs the capability of an app endpoint`)
|
|
528
818
|
}
|
|
529
819
|
const actions = model.actions[use]
|
|
530
|
-
|
|
820
|
+
const held = grantActions(grant)
|
|
821
|
+
if (admitted(held, actions).length > 0) {
|
|
531
822
|
return
|
|
532
823
|
}
|
|
533
824
|
const columnWrites: string[] = []
|
|
@@ -539,11 +830,39 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
|
|
|
539
830
|
if (actions.length === 0 && columnWrites.length === 0) {
|
|
540
831
|
throw new CapabilityError('undeclared_operation', `${statement}: its policy declares no ${use} action`)
|
|
541
832
|
}
|
|
542
|
-
if (
|
|
833
|
+
if (admitted(held, columnWrites).length === 0) {
|
|
543
834
|
const needs = actions.length === 0 ? [] : [`its ${use} action ${actions.join(' or ')}`]
|
|
544
835
|
if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
|
|
545
|
-
throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${
|
|
836
|
+
throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${held.join(', ')}`)
|
|
837
|
+
}
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
/** The actions a grant holds: an `app` grant's (several for an `anyOf` endpoint), or any other grant's one. */
|
|
841
|
+
export function grantActions(grant: CapabilityGrant): readonly string[] {
|
|
842
|
+
return grant.kind === 'app' ? grant.actions : [grant.action]
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/** The actions of `held` that `allowed` lists: those that allow an operation, as any one of them does. */
|
|
846
|
+
function admitted(held: readonly string[], allowed: readonly string[]): string[] {
|
|
847
|
+
const found: string[] = []
|
|
848
|
+
for (let index = 0; index < held.length; index++) {
|
|
849
|
+
const action = held[index]
|
|
850
|
+
if (action !== undefined && includes(allowed, action)) {
|
|
851
|
+
found[found.length] = action
|
|
852
|
+
}
|
|
853
|
+
}
|
|
854
|
+
return found
|
|
855
|
+
}
|
|
856
|
+
|
|
857
|
+
/** The first of `actions` the table narrows with a `when`: a fragment, which renders column tests only, cannot hold it. */
|
|
858
|
+
function heldCondition(model: TableModel, actions: readonly string[]): string | undefined {
|
|
859
|
+
for (let index = 0; index < actions.length; index++) {
|
|
860
|
+
const action = actions[index]
|
|
861
|
+
if (action !== undefined && hasOwn(model.when, action)) {
|
|
862
|
+
return action
|
|
863
|
+
}
|
|
546
864
|
}
|
|
865
|
+
return undefined
|
|
547
866
|
}
|
|
548
867
|
|
|
549
868
|
/**
|
|
@@ -565,8 +884,29 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
|
|
|
565
884
|
if (use !== 'read') {
|
|
566
885
|
checkWriteTarget(context, grant, use)
|
|
567
886
|
}
|
|
887
|
+
// 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.
|
|
888
|
+
const held = grant.kind !== 'app'
|
|
889
|
+
&& (grant.relations.length > 0 || (grant.kind === 'ref' && (grant.revealing.length > 0 || grant.paths.length > 0)))
|
|
890
|
+
// An `'any'` read is unconditioned: a `when` keyed by the action narrows only its writes.
|
|
891
|
+
const readsEvery = grant.kind === 'app' && use === 'read' && readsAny(context, grant)
|
|
892
|
+
const conditionedBy = readsEvery ? undefined : heldCondition(model, grantActions(grant))
|
|
893
|
+
if (held || conditionedBy !== undefined) {
|
|
894
|
+
throw new CapabilityError(
|
|
895
|
+
'unenforceable',
|
|
896
|
+
`ctx.sql.scope cannot render a relation, a member reveal, a secondary path or a condition of ${
|
|
897
|
+
conditionedBy ?? grantActions(grant).join(', ')
|
|
898
|
+
} on ${model.name}: read it through ctx.db`,
|
|
899
|
+
)
|
|
900
|
+
}
|
|
901
|
+
// Nor the subquery through the parent row, which alone places a child view's rows.
|
|
902
|
+
if (grant.kind !== 'app' && context.through !== undefined) {
|
|
903
|
+
throw new CapabilityError(
|
|
904
|
+
'unenforceable',
|
|
905
|
+
`ctx.sql.scope cannot render the read of the view ${model.name} through its parent: read it through ctx.db`,
|
|
906
|
+
)
|
|
907
|
+
}
|
|
568
908
|
if (grant.kind === 'app') {
|
|
569
|
-
if (use === 'read') {
|
|
909
|
+
if (use === 'read' && !readsEvery) {
|
|
570
910
|
// The action is held as a global grant, so its scope is every row of a table it reaches.
|
|
571
911
|
checkAppReach(context, grant)
|
|
572
912
|
}
|
|
@@ -608,7 +948,7 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
|
|
|
608
948
|
}
|
|
609
949
|
return [tests]
|
|
610
950
|
}
|
|
611
|
-
const column =
|
|
951
|
+
const column = nodeColumnOf(model, grant.dimension)
|
|
612
952
|
if (column === undefined) {
|
|
613
953
|
throw new CapabilityError(
|
|
614
954
|
'out_of_reach',
|
|
@@ -690,32 +1030,63 @@ export function updatingRef(context: TableContext, capability: unknown, dimensio
|
|
|
690
1030
|
*/
|
|
691
1031
|
export type AppReach = 'rows' | 'counts'
|
|
692
1032
|
|
|
693
|
-
/**
|
|
694
|
-
|
|
1033
|
+
/**
|
|
1034
|
+
* The actions of an `app` capability that reach `reach` of a dimension or child table, at least one: its read action and
|
|
1035
|
+
* its `appRead`, and for `counts` its `appCount` too. Refuses a capability none of whose actions does.
|
|
1036
|
+
*/
|
|
1037
|
+
function recordReach(context: TableContext, grant: AppGrant, reach: AppReach): readonly string[] {
|
|
695
1038
|
const model = context.model
|
|
696
1039
|
const { appRead, appCount } = model.actions
|
|
697
1040
|
const read = model.actions.read.join(' or ')
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
) {
|
|
701
|
-
|
|
1041
|
+
const reaching = admitted(grant.actions, model.actions.read)
|
|
1042
|
+
const reads = admitted(grant.actions, appRead)
|
|
1043
|
+
for (let index = 0; index < reads.length; index++) {
|
|
1044
|
+
reaching[reaching.length] = reads[index] ?? ''
|
|
702
1045
|
}
|
|
703
|
-
|
|
1046
|
+
const counts = admitted(grant.actions, appCount)
|
|
1047
|
+
if (reach === 'counts') {
|
|
1048
|
+
for (let index = 0; index < counts.length; index++) {
|
|
1049
|
+
reaching[reaching.length] = counts[index] ?? ''
|
|
1050
|
+
}
|
|
1051
|
+
}
|
|
1052
|
+
if (reaching.length > 0) {
|
|
1053
|
+
return reaching
|
|
1054
|
+
}
|
|
1055
|
+
const held = grant.actions.join(', ')
|
|
1056
|
+
if (counts.length > 0) {
|
|
704
1057
|
throw new CapabilityError(
|
|
705
1058
|
'wrong_action',
|
|
706
|
-
`an app capability of ${
|
|
1059
|
+
`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}${
|
|
707
1060
|
appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
|
|
708
1061
|
}`,
|
|
709
1062
|
)
|
|
710
1063
|
}
|
|
711
1064
|
throw new CapabilityError(
|
|
712
1065
|
'wrong_action',
|
|
713
|
-
`an app capability of ${
|
|
1066
|
+
`an app capability of ${held} does not reach ${model.name}: ctx.db.app lists it for its read action ${read}${
|
|
714
1067
|
appRead.length === 0 ? '' : ` or one of its appRead (${appRead.join(', ')})`
|
|
715
1068
|
} only`,
|
|
716
1069
|
)
|
|
717
1070
|
}
|
|
718
1071
|
|
|
1072
|
+
/** The actions of an `app` capability the application table names; refuses a capability none of whose actions it names. */
|
|
1073
|
+
function namedActions(model: TableModel, grant: AppGrant): readonly string[] {
|
|
1074
|
+
const named: string[] = []
|
|
1075
|
+
for (let index = 0; index < grant.actions.length; index++) {
|
|
1076
|
+
const action = grant.actions[index]
|
|
1077
|
+
if (action !== undefined && namesAction(model, action)) {
|
|
1078
|
+
named[named.length] = action
|
|
1079
|
+
}
|
|
1080
|
+
}
|
|
1081
|
+
if (named.length === 0) {
|
|
1082
|
+
throw new CapabilityError(
|
|
1083
|
+
'wrong_action',
|
|
1084
|
+
`an app capability of ${grant.actions.join(', ')} does not reach ${model.name}: ${model.name} does not name the action`,
|
|
1085
|
+
)
|
|
1086
|
+
}
|
|
1087
|
+
return named
|
|
1088
|
+
}
|
|
1089
|
+
|
|
719
1090
|
/**
|
|
720
1091
|
* Refuses a table `ctx.db.app` does not list for the capability (`applicationTables` in `orm.ts`): it lists an
|
|
721
1092
|
* application table under any action the table names, and the rows of a dimension or child table under its read
|
|
@@ -725,12 +1096,7 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
|
|
|
725
1096
|
const model = context.model
|
|
726
1097
|
const mode = model.scope.mode
|
|
727
1098
|
if (mode === 'app') {
|
|
728
|
-
|
|
729
|
-
throw new CapabilityError(
|
|
730
|
-
'wrong_action',
|
|
731
|
-
`an app capability of ${grant.action} does not reach ${model.name}: ${model.name} does not name the action`,
|
|
732
|
-
)
|
|
733
|
-
}
|
|
1099
|
+
namedActions(model, grant)
|
|
734
1100
|
return
|
|
735
1101
|
}
|
|
736
1102
|
if (mode !== 'dimension' && mode !== 'child') {
|
|
@@ -739,14 +1105,20 @@ function checkAppReach(context: TableContext, grant: AppGrant): void {
|
|
|
739
1105
|
`an app capability does not reach ${model.name}: ctx.db.app lists application, dimension and child tables only`,
|
|
740
1106
|
)
|
|
741
1107
|
}
|
|
742
|
-
|
|
1108
|
+
recordReach(context, grant, 'rows')
|
|
1109
|
+
}
|
|
1110
|
+
|
|
1111
|
+
/** What an `app` capability reads of a table: the rows (`predicate`), and the reach whose columns it answers. */
|
|
1112
|
+
export interface AppRead {
|
|
1113
|
+
readonly predicate: OperationNode
|
|
1114
|
+
readonly reach: ReadReach
|
|
743
1115
|
}
|
|
744
1116
|
|
|
745
1117
|
/**
|
|
746
|
-
* Every row of a dimension or child table an `app` capability reads through `ctx.db.app
|
|
747
|
-
*
|
|
1118
|
+
* Every row of a dimension or child table an `app` capability reads through `ctx.db.app`, for its actions that reach
|
|
1119
|
+
* `reach` (`recordReach`): each row within the condition of one of them, and the columns they read alone.
|
|
748
1120
|
*/
|
|
749
|
-
export function
|
|
1121
|
+
export function appRecordRead(context: TableContext, capability: unknown, reach: AppReach): AppRead {
|
|
750
1122
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
751
1123
|
const model = context.model
|
|
752
1124
|
if (grant.kind !== 'app') {
|
|
@@ -758,8 +1130,13 @@ export function appRecordPredicate(context: TableContext, capability: unknown, r
|
|
|
758
1130
|
if (model.scope.mode !== 'dimension' && model.scope.mode !== 'child') {
|
|
759
1131
|
throw new CapabilityError('table_kind', `${model.name} is not a dimension or child table`)
|
|
760
1132
|
}
|
|
761
|
-
|
|
762
|
-
return
|
|
1133
|
+
const actions = recordReach(context, grant, reach)
|
|
1134
|
+
return { predicate: conditionedAny(model, actions, 'all', new Date()), reach: freeze({ actions, narrowed: true }) }
|
|
1135
|
+
}
|
|
1136
|
+
|
|
1137
|
+
/** `appRecordRead`'s rows. */
|
|
1138
|
+
export function appRecordPredicate(context: TableContext, capability: unknown, reach: AppReach): OperationNode {
|
|
1139
|
+
return appRecordRead(context, capability, reach).predicate
|
|
763
1140
|
}
|
|
764
1141
|
|
|
765
1142
|
/** An `app` capability addresses a row by its key, and writes, only in an application table. */
|
|
@@ -773,10 +1150,11 @@ function checkApplicationTable(context: TableContext, operation: Operation): voi
|
|
|
773
1150
|
}
|
|
774
1151
|
|
|
775
1152
|
/**
|
|
776
|
-
* The capability of an `app` endpoint for `operation` on `table
|
|
777
|
-
* is written with it, and a dimension or child
|
|
1153
|
+
* The capability of an `app` endpoint for `operation` on `table`, and its actions that are that operation's, at least
|
|
1154
|
+
* one. An application table is written with it, and a dimension or child
|
|
1155
|
+
* table read with it.
|
|
778
1156
|
*/
|
|
779
|
-
function appGrant(context: TableContext, capability: unknown, operation: Operation):
|
|
1157
|
+
function appGrant(context: TableContext, capability: unknown, operation: Operation): AppOperation {
|
|
780
1158
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
781
1159
|
const table = context.model.name
|
|
782
1160
|
if (grant.kind !== 'app') {
|
|
@@ -785,22 +1163,82 @@ function appGrant(context: TableContext, capability: unknown, operation: Operati
|
|
|
785
1163
|
if (operation !== 'read') {
|
|
786
1164
|
checkApplicationTable(context, operation)
|
|
787
1165
|
}
|
|
1166
|
+
if (operation === 'read' && readsAny(context, grant)) {
|
|
1167
|
+
return { grant, actions: grant.actions, narrowed: false }
|
|
1168
|
+
}
|
|
788
1169
|
checkAppReach(context, grant)
|
|
789
|
-
|
|
790
|
-
|
|
1170
|
+
return { grant, actions: operationActions(context, operation, grant), narrowed: true }
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
/**
|
|
1174
|
+
* An `app` capability and those of its actions that allow one operation: every one it holds for a read of a table read
|
|
1175
|
+
* with `'any'`, which no `when` narrows.
|
|
1176
|
+
*/
|
|
1177
|
+
interface AppOperation extends ReadReach {
|
|
1178
|
+
readonly grant: AppGrant
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
/** The actions of `grant` that allow `operation` on the table, at least one; `checkAction` over a set. */
|
|
1182
|
+
function operationActions(context: TableContext, operation: Operation, grant: AppGrant): readonly string[] {
|
|
1183
|
+
const actions = requiredActions(context, operation)
|
|
1184
|
+
const allowing = admitted(grant.actions, actions)
|
|
1185
|
+
if (allowing.length === 0) {
|
|
1186
|
+
throw new CapabilityError(
|
|
1187
|
+
'wrong_action',
|
|
1188
|
+
`${operation} on ${context.model.name} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`,
|
|
1189
|
+
)
|
|
1190
|
+
}
|
|
1191
|
+
return allowing
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
/**
|
|
1195
|
+
* Whether `grant` reads `context`'s table because it is read with `'any'`: every `app` grant but a public procedure's,
|
|
1196
|
+
* which is refused there. The read is unconditioned: a `when` of the grant's action narrows only its writes.
|
|
1197
|
+
*/
|
|
1198
|
+
function readsAny(context: TableContext, grant: AppGrant): boolean {
|
|
1199
|
+
const model = context.model
|
|
1200
|
+
if (model.scope.mode !== 'app' || !model.actions.readAny) {
|
|
1201
|
+
return false
|
|
1202
|
+
}
|
|
1203
|
+
if (grant.public) {
|
|
1204
|
+
throw new CapabilityError(
|
|
1205
|
+
'wrong_capability',
|
|
1206
|
+
`a public procedure does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
|
|
1207
|
+
)
|
|
1208
|
+
}
|
|
1209
|
+
return true
|
|
1210
|
+
}
|
|
1211
|
+
|
|
1212
|
+
/**
|
|
1213
|
+
* The rows `held`, the read actions of an `app` capability, read of `context`'s table within `branch`: narrowed by their
|
|
1214
|
+
* conditions, any one admitting a row, unless the table is read with `'any'`.
|
|
1215
|
+
*/
|
|
1216
|
+
function appReadPredicate(context: TableContext, held: AppOperation, branch: OperationNode | 'all'): OperationNode {
|
|
1217
|
+
if (context.model.scope.mode === 'app' && context.model.actions.readAny) {
|
|
1218
|
+
return branch === 'all' ? ValueNode.createImmediate(true) : branch
|
|
1219
|
+
}
|
|
1220
|
+
return conditionedAny(context.model, held.actions, branch, new Date())
|
|
1221
|
+
}
|
|
1222
|
+
|
|
1223
|
+
/**
|
|
1224
|
+
* Every row a capability of an `app` endpoint reads in an application table, by the table's read actions it holds or
|
|
1225
|
+
* `'any'`, and the reach whose columns it answers.
|
|
1226
|
+
*/
|
|
1227
|
+
export function appListRead(context: TableContext, capability: unknown): AppRead {
|
|
1228
|
+
const held = appGrant(context, capability, 'read')
|
|
1229
|
+
return { predicate: appReadPredicate(context, held, 'all'), reach: freeze({ actions: held.actions, narrowed: held.narrowed }) }
|
|
791
1230
|
}
|
|
792
1231
|
|
|
793
|
-
/**
|
|
1232
|
+
/** `appListRead`'s rows. */
|
|
794
1233
|
export function appListPredicate(context: TableContext, capability: unknown): OperationNode {
|
|
795
|
-
|
|
796
|
-
return everything()
|
|
1234
|
+
return appListRead(context, capability).predicate
|
|
797
1235
|
}
|
|
798
1236
|
|
|
799
1237
|
/**
|
|
800
1238
|
* Every row of an application table, for a `Ref` or a `Within` of its read action: what `ctx.db.app` of an `on`, `in`
|
|
801
1239
|
* or `over` endpoint reads, read-only, as a reference table is read. The table's read action decides who reads it.
|
|
802
1240
|
*/
|
|
803
|
-
export function scopedApplicationRead(context: TableContext, capability: unknown): OperationNode {
|
|
1241
|
+
export function scopedApplicationRead(context: TableContext, capability: unknown, branch: OperationNode | 'all' = 'all'): OperationNode {
|
|
804
1242
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
805
1243
|
const model = context.model
|
|
806
1244
|
if (model.scope.mode !== 'app') {
|
|
@@ -809,6 +1247,12 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
|
|
|
809
1247
|
if (grant.kind === 'app') {
|
|
810
1248
|
throw new CapabilityError('wrong_capability', `a read of ${model.name} from a scoped site needs a Ref or a Within, got ${describeGrant(grant)}`)
|
|
811
1249
|
}
|
|
1250
|
+
if (model.actions.readAny) {
|
|
1251
|
+
throw new CapabilityError(
|
|
1252
|
+
'wrong_capability',
|
|
1253
|
+
`a scoped site does not read ${model.name}: it is read with 'any', which an app endpoint, a job and a webhook hold`,
|
|
1254
|
+
)
|
|
1255
|
+
}
|
|
812
1256
|
const read = requiredActions(context, 'read')
|
|
813
1257
|
if (!includes(read, grant.action)) {
|
|
814
1258
|
throw new CapabilityError(
|
|
@@ -816,14 +1260,15 @@ export function scopedApplicationRead(context: TableContext, capability: unknown
|
|
|
816
1260
|
`a scoped site reads ${model.name} with its read action ${read.join(' or ')} only; the capability holds ${grant.action}`,
|
|
817
1261
|
)
|
|
818
1262
|
}
|
|
819
|
-
return
|
|
1263
|
+
return conditioned(model, grant.action, branch, new Date())
|
|
820
1264
|
}
|
|
821
1265
|
|
|
822
1266
|
/** One row of an application table by its key, for an `app` capability of `operation`'s action. */
|
|
823
1267
|
export function appRowPredicate(context: TableContext, capability: unknown, key: unknown, operation: Operation): OperationNode {
|
|
824
1268
|
checkApplicationTable(context, operation)
|
|
825
|
-
appGrant(context, capability, operation)
|
|
826
|
-
|
|
1269
|
+
const held = appGrant(context, capability, operation)
|
|
1270
|
+
const row = appKeyPredicate(context.model, key)
|
|
1271
|
+
return operation === 'read' ? appReadPredicate(context, held, row) : conditionedAny(context.model, held.actions, row, new Date())
|
|
827
1272
|
}
|
|
828
1273
|
|
|
829
1274
|
/**
|
|
@@ -833,14 +1278,20 @@ export function appRowPredicate(context: TableContext, capability: unknown, key:
|
|
|
833
1278
|
export function claimScope(
|
|
834
1279
|
context: TableContext,
|
|
835
1280
|
capability: unknown,
|
|
836
|
-
): { readonly grant: AppGrant | WithinGrant; readonly scope: OperationNode | undefined } {
|
|
1281
|
+
): { readonly grant: AppGrant | WithinGrant; readonly action: string; readonly scope: OperationNode | undefined } {
|
|
837
1282
|
const model = context.model
|
|
838
1283
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
839
1284
|
if (model.queue === undefined) {
|
|
840
1285
|
throw new CapabilityError('undeclared_operation', `${model.name} is not a queue table: its policy declares no queue`)
|
|
841
1286
|
}
|
|
842
1287
|
if (grant.kind === 'app') {
|
|
843
|
-
|
|
1288
|
+
const [action, ...more] = grant.actions
|
|
1289
|
+
// A claimed row's `row.ref` is finished under one action; only a job claims, and its `ctx.app(action)` holds one.
|
|
1290
|
+
if (more.length > 0) {
|
|
1291
|
+
throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a capability of one action, got one of ${grant.actions.join(', ')}`)
|
|
1292
|
+
}
|
|
1293
|
+
appGrant(context, capability, 'update')
|
|
1294
|
+
return { grant, action, scope: conditioned(model, action, 'all', new Date()) }
|
|
844
1295
|
}
|
|
845
1296
|
if (grant.kind !== 'within') {
|
|
846
1297
|
throw new CapabilityError('wrong_capability', `a claim of ${model.name} needs a Within or an app capability, got ${describeGrant(grant)}`)
|
|
@@ -849,14 +1300,14 @@ export function claimScope(
|
|
|
849
1300
|
throw new CapabilityError('table_kind', `${model.name} is an application table: claim it through ctx.db.app`)
|
|
850
1301
|
}
|
|
851
1302
|
checkAction(context, 'update', grant.action)
|
|
852
|
-
const column =
|
|
1303
|
+
const column = nodeColumnOf(model, grant.dimension)
|
|
853
1304
|
if (column === undefined) {
|
|
854
1305
|
throw new CapabilityError(
|
|
855
1306
|
'out_of_reach',
|
|
856
1307
|
`a Within of ${grant.dimension} does not reach ${model.name}: its containment chain does not hold ${grant.dimension}`,
|
|
857
1308
|
)
|
|
858
1309
|
}
|
|
859
|
-
return { grant, scope: withinPredicate(
|
|
1310
|
+
return { grant, action: grant.action, scope: withinPredicate(context, column, grant, 'update') }
|
|
860
1311
|
}
|
|
861
1312
|
|
|
862
1313
|
/**
|
|
@@ -879,7 +1330,17 @@ export function claimedRowPredicate(context: TableContext, capability: unknown,
|
|
|
879
1330
|
}
|
|
880
1331
|
terms[terms.length] = equals(model.name, link.column, value)
|
|
881
1332
|
}
|
|
882
|
-
return allOf(terms)
|
|
1333
|
+
return conditioned(model, grant.action, allOf(terms), new Date())
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
/** The row of an application table `key` names, as `actions` reach it: within their conditions, any one admitting it. */
|
|
1337
|
+
export function appKeyScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
|
|
1338
|
+
return conditionedAny(model, actions, appKeyPredicate(model, key), new Date())
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
/** The row `key` names, as a read by key with `actions` reaches it: unconditioned in a table read with `'any'`. */
|
|
1342
|
+
export function appGetScope(model: TableModel, actions: readonly string[], key: unknown): OperationNode {
|
|
1343
|
+
return model.actions.readAny ? appKeyPredicate(model, key) : appKeyScope(model, actions, key)
|
|
883
1344
|
}
|
|
884
1345
|
|
|
885
1346
|
/** The row of an application table `key` names. */
|
|
@@ -891,10 +1352,10 @@ export function appKeyPredicate(model: TableModel, key: unknown): OperationNode
|
|
|
891
1352
|
}
|
|
892
1353
|
|
|
893
1354
|
/**
|
|
894
|
-
* The
|
|
895
|
-
* column's own write action. Which columns
|
|
1355
|
+
* The actions of an `app` endpoint's capability that update columns of an application table, at least one: its update
|
|
1356
|
+
* action, or a column's own write action. Which columns they update follows from them (`updatableByAny`).
|
|
896
1357
|
*/
|
|
897
|
-
export function updatingApp(context: TableContext, capability: unknown):
|
|
1358
|
+
export function updatingApp(context: TableContext, capability: unknown): readonly string[] {
|
|
898
1359
|
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
899
1360
|
const table = context.model.name
|
|
900
1361
|
if (grant.kind !== 'app') {
|
|
@@ -905,12 +1366,63 @@ export function updatingApp(context: TableContext, capability: unknown): AppGran
|
|
|
905
1366
|
if (actions.length === 0) {
|
|
906
1367
|
throw new CapabilityError('undeclared_operation', `${table} allows no update; its policy declares no update action`)
|
|
907
1368
|
}
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
1369
|
+
const updating = admitted(grant.actions, actions)
|
|
1370
|
+
if (updating.length === 0) {
|
|
1371
|
+
throw new CapabilityError('wrong_action', `update on ${table} requires ${actions.join(' or ')}; the capability holds ${grant.actions.join(', ')}`)
|
|
1372
|
+
}
|
|
1373
|
+
return updating
|
|
1374
|
+
}
|
|
1375
|
+
|
|
1376
|
+
/**
|
|
1377
|
+
* An `app` capability's update of the application table row `key`: `values`, read against the columns its update
|
|
1378
|
+
* actions write, and the row's scope under only those actions that write every given column, any one's condition
|
|
1379
|
+
* admitting the row. So several held actions never write one action's columns on rows only another one reaches.
|
|
1380
|
+
*/
|
|
1381
|
+
export function appUpdate(
|
|
1382
|
+
context: TableContext,
|
|
1383
|
+
capability: unknown,
|
|
1384
|
+
key: unknown,
|
|
1385
|
+
values: unknown,
|
|
1386
|
+
): { readonly scope: OperationNode; readonly changes: Map<string, Primitive | null> } {
|
|
1387
|
+
const model = context.model
|
|
1388
|
+
const updating = updatingApp(context, capability)
|
|
1389
|
+
const writable = updatableByAny(model, updating)
|
|
1390
|
+
const changes = readValues(values, writable, 'update', model)
|
|
1391
|
+
// `readValues` took only columns of `writable`, so those of them `changes` sets are every column it sets.
|
|
1392
|
+
const columns = namesOf(writable)
|
|
1393
|
+
const written: string[] = []
|
|
1394
|
+
for (let index = 0; index < columns.length; index++) {
|
|
1395
|
+
const name = columns[index] ?? ''
|
|
1396
|
+
if (changes.has(name)) {
|
|
1397
|
+
written[written.length] = name
|
|
911
1398
|
}
|
|
912
1399
|
}
|
|
913
|
-
|
|
1400
|
+
const covering: string[] = []
|
|
1401
|
+
for (let index = 0; index < updating.length; index++) {
|
|
1402
|
+
const action = updating[index]
|
|
1403
|
+
if (action !== undefined && writesEvery(updatableBy(model, action), written)) {
|
|
1404
|
+
covering[covering.length] = action
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
if (covering.length === 0) {
|
|
1408
|
+
throw new CapabilityError(
|
|
1409
|
+
'wrong_action',
|
|
1410
|
+
`no action of ${updating.join(', ')} updates every column of this update of ${model.name} (${
|
|
1411
|
+
written.join(', ')
|
|
1412
|
+
}): update the columns of each action apart`,
|
|
1413
|
+
)
|
|
1414
|
+
}
|
|
1415
|
+
return { scope: appKeyScope(model, covering, key), changes }
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
/** Whether `columns` holds each of `written`. */
|
|
1419
|
+
function writesEvery(columns: NameSet, written: readonly string[]): boolean {
|
|
1420
|
+
for (let index = 0; index < written.length; index++) {
|
|
1421
|
+
if (!inSet(columns, written[index])) {
|
|
1422
|
+
return false
|
|
1423
|
+
}
|
|
1424
|
+
}
|
|
1425
|
+
return true
|
|
914
1426
|
}
|
|
915
1427
|
|
|
916
1428
|
export function childObjectPredicate(context: TableContext, parent: unknown, key: unknown, operation: Operation): OperationNode {
|
|
@@ -919,11 +1431,22 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
|
|
|
919
1431
|
throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its parent Ref and its ${scope.key}`)
|
|
920
1432
|
}
|
|
921
1433
|
const grant = refGrant(context, parent, scope.parent.dimension, operation)
|
|
922
|
-
return
|
|
1434
|
+
return parentPredicate(context, grant, key)
|
|
923
1435
|
}
|
|
924
1436
|
|
|
925
1437
|
export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
|
|
926
|
-
|
|
1438
|
+
// Every store write reaches its statement through here: a view's rows are its tables', never written (ADR-0072).
|
|
1439
|
+
if (context.model.view && root !== 'SelectQueryNode') {
|
|
1440
|
+
throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
|
|
1441
|
+
}
|
|
1442
|
+
return {
|
|
1443
|
+
root,
|
|
1444
|
+
table: context.model.name,
|
|
1445
|
+
joins: root === 'SelectQueryNode' ? context.joins : {},
|
|
1446
|
+
scope,
|
|
1447
|
+
subqueries: context.subqueries,
|
|
1448
|
+
through: context.through,
|
|
1449
|
+
}
|
|
927
1450
|
}
|
|
928
1451
|
|
|
929
1452
|
/**
|
|
@@ -949,9 +1472,29 @@ export function fencedWork<T>(runtime: DataLayerRuntime, work: (transaction: Ses
|
|
|
949
1472
|
return fence === null ? session.transaction(work) : fencedTransaction(session, fence, work)
|
|
950
1473
|
}
|
|
951
1474
|
|
|
952
|
-
/**
|
|
1475
|
+
/**
|
|
1476
|
+
* The one action a capability holds, which its operation's checks already admitted. An `anyOf` endpoint's `app`
|
|
1477
|
+
* capability that holds several is refused: it reads through `ctx.db.app`, which reads with every action it holds.
|
|
1478
|
+
*/
|
|
953
1479
|
export function heldAction(context: TableContext, capability: unknown): string {
|
|
954
|
-
|
|
1480
|
+
const grant = runtimeOf(context.connection).capabilities.resolve(capability)
|
|
1481
|
+
if (grant.kind !== 'app') {
|
|
1482
|
+
return grant.action
|
|
1483
|
+
}
|
|
1484
|
+
const [action, ...more] = grant.actions
|
|
1485
|
+
if (more.length > 0) {
|
|
1486
|
+
throw new CapabilityError(
|
|
1487
|
+
'wrong_capability',
|
|
1488
|
+
`this read takes a capability of one action, got one of ${grant.actions.join(', ')}: read through ctx.db.app`,
|
|
1489
|
+
)
|
|
1490
|
+
}
|
|
1491
|
+
return action
|
|
1492
|
+
}
|
|
1493
|
+
|
|
1494
|
+
/** The one action a capability holds, or `undefined` for an `anyOf` endpoint's `app` capability that holds several. */
|
|
1495
|
+
function soleAction(context: TableContext, capability: unknown): string | undefined {
|
|
1496
|
+
const actions = grantActions(runtimeOf(context.connection).capabilities.resolve(capability))
|
|
1497
|
+
return actions.length === 1 ? actions[0] : undefined
|
|
955
1498
|
}
|
|
956
1499
|
|
|
957
1500
|
function storeRunner(context: TableContext): Runner {
|
|
@@ -1003,6 +1546,10 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
|
|
|
1003
1546
|
copied.set(key, fileValue(model, key, value))
|
|
1004
1547
|
continue
|
|
1005
1548
|
}
|
|
1549
|
+
if (inSet(model.json, key)) {
|
|
1550
|
+
copied.set(key, value === null ? null : jsonInput(value, `${table}.${key}`))
|
|
1551
|
+
continue
|
|
1552
|
+
}
|
|
1006
1553
|
if (value !== null && !isPrimitive(value)) {
|
|
1007
1554
|
throw new QueryRefusedError('invalid_argument', `${table}.${key} takes a plain value (string, number, bigint, boolean, Date or null)`)
|
|
1008
1555
|
}
|
|
@@ -1052,28 +1599,61 @@ async function selectRows<S>(
|
|
|
1052
1599
|
context: TableContext,
|
|
1053
1600
|
scope: OperationNode | undefined,
|
|
1054
1601
|
state: SelectState,
|
|
1055
|
-
action: string,
|
|
1602
|
+
action: string | undefined,
|
|
1056
1603
|
visible: readonly string[] = context.model.visible,
|
|
1057
1604
|
): Promise<S[]> {
|
|
1058
1605
|
const run = storeRunner(context)
|
|
1606
|
+
const now = new Date()
|
|
1607
|
+
const joins: JoinState[] = []
|
|
1059
1608
|
for (let index = 0; index < state.joins.length; index++) {
|
|
1060
1609
|
const join = state.joins[index]
|
|
1061
|
-
if (join
|
|
1610
|
+
if (join === undefined) continue
|
|
1611
|
+
if (action === undefined) {
|
|
1612
|
+
throw new CapabilityError('wrong_capability', `joining ${join.join.shape.table} takes a capability of one action, whose condition narrows it`)
|
|
1613
|
+
}
|
|
1614
|
+
if (!includes(join.join.readActions, action)) {
|
|
1062
1615
|
throw new CapabilityError(
|
|
1063
1616
|
'wrong_action',
|
|
1064
1617
|
`joining ${join.join.shape.table} requires ${join.join.readActions.join(' or ')}; the capability holds ${action}`,
|
|
1065
1618
|
)
|
|
1066
1619
|
}
|
|
1620
|
+
joins[joins.length] = heldJoin(context, join, action, now)
|
|
1067
1621
|
}
|
|
1068
1622
|
if (scope === undefined) {
|
|
1069
1623
|
return []
|
|
1070
1624
|
}
|
|
1071
1625
|
const dialect = dialectOf(context)
|
|
1072
|
-
const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
|
|
1626
|
+
const node = selectNode(boundState(context, { ...state, joins }), visible, scope, undefined, context.model.dates, dialect)
|
|
1073
1627
|
const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
|
|
1074
1628
|
return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
|
|
1075
1629
|
}
|
|
1076
1630
|
|
|
1631
|
+
/**
|
|
1632
|
+
* `join` narrowed by the child's condition of `action`, as a read of the child narrows its rows. The guard admits no
|
|
1633
|
+
* subquery in an ON, so a condition that reads other rows (a path, `some`, `none`) refuses the join.
|
|
1634
|
+
*/
|
|
1635
|
+
function heldJoin(context: TableContext, join: JoinState, action: string, now: Date): JoinState {
|
|
1636
|
+
const child = ownEntry(context.children, join.join.shape.table)
|
|
1637
|
+
if (child === undefined) {
|
|
1638
|
+
throw new QueryRefusedError('unknown_table', `${join.join.shape.table} is not a joinable child of ${context.model.name}`)
|
|
1639
|
+
}
|
|
1640
|
+
const condition = ownEntry(child.when, action)
|
|
1641
|
+
if (condition === undefined) {
|
|
1642
|
+
return join
|
|
1643
|
+
}
|
|
1644
|
+
let reads = false
|
|
1645
|
+
conditionReach(condition, () => {
|
|
1646
|
+
reads = true
|
|
1647
|
+
})
|
|
1648
|
+
if (reads) {
|
|
1649
|
+
throw new CapabilityError(
|
|
1650
|
+
'unenforceable',
|
|
1651
|
+
`joining ${child.name} cannot hold its condition of ${action}, which reads other rows; read ${child.name} through its own handle`,
|
|
1652
|
+
)
|
|
1653
|
+
}
|
|
1654
|
+
return { ...join, condition: conditionNode(child.name, condition, now) }
|
|
1655
|
+
}
|
|
1656
|
+
|
|
1077
1657
|
/** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
|
|
1078
1658
|
function joinedColumns(context: TableContext, state: SelectState): RowColumns {
|
|
1079
1659
|
const own = rowColumnsOf(context.model)
|
|
@@ -1100,19 +1680,20 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
|
|
|
1100
1680
|
days: joined((columns) => columns.days),
|
|
1101
1681
|
timestamps: joined((columns) => columns.timestamps),
|
|
1102
1682
|
booleans: joined((columns) => columns.booleans),
|
|
1683
|
+
json: joined((columns) => columns.json),
|
|
1103
1684
|
}
|
|
1104
1685
|
}
|
|
1105
1686
|
|
|
1106
1687
|
/**
|
|
1107
1688
|
* One row by its scope predicate, with `visible` columns (the table's read action's, unless a capability reads its own).
|
|
1108
|
-
* `
|
|
1689
|
+
* `reach` is what read it: each file column then answers a reference that reads the file only under a read action.
|
|
1109
1690
|
*/
|
|
1110
1691
|
export async function selectOne<O>(
|
|
1111
1692
|
context: TableContext,
|
|
1112
1693
|
run: Runner,
|
|
1113
1694
|
scope: OperationNode,
|
|
1114
1695
|
visible = context.model.visible,
|
|
1115
|
-
|
|
1696
|
+
reach?: ReadReach,
|
|
1116
1697
|
): Promise<O> {
|
|
1117
1698
|
const start = startSelect(context.shape)
|
|
1118
1699
|
const state = finishSelect(start, start)
|
|
@@ -1124,8 +1705,8 @@ export async function selectOne<O>(
|
|
|
1124
1705
|
if (row === undefined) {
|
|
1125
1706
|
throw new NotFoundError(`${context.model.name} not found`)
|
|
1126
1707
|
}
|
|
1127
|
-
if (
|
|
1128
|
-
await answerFiles(context.model, run.files, session, [row],
|
|
1708
|
+
if (reach !== undefined) {
|
|
1709
|
+
await answerFiles(context.model, run.files, session, [row], reach)
|
|
1129
1710
|
}
|
|
1130
1711
|
return row
|
|
1131
1712
|
}
|
|
@@ -1195,29 +1776,55 @@ export function keyOf(model: TableModel): string {
|
|
|
1195
1776
|
* Locks the destination row `for share` and checks that it still lies where the Ref's chain says. Without it, a
|
|
1196
1777
|
* Ref minted before its object moved would insert into, or move rows into, the object's new container.
|
|
1197
1778
|
*/
|
|
1198
|
-
async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant): Promise<void> {
|
|
1779
|
+
async function lockDestination(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<void> {
|
|
1780
|
+
if (!(await destinationHeld(transaction, context, grant, paths))) {
|
|
1781
|
+
throw context.destination === undefined
|
|
1782
|
+
? new NotFoundError(`no row holds ${grant.action} for the Ref's principal at ${grant.dimension} ${grant.id} any more; obtain a fresh Ref`)
|
|
1783
|
+
: new NotFoundError(`${context.destination.name} ${grant.id} is not where its Ref says; obtain a fresh Ref`)
|
|
1784
|
+
}
|
|
1785
|
+
}
|
|
1786
|
+
|
|
1787
|
+
/** Whether the destination still lies where `grant`'s chain says and still holds it, locked `for share` (`lockDestination`). */
|
|
1788
|
+
async function destinationHeld(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
|
|
1199
1789
|
const owner = context.destination
|
|
1200
1790
|
if (owner === undefined) {
|
|
1201
|
-
|
|
1791
|
+
// No table owns the destination, so a Ref held through relations or member reveals is checked on the rows that hold it.
|
|
1792
|
+
return grant.relations.length === 0 && grant.revealing.length === 0 ? true : await holdingRowLocked(transaction, context, grant)
|
|
1202
1793
|
}
|
|
1203
|
-
const
|
|
1794
|
+
const chain = linksPredicate(owner.name, linkValues(owner.name, selfLinks(owner), grant))
|
|
1795
|
+
// A Ref held through a relation or a member reveal inserts only while a row of it still holds the destination.
|
|
1796
|
+
const gate = relationGate(context, owner, grant, new Date(), paths ?? heldThrough(grant.action))
|
|
1797
|
+
const scope = gate === undefined ? chain : allOf([chain, gate])
|
|
1204
1798
|
const node = lockNode(owner.name, keyOf(owner), scope)
|
|
1205
|
-
const rows = await transaction.run(node, {
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1799
|
+
const rows = await transaction.run(node, {
|
|
1800
|
+
root: 'SelectQueryNode',
|
|
1801
|
+
table: owner.name,
|
|
1802
|
+
joins: {},
|
|
1803
|
+
scope,
|
|
1804
|
+
lock: 'share',
|
|
1805
|
+
subqueries: context.subqueries,
|
|
1806
|
+
})
|
|
1807
|
+
return rows.length > 0
|
|
1209
1808
|
}
|
|
1210
1809
|
|
|
1810
|
+
/** An insert, in a transaction that first locks its destination and judges its writer's bounds and its condition. */
|
|
1211
1811
|
export async function insertRow<O>(
|
|
1212
1812
|
context: TableContext,
|
|
1213
1813
|
run: Runner,
|
|
1214
1814
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1215
|
-
|
|
1815
|
+
prepared: Pick<PreparedInsert, 'destination' | 'writer' | 'judged' | 'narrowed'> | undefined,
|
|
1216
1816
|
): Promise<O> {
|
|
1217
1817
|
const values = boundValues(context, given)
|
|
1218
1818
|
return run.write(async (transaction) => {
|
|
1219
|
-
if (destination !== undefined) {
|
|
1220
|
-
await lockDestination(transaction, context, destination)
|
|
1819
|
+
if (prepared?.destination !== undefined) {
|
|
1820
|
+
await lockDestination(transaction, context, prepared.destination)
|
|
1821
|
+
}
|
|
1822
|
+
const before = await narrowedHolds(transaction, context, prepared)
|
|
1823
|
+
if (prepared !== undefined) {
|
|
1824
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, given)
|
|
1825
|
+
await checkRevealAssign(transaction, context, prepared.writer, given)
|
|
1826
|
+
await checkMemberRevealAssign(transaction, context, prepared.writer, given)
|
|
1827
|
+
await checkPathWriters(transaction, context, prepared.writer, given)
|
|
1221
1828
|
}
|
|
1222
1829
|
const [row] = await transaction.run<O>(insertNode(context.model.name, values, answer(context)), guard(context, 'InsertQueryNode', undefined))
|
|
1223
1830
|
if (row === undefined) {
|
|
@@ -1225,6 +1832,8 @@ export async function insertRow<O>(
|
|
|
1225
1832
|
}
|
|
1226
1833
|
checkVersion(context, row)
|
|
1227
1834
|
await referenceInserted(context, run, transaction, values)
|
|
1835
|
+
await judgeInserted(transaction, context, prepared?.judged, values.get(keyOf(context.model)))
|
|
1836
|
+
await judgeNarrowed(transaction, context, prepared, before, values.get(keyOf(context.model)))
|
|
1228
1837
|
return row
|
|
1229
1838
|
})
|
|
1230
1839
|
}
|
|
@@ -1238,18 +1847,20 @@ export interface OnConflict {
|
|
|
1238
1847
|
readonly mode: 'nothing' | 'update'
|
|
1239
1848
|
/** The values given for the table's update columns: what `update` sets on the conflicting row. */
|
|
1240
1849
|
readonly updates: ReadonlyMap<string, Primitive | null>
|
|
1850
|
+
/** The capability's update actions, one of whose conditions the conflicting row must satisfy to be updated. */
|
|
1851
|
+
readonly actions: readonly string[]
|
|
1241
1852
|
}
|
|
1242
1853
|
|
|
1243
1854
|
const CONFLICT_FIELDS = nameSet(['columns', 'do'])
|
|
1244
1855
|
|
|
1245
1856
|
/**
|
|
1246
1857
|
* The `onConflict` of an insert's options, read through own data properties; `undefined` without options. `'update'`
|
|
1247
|
-
* also needs the capability's
|
|
1858
|
+
* also needs one of the capability's `actions` to be one of the table's update actions.
|
|
1248
1859
|
*/
|
|
1249
1860
|
export function onConflictOf(
|
|
1250
1861
|
context: TableContext,
|
|
1251
1862
|
options: unknown,
|
|
1252
|
-
|
|
1863
|
+
actions: readonly string[],
|
|
1253
1864
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1254
1865
|
): OnConflict | undefined {
|
|
1255
1866
|
if (options === undefined) {
|
|
@@ -1266,6 +1877,10 @@ export function onConflictOf(
|
|
|
1266
1877
|
if (!inSet(model.columns, name)) {
|
|
1267
1878
|
throw new QueryRefusedError('on_conflict', `onConflict names ${String(name)}, which is not a column of ${model.name}`)
|
|
1268
1879
|
}
|
|
1880
|
+
if (inSet(model.json, name)) {
|
|
1881
|
+
// jsonb compares by value and SQLite's text by spelling: the two dialects would disagree about a conflict.
|
|
1882
|
+
throw new QueryRefusedError('on_conflict', `onConflict names ${name}, a JSON column of ${model.name}, which the data layer never compares`)
|
|
1883
|
+
}
|
|
1269
1884
|
return name
|
|
1270
1885
|
})
|
|
1271
1886
|
if (columns === undefined || columns.length === 0) {
|
|
@@ -1276,13 +1891,14 @@ export function onConflictOf(
|
|
|
1276
1891
|
throw new QueryRefusedError('on_conflict', "onConflict.do takes 'nothing' or 'update'")
|
|
1277
1892
|
}
|
|
1278
1893
|
const updates = new Map<string, Primitive | null>()
|
|
1894
|
+
const updating = admitted(actions, model.actions.update)
|
|
1279
1895
|
if (mode === 'update') {
|
|
1280
|
-
if (
|
|
1896
|
+
if (updating.length === 0) {
|
|
1281
1897
|
throw new CapabilityError(
|
|
1282
1898
|
'wrong_action',
|
|
1283
1899
|
`an insert of ${model.name} that updates on a conflict also needs its update action ${
|
|
1284
1900
|
model.actions.update.join(' or ') || '(none)'
|
|
1285
|
-
}; the capability holds ${
|
|
1901
|
+
}; the capability holds ${actions.join(', ')}`,
|
|
1286
1902
|
)
|
|
1287
1903
|
}
|
|
1288
1904
|
const columns = namesOf(model.update)
|
|
@@ -1294,7 +1910,7 @@ export function onConflictOf(
|
|
|
1294
1910
|
}
|
|
1295
1911
|
}
|
|
1296
1912
|
}
|
|
1297
|
-
return freeze({ columns: freeze(columns), mode, updates })
|
|
1913
|
+
return freeze({ columns: freeze(columns), mode, updates, actions: freeze(updating) })
|
|
1298
1914
|
}
|
|
1299
1915
|
|
|
1300
1916
|
/** A plain object's own data properties, each one of `allowed`; the options of an insert or its `onConflict`. */
|
|
@@ -1349,8 +1965,8 @@ function insertedScope(context: TableContext, values: ReadonlyMap<string, Primit
|
|
|
1349
1965
|
|
|
1350
1966
|
/**
|
|
1351
1967
|
* `insert … on conflict (columns) do nothing`, and for `update` the conflicting row's update in the same transaction,
|
|
1352
|
-
* within the insert's own containment. A row deleted between the two is
|
|
1353
|
-
* the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
|
|
1968
|
+
* within the insert's own containment and the action's condition on the stored row. A row deleted between the two is
|
|
1969
|
+
* inserted on the second try; a conflicting row the capability does not reach is a 409. Answers `{ id, version?, inserted: true }`, `{ id, version?, inserted:
|
|
1354
1970
|
* false }` after an update, and `{ inserted: false }` when `nothing` wrote nothing.
|
|
1355
1971
|
*/
|
|
1356
1972
|
async function insertOnConflict(
|
|
@@ -1372,7 +1988,7 @@ async function insertOnConflict(
|
|
|
1372
1988
|
}
|
|
1373
1989
|
matches[matches.length] = equals(model.name, name, value)
|
|
1374
1990
|
}
|
|
1375
|
-
const scope = conflict.mode === 'update' ? insertedScope(context, values) : undefined
|
|
1991
|
+
const scope = conflict.mode === 'update' ? conditionedAny(model, conflict.actions, insertedScope(context, values), new Date()) : undefined
|
|
1376
1992
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
1377
1993
|
const node = insertNode(model.name, values, answer(context), conflict.columns)
|
|
1378
1994
|
const [row] = await transaction.run<Readonly<Record<string, unknown>>>(node, {
|
|
@@ -1453,7 +2069,7 @@ export async function updateRow<O>(
|
|
|
1453
2069
|
target: Addressed,
|
|
1454
2070
|
given: ReadonlyMap<string, Primitive | null>,
|
|
1455
2071
|
expectedVersion: OperationNode | undefined,
|
|
1456
|
-
|
|
2072
|
+
moved?: MovedRow,
|
|
1457
2073
|
): Promise<O> {
|
|
1458
2074
|
const { name: table, version } = context.model
|
|
1459
2075
|
const changes = boundValues(context, given)
|
|
@@ -1463,19 +2079,42 @@ export async function updateRow<O>(
|
|
|
1463
2079
|
? acknowledgementNode(table, keyOf(context.model), version, where)
|
|
1464
2080
|
: updateNode(table, changes, version, where, answer(context))
|
|
1465
2081
|
return run.write(async (transaction) => {
|
|
1466
|
-
|
|
1467
|
-
|
|
2082
|
+
// A move follows containment, so a path never holds its destination.
|
|
2083
|
+
if (moved !== undefined) {
|
|
2084
|
+
await lockDestination(transaction, context, moved.destination, noPath)
|
|
1468
2085
|
}
|
|
2086
|
+
const before = moved === undefined ? undefined : await narrowedHolds(transaction, context, moved, noPath)
|
|
1469
2087
|
const [row] = await transaction.run<O>(node, guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', target.scope))
|
|
1470
2088
|
if (row !== undefined) {
|
|
1471
2089
|
checkVersion(context, row)
|
|
1472
2090
|
await referenceUpdated(context, run, transaction, changes, row)
|
|
2091
|
+
if (moved !== undefined) {
|
|
2092
|
+
await judgeInserted(transaction, context, moved.judged, rowKey(context, row))
|
|
2093
|
+
await judgeNarrowed(transaction, context, moved, before, rowKey(context, row))
|
|
2094
|
+
}
|
|
1473
2095
|
return row
|
|
1474
2096
|
}
|
|
1475
2097
|
return missingOrChanged(context, transaction, target, expectedVersion)
|
|
1476
2098
|
})
|
|
1477
2099
|
}
|
|
1478
2100
|
|
|
2101
|
+
/**
|
|
2102
|
+
* A move's destination, locked before the write, and the destination's insert conditions, which judge the moved row
|
|
2103
|
+
* after it as an insert into the destination judges its row: the insert action's (`judgeInserted`), and each one
|
|
2104
|
+
* `relationWhen` puts on a relation the destination `Ref` holds through (`judgeNarrowed`).
|
|
2105
|
+
*/
|
|
2106
|
+
export interface MovedRow {
|
|
2107
|
+
readonly destination: RefGrant
|
|
2108
|
+
readonly judged: JudgedInsert | undefined
|
|
2109
|
+
readonly narrowed: readonly NarrowedInsert[]
|
|
2110
|
+
}
|
|
2111
|
+
|
|
2112
|
+
/** The key `row`, a write's acknowledgement, answers; `undefined` when it answers none as text. */
|
|
2113
|
+
function rowKey(context: TableContext, row: unknown): string | undefined {
|
|
2114
|
+
const value: unknown = typeof row === 'object' && row !== null ? ownDescriptor(row, keyOf(context.model))?.value : undefined
|
|
2115
|
+
return typeof value === 'string' ? value : undefined
|
|
2116
|
+
}
|
|
2117
|
+
|
|
1479
2118
|
/** Like `updateRow`: under `expectVersion`, a row that changed is 409 and a missing one 404. */
|
|
1480
2119
|
export async function removeRow(context: TableContext, run: Runner, target: Addressed, expectedVersion?: OperationNode): Promise<void> {
|
|
1481
2120
|
const node = deleteNode(context.model.name, scopedWhere(conditionsWith(target, expectedVersion), target.scope), keyOf(context.model))
|
|
@@ -1491,11 +2130,11 @@ type Columns<Row> = keyof Row & string
|
|
|
1491
2130
|
type NumericColumn<Row> = { [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never }[Columns<Row>]
|
|
1492
2131
|
|
|
1493
2132
|
export interface AggregateSpec<Row> {
|
|
1494
|
-
readonly groupBy?: readonly
|
|
2133
|
+
readonly groupBy?: readonly ComparableColumn<Row>[]
|
|
1495
2134
|
readonly count?: boolean
|
|
1496
2135
|
readonly sum?: readonly NumericColumn<Row>[]
|
|
1497
|
-
readonly min?: readonly
|
|
1498
|
-
readonly max?: readonly
|
|
2136
|
+
readonly min?: readonly ComparableColumn<Row>[]
|
|
2137
|
+
readonly max?: readonly ComparableColumn<Row>[]
|
|
1499
2138
|
readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>
|
|
1500
2139
|
}
|
|
1501
2140
|
|
|
@@ -1532,7 +2171,7 @@ function aggregateColumns(table: string, shape: TableShape, spec: AggregateInput
|
|
|
1532
2171
|
if (!inSet(shape.visible, name)) {
|
|
1533
2172
|
throw new QueryRefusedError('unknown_column', `${String(name)} is not a column of ${table} (columns: ${namesOf(shape.visible).join(', ')})`)
|
|
1534
2173
|
}
|
|
1535
|
-
return name
|
|
2174
|
+
return comparableColumnOf(shape, name, 'aggregates')
|
|
1536
2175
|
})
|
|
1537
2176
|
if (names === undefined) {
|
|
1538
2177
|
throw new QueryRefusedError('invalid_argument', `aggregate ${field} takes a plain array of column names`)
|
|
@@ -1555,7 +2194,7 @@ function aggregateFilter<Row>(shape: TableShape, where: AggregateSpec<Row>['wher
|
|
|
1555
2194
|
throw new QueryRefusedError('invalid_argument', 'aggregate where takes a callback')
|
|
1556
2195
|
}
|
|
1557
2196
|
const start = startSelect<Row, NoColumns>(shape)
|
|
1558
|
-
const state =
|
|
2197
|
+
const state = finishFilter(where(start), start)
|
|
1559
2198
|
if (state.columns !== undefined || state.orderBy.length > 0 || state.limit !== undefined || state.offset !== undefined || state.joins.length > 0) {
|
|
1560
2199
|
throw new QueryRefusedError('invalid_argument', 'aggregate where takes where conditions only')
|
|
1561
2200
|
}
|
|
@@ -1574,7 +2213,8 @@ export async function aggregateRows<Row, O>(
|
|
|
1574
2213
|
}
|
|
1575
2214
|
const columns = aggregateColumns(context.model.name, shape, spec)
|
|
1576
2215
|
const filter = aggregateFilter(shape, spec.where)
|
|
1577
|
-
|
|
2216
|
+
// An `in` with an empty list answers what an empty `Within` does, and sends no statement.
|
|
2217
|
+
if (scope === undefined || filter?.matchesNone === true) {
|
|
1578
2218
|
return []
|
|
1579
2219
|
}
|
|
1580
2220
|
const dialect = dialectOf(context)
|
|
@@ -1586,6 +2226,7 @@ export async function aggregateRows<Row, O>(
|
|
|
1586
2226
|
days: aggregated(own.days, columns),
|
|
1587
2227
|
timestamps: aggregated(own.timestamps, columns),
|
|
1588
2228
|
booleans: aggregated(own.booleans, columns),
|
|
2229
|
+
json: nameSet([]),
|
|
1589
2230
|
}, rows)
|
|
1590
2231
|
return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
|
|
1591
2232
|
}
|
|
@@ -1641,8 +2282,25 @@ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]
|
|
|
1641
2282
|
/** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
|
|
1642
2283
|
export interface PreparedInsert {
|
|
1643
2284
|
readonly row: Map<string, Primitive | null>
|
|
2285
|
+
/** The principal the insert acts for: the bound of a reveal through a secondary path is judged against it. */
|
|
2286
|
+
readonly writer: string
|
|
1644
2287
|
readonly destination: RefGrant | undefined
|
|
1645
2288
|
readonly conflict: OnConflict | undefined
|
|
2289
|
+
/** The insert action's condition when it follows a path: judged in the insert's transaction, on the rows it names. */
|
|
2290
|
+
readonly judged: JudgedInsert | undefined
|
|
2291
|
+
/** The destination's relations whose `relationWhen` for the insert follows a path: judged on the written row. */
|
|
2292
|
+
readonly narrowed: readonly NarrowedInsert[]
|
|
2293
|
+
}
|
|
2294
|
+
|
|
2295
|
+
export interface JudgedInsert {
|
|
2296
|
+
readonly action: string
|
|
2297
|
+
readonly condition: ConditionModel
|
|
2298
|
+
}
|
|
2299
|
+
|
|
2300
|
+
/** A relation the destination `Ref` holds through, which the inserted table narrows for the insert by a condition with a path. */
|
|
2301
|
+
export interface NarrowedInsert {
|
|
2302
|
+
readonly relation: string
|
|
2303
|
+
readonly condition: ConditionModel
|
|
1646
2304
|
}
|
|
1647
2305
|
|
|
1648
2306
|
/**
|
|
@@ -1653,25 +2311,66 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
|
|
|
1653
2311
|
const scope = dimensionScope(context.model)
|
|
1654
2312
|
const grant = refGrant(context, target, listDimension(scope), 'insert')
|
|
1655
2313
|
const row = readValues(values, context.model.insert, 'insert', context.model)
|
|
1656
|
-
const conflict = onConflictOf(context, options, grant.action, row)
|
|
2314
|
+
const conflict = onConflictOf(context, options, [grant.action], row)
|
|
1657
2315
|
if (scope.container === undefined) {
|
|
1658
2316
|
// The object does not exist yet; this only refuses a chain the table has no column for.
|
|
1659
2317
|
linkValues(context.model.name, [{ dimension: scope.dimension, column: scope.key }], grant)
|
|
1660
2318
|
stampInsert(context, grant, row, scope.key, grant.id)
|
|
1661
|
-
|
|
2319
|
+
const judged = checkInserted(context, [grant.action], grant.principal, row)
|
|
2320
|
+
// No destination to check again after the write, so a condition with a path holds nothing here.
|
|
2321
|
+
narrowedDestination(context, grant, row, false)
|
|
2322
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
|
|
1662
2323
|
}
|
|
1663
2324
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1664
2325
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1665
|
-
|
|
2326
|
+
const judged = checkInserted(context, [grant.action], grant.principal, row)
|
|
2327
|
+
const held = narrowedDestination(context, grant, row, true)
|
|
2328
|
+
return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
|
|
1666
2329
|
}
|
|
1667
2330
|
|
|
1668
2331
|
/** An application table's insert, for an `app` capability of its insert action: a new key, no containment. */
|
|
1669
2332
|
export function prepareApplicationInsert(context: TableContext, capability: unknown, values: unknown, options?: unknown): PreparedInsert {
|
|
1670
|
-
const grant = appGrant(context, capability, 'insert')
|
|
2333
|
+
const { grant, actions } = appGrant(context, capability, 'insert')
|
|
2334
|
+
// Every insert action writes the table's one insert list, so each held one writes all of `values`: only their conditions differ.
|
|
1671
2335
|
const row = readValues(values, context.model.insert, 'insert', context.model)
|
|
1672
|
-
|
|
2336
|
+
// Only an insert action that also updates may update on a conflict: never one action's insert with another's update.
|
|
2337
|
+
const declared = onConflictOf(context, options, actions, row)
|
|
1673
2338
|
stampInsert(context, grant, row, keyOf(context.model), uuidv7())
|
|
1674
|
-
|
|
2339
|
+
const conflict = declared?.mode === 'update' ? upsertingActions(context.model, declared, row) : declared
|
|
2340
|
+
const judged = checkInserted(context, conflict?.mode === 'update' ? conflict.actions : actions, grant.principal, row)
|
|
2341
|
+
return { row, writer: grant.principal, destination: undefined, conflict, judged, narrowed: [] }
|
|
2342
|
+
}
|
|
2343
|
+
|
|
2344
|
+
/**
|
|
2345
|
+
* An upsert under several actions that each insert and update: only those whose own condition admits the inserted row
|
|
2346
|
+
* may update the conflicting one, so the update runs under an action whose insert alone was allowed. A condition that
|
|
2347
|
+
* follows a path is judged only in the transaction, after the update chose its actions, so several such are refused.
|
|
2348
|
+
*/
|
|
2349
|
+
function upsertingActions(model: TableModel, conflict: OnConflict, row: ReadonlyMap<string, Primitive | null>): OnConflict {
|
|
2350
|
+
if (conflict.actions.length < 2) {
|
|
2351
|
+
return conflict
|
|
2352
|
+
}
|
|
2353
|
+
const now = new Date()
|
|
2354
|
+
const admitting: string[] = []
|
|
2355
|
+
for (let index = 0; index < conflict.actions.length; index++) {
|
|
2356
|
+
const action = conflict.actions[index] ?? ''
|
|
2357
|
+
const condition = ownEntry(model.when, action)
|
|
2358
|
+
if (condition !== undefined && readPaths(condition).length > 0) {
|
|
2359
|
+
throw new CapabilityError(
|
|
2360
|
+
'unenforceable',
|
|
2361
|
+
`an insert into ${model.name} that updates on a conflict under ${
|
|
2362
|
+
conflict.actions.join(', ')
|
|
2363
|
+
} would pair a condition that follows a path with another action's: upsert from an endpoint of one of them`,
|
|
2364
|
+
)
|
|
2365
|
+
}
|
|
2366
|
+
if (condition === undefined || rowSatisfies(condition, row, now)) {
|
|
2367
|
+
admitting[admitting.length] = action
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
// None admits the row: keep them all, and the insert's own check refuses it.
|
|
2371
|
+
return admitting.length === 0
|
|
2372
|
+
? conflict
|
|
2373
|
+
: freeze({ columns: conflict.columns, mode: conflict.mode, updates: conflict.updates, actions: freeze(admitting) })
|
|
1675
2374
|
}
|
|
1676
2375
|
|
|
1677
2376
|
/** A child table's insert under the parent its `Ref` names, whose chain is checked against the database. */
|
|
@@ -1679,52 +2378,574 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
|
|
|
1679
2378
|
const scope = childScope(context)
|
|
1680
2379
|
const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
|
|
1681
2380
|
const row = readValues(values, context.model.insert, 'insert', context.model)
|
|
1682
|
-
const conflict = onConflictOf(context, options, grant.action, row)
|
|
2381
|
+
const conflict = onConflictOf(context, options, [grant.action], row)
|
|
1683
2382
|
stampInsert(context, grant, row, scope.key, uuidv7())
|
|
1684
2383
|
stampChain(row, linkValues(context.model.name, context.model.chain, grant))
|
|
1685
|
-
|
|
2384
|
+
const judged = checkInserted(context, [grant.action], grant.principal, row)
|
|
2385
|
+
const held = narrowedDestination(context, grant, row, true)
|
|
2386
|
+
return { row, writer: grant.principal, destination: held.destination, conflict, judged, narrowed: held.narrowed }
|
|
1686
2387
|
}
|
|
1687
2388
|
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
2389
|
+
const DAY_MS = 86_400_000
|
|
2390
|
+
|
|
2391
|
+
/**
|
|
2392
|
+
* An inserted row as its insert action's condition judges it, on its final values, and, for a relation source, within
|
|
2393
|
+
* its delegation bound: a row naming the inserting principal only with `assign.self`, an expiry at most `maxDays`
|
|
2394
|
+
* ahead. Its node is the inserting Ref's, stamped above, so a row confers only where its writer acts. A condition
|
|
2395
|
+
* that follows a path is answered for the transaction to judge.
|
|
2396
|
+
*/
|
|
2397
|
+
function checkInserted(
|
|
2398
|
+
context: TableContext,
|
|
2399
|
+
actions: readonly string[],
|
|
2400
|
+
principal: string,
|
|
2401
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2402
|
+
): JudgedInsert | undefined {
|
|
2403
|
+
const model = context.model
|
|
2404
|
+
const now = new Date()
|
|
2405
|
+
const judged = insertCondition(model, actions, row, now)
|
|
2406
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
2407
|
+
const source = model.confers[index]
|
|
2408
|
+
if (source === undefined) {
|
|
2409
|
+
continue
|
|
2410
|
+
}
|
|
2411
|
+
const assign = source.assign
|
|
2412
|
+
if (assign === undefined) {
|
|
2413
|
+
throw new CapabilityError('undeclared_operation', `${model.name} confers ${source.relation} and states no assign, so no handler inserts a row`)
|
|
2414
|
+
}
|
|
2415
|
+
// A principal through a path is resolved in the insert's transaction (`checkPrincipalAssign`).
|
|
2416
|
+
if (!assign.self && source.principalPath === undefined && row.get(source.principal) === principal) {
|
|
2417
|
+
throw new ConflictError(`a row of ${model.name} names its writer in ${source.relation}, which assign.self does not allow`)
|
|
2418
|
+
}
|
|
2419
|
+
if (assign.maxDays !== undefined && source.expires !== undefined) {
|
|
2420
|
+
const value = row.get(source.expires)
|
|
2421
|
+
const until = value instanceof Date ? value.getTime() : typeof value === 'string' ? Date.parse(value) : Number.NaN
|
|
2422
|
+
if (Number.isNaN(until) || until > now.getTime() + assign.maxDays * DAY_MS) {
|
|
2423
|
+
throw new ConflictError(
|
|
2424
|
+
`a row of ${model.name} confers ${source.relation} until ${source.expires}, at most ${assign.maxDays} days ahead`,
|
|
2425
|
+
)
|
|
2426
|
+
}
|
|
1694
2427
|
}
|
|
1695
2428
|
}
|
|
2429
|
+
return judged
|
|
1696
2430
|
}
|
|
1697
2431
|
|
|
1698
|
-
/**
|
|
1699
|
-
|
|
1700
|
-
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
2432
|
+
/**
|
|
2433
|
+
* The insert actions' condition on the row, as one role holding `actions` is narrowed: a row any of them admits passes,
|
|
2434
|
+
* and one without a condition admits every row. A pathless condition is judged here; one that follows a path is
|
|
2435
|
+
* answered for the transaction to judge, which holds one such condition only, so several are refused.
|
|
2436
|
+
*/
|
|
2437
|
+
function insertCondition(
|
|
2438
|
+
model: TableModel,
|
|
2439
|
+
actions: readonly string[],
|
|
2440
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2441
|
+
now: Date,
|
|
2442
|
+
): JudgedInsert | undefined {
|
|
2443
|
+
const pathed: JudgedInsert[] = []
|
|
2444
|
+
for (let index = 0; index < actions.length; index++) {
|
|
2445
|
+
const action = actions[index]
|
|
2446
|
+
if (action === undefined) continue
|
|
2447
|
+
const condition = ownEntry(model.when, action)
|
|
2448
|
+
if (condition === undefined) {
|
|
2449
|
+
return undefined
|
|
1707
2450
|
}
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
}
|
|
2451
|
+
if (readPaths(condition).length > 0) {
|
|
2452
|
+
pathed[pathed.length] = { action, condition }
|
|
2453
|
+
} else if (rowSatisfies(condition, row, now)) {
|
|
2454
|
+
return undefined
|
|
2455
|
+
}
|
|
2456
|
+
}
|
|
2457
|
+
const [only, ...more] = pathed
|
|
2458
|
+
if (only === undefined) {
|
|
2459
|
+
throw new ConflictError(`the row is outside what ${actions.join(' or ')} inserts into ${model.name}`)
|
|
2460
|
+
}
|
|
2461
|
+
if (more.length > 0) {
|
|
2462
|
+
throw new CapabilityError(
|
|
2463
|
+
'unenforceable',
|
|
2464
|
+
`an insert into ${model.name} under ${
|
|
2465
|
+
actions.join(', ')
|
|
2466
|
+
} would be judged by several conditions that follow paths: insert from an endpoint of one of them`,
|
|
2467
|
+
)
|
|
2468
|
+
}
|
|
2469
|
+
return only
|
|
2470
|
+
}
|
|
2471
|
+
|
|
2472
|
+
/**
|
|
2473
|
+
* The destination `Ref` an insert locks, without the relations the inserted table's `relationWhen` narrows for the insert
|
|
2474
|
+
* and the written row fails: a pathless condition judged here, on the row's final values; one with a path answered for
|
|
2475
|
+
* 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
|
|
2476
|
+
* is never judged on the written row, so the row never counts towards its own insert.
|
|
2477
|
+
*/
|
|
2478
|
+
function narrowedDestination(
|
|
2479
|
+
context: TableContext,
|
|
2480
|
+
grant: RefGrant,
|
|
2481
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2482
|
+
defer: boolean,
|
|
2483
|
+
): { readonly destination: RefGrant; readonly narrowed: readonly NarrowedInsert[] } {
|
|
2484
|
+
const now = new Date()
|
|
2485
|
+
const kept: RelationHold[] = []
|
|
2486
|
+
const narrowed: NarrowedInsert[] = []
|
|
2487
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
2488
|
+
const hold = grant.relations[index]
|
|
2489
|
+
if (hold === undefined) continue
|
|
2490
|
+
const relation = hold.relation
|
|
2491
|
+
const condition = relationCondition(context.model, relation, grant.action)
|
|
2492
|
+
const pathed = condition !== undefined && readPaths(condition).length > 0
|
|
2493
|
+
if (condition !== undefined && pathed && defer && !judgesRelation(narrowed, relation)) {
|
|
2494
|
+
narrowed[narrowed.length] = { relation, condition }
|
|
2495
|
+
}
|
|
2496
|
+
if (condition === undefined || (pathed ? defer : rowSatisfies(condition, row, now))) {
|
|
2497
|
+
kept[kept.length] = hold
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
if (kept.length === grant.relations.length) {
|
|
2501
|
+
return { destination: grant, narrowed }
|
|
2502
|
+
}
|
|
2503
|
+
if (kept.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
|
|
2504
|
+
throw new ConflictError(`the row is outside what ${grant.action} inserts into ${context.model.name} through its relations`)
|
|
2505
|
+
}
|
|
2506
|
+
return { destination: { ...grant, relations: kept }, narrowed }
|
|
2507
|
+
}
|
|
2508
|
+
|
|
2509
|
+
/** Whether `narrowed` already judges `relation`: two holds of one relation are judged once. */
|
|
2510
|
+
function judgesRelation(narrowed: readonly NarrowedInsert[], relation: string): boolean {
|
|
2511
|
+
for (let index = 0; index < narrowed.length; index++) {
|
|
2512
|
+
if (narrowed[index]?.relation === relation) return true
|
|
2513
|
+
}
|
|
2514
|
+
return false
|
|
2515
|
+
}
|
|
2516
|
+
|
|
2517
|
+
/**
|
|
2518
|
+
* What held an insert's destination before the write, apart from the relations narrowed by a path: the rest of the
|
|
2519
|
+
* `Ref`, and, with several such relations, each of them alone. Decided before the row exists, so it never counts it.
|
|
2520
|
+
*/
|
|
2521
|
+
interface NarrowedHolds {
|
|
2522
|
+
readonly rest: boolean
|
|
2523
|
+
readonly alone: readonly string[]
|
|
2524
|
+
}
|
|
2525
|
+
|
|
2526
|
+
/** `NarrowedHolds` of a prepared insert, locked `for share` in its transaction before the write; `undefined` with nothing narrowed. */
|
|
2527
|
+
async function narrowedHolds(
|
|
2528
|
+
transaction: Session,
|
|
2529
|
+
context: TableContext,
|
|
2530
|
+
prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
|
|
2531
|
+
paths?: PathRule,
|
|
2532
|
+
): Promise<NarrowedHolds | undefined> {
|
|
2533
|
+
const destination = prepared?.destination
|
|
2534
|
+
if (prepared === undefined || destination === undefined || prepared.narrowed.length === 0) {
|
|
2535
|
+
return undefined
|
|
2536
|
+
}
|
|
2537
|
+
const relations: string[] = []
|
|
2538
|
+
for (let index = 0; index < prepared.narrowed.length; index++) {
|
|
2539
|
+
const entry = prepared.narrowed[index]
|
|
2540
|
+
if (entry !== undefined) relations[relations.length] = entry.relation
|
|
2541
|
+
}
|
|
2542
|
+
const rest = await heldBy(transaction, context, { ...destination, relations: holdsBesides(destination.relations, relations) }, paths)
|
|
2543
|
+
const alone: string[] = []
|
|
2544
|
+
// One narrowed relation that passes leaves the destination as `lockDestination` found it; only with several may it be another's.
|
|
2545
|
+
for (let index = 0; relations.length > 1 && index < relations.length; index++) {
|
|
2546
|
+
const relation = relations[index] ?? ''
|
|
2547
|
+
const holds: RelationHold[] = []
|
|
2548
|
+
for (let position = 0; position < destination.relations.length; position++) {
|
|
2549
|
+
const hold = destination.relations[position]
|
|
2550
|
+
if (hold !== undefined && hold.relation === relation) holds[holds.length] = hold
|
|
2551
|
+
}
|
|
2552
|
+
if (await heldBy(transaction, context, { ...destination, relations: holds, revealing: [], paths: [] }, paths)) alone[alone.length] = relation
|
|
2553
|
+
}
|
|
2554
|
+
return { rest, alone }
|
|
2555
|
+
}
|
|
2556
|
+
|
|
2557
|
+
/** Whether `grant` holds the destination: with no part left, never. */
|
|
2558
|
+
async function heldBy(transaction: Session, context: TableContext, grant: RefGrant, paths?: PathRule): Promise<boolean> {
|
|
2559
|
+
if (grant.relations.length === 0 && grant.revealing.length === 0 && grant.paths.length === 0) {
|
|
2560
|
+
return false
|
|
2561
|
+
}
|
|
2562
|
+
return await destinationHeld(transaction, context, grant, paths)
|
|
2563
|
+
}
|
|
2564
|
+
|
|
2565
|
+
/**
|
|
2566
|
+
* The destination's relations whose condition for the insert follows a path, judged on the row just written as
|
|
2567
|
+
* `judgeInserted` judges `when`. When the row fails one, the insert stands only on what held the destination before the
|
|
2568
|
+
* write without it (`before`): the rest of the `Ref`, or a narrowed relation the row meets that held it alone. Otherwise
|
|
2569
|
+
* the transaction fails with a 409.
|
|
2570
|
+
*/
|
|
2571
|
+
async function judgeNarrowed(
|
|
2572
|
+
transaction: Session,
|
|
2573
|
+
context: TableContext,
|
|
2574
|
+
prepared: Pick<PreparedInsert, 'destination' | 'narrowed'> | undefined,
|
|
2575
|
+
before: NarrowedHolds | undefined,
|
|
2576
|
+
key: Primitive | null | undefined,
|
|
2577
|
+
): Promise<void> {
|
|
2578
|
+
const destination = prepared?.destination
|
|
2579
|
+
if (prepared === undefined || destination === undefined || before === undefined) {
|
|
2580
|
+
return
|
|
2581
|
+
}
|
|
2582
|
+
let failed = false
|
|
2583
|
+
let held = before.rest
|
|
2584
|
+
for (let index = 0; index < prepared.narrowed.length; index++) {
|
|
2585
|
+
const entry = prepared.narrowed[index]
|
|
2586
|
+
if (entry === undefined) continue
|
|
2587
|
+
if (!(await rowMeets(transaction, context, destination.action, entry.condition, key))) {
|
|
2588
|
+
failed = true
|
|
2589
|
+
} else if (includes(before.alone, entry.relation)) {
|
|
2590
|
+
held = true
|
|
2591
|
+
}
|
|
2592
|
+
}
|
|
2593
|
+
if (failed && !held) {
|
|
2594
|
+
transaction.fail()
|
|
2595
|
+
throw new ConflictError(`the row is outside what ${destination.action} inserts into ${context.model.name} through its relations`)
|
|
2596
|
+
}
|
|
2597
|
+
}
|
|
2598
|
+
|
|
2599
|
+
/**
|
|
2600
|
+
* An insert's condition that follows a path, judged on the row just written, in its transaction. The database has then
|
|
2601
|
+
* 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
|
|
2602
|
+
* reaches is locked `FOR SHARE` first (a `some`'s rows: every row naming the row it reached), so none changes or goes
|
|
2603
|
+
* before the commit; then the condition is judged as a read of the row judges it. A refused row fails the transaction,
|
|
2604
|
+
* so it commits nothing even when the handler catches the refusal.
|
|
2605
|
+
*/
|
|
2606
|
+
async function judgeInserted(
|
|
2607
|
+
transaction: Session,
|
|
2608
|
+
context: TableContext,
|
|
2609
|
+
judged: JudgedInsert | undefined,
|
|
2610
|
+
key: Primitive | null | undefined,
|
|
2611
|
+
): Promise<void> {
|
|
2612
|
+
if (judged === undefined) {
|
|
2613
|
+
return
|
|
2614
|
+
}
|
|
2615
|
+
if (!(await rowMeets(transaction, context, judged.action, judged.condition, key))) {
|
|
2616
|
+
transaction.fail()
|
|
2617
|
+
throw new ConflictError(`the row is outside what ${judged.action} inserts into ${context.model.name}`)
|
|
2618
|
+
}
|
|
2619
|
+
}
|
|
2620
|
+
|
|
2621
|
+
/**
|
|
2622
|
+
* Whether the row just written meets `condition`, in the insert's transaction: every row each of its paths reaches is
|
|
2623
|
+
* locked `FOR SHARE` first, then the condition is judged as a read of the row judges it.
|
|
2624
|
+
*/
|
|
2625
|
+
async function rowMeets(
|
|
2626
|
+
transaction: Session,
|
|
2627
|
+
context: TableContext,
|
|
2628
|
+
action: string,
|
|
2629
|
+
condition: ConditionModel,
|
|
2630
|
+
key: Primitive | null | undefined,
|
|
2631
|
+
): Promise<boolean> {
|
|
2632
|
+
const model = context.model
|
|
2633
|
+
if (key === undefined || key === null) {
|
|
2634
|
+
throw new QueryRefusedError('unexpected_row', `an insert into ${model.name} judged by ${action} has no key`)
|
|
2635
|
+
}
|
|
2636
|
+
const paths = readPaths(condition)
|
|
2637
|
+
for (let index = 0; index < paths.length; index++) {
|
|
2638
|
+
const steps = paths[index] ?? []
|
|
2639
|
+
// The rows a path reaches, step by step from the inserted row; each statement admits the columns it walks.
|
|
2640
|
+
let reached = subquery(model.name, steps[0]?.from ?? '', equals(model.name, keyOf(model), key))
|
|
2641
|
+
const walked: Record<string, string[]> = { [model.name]: [steps[0]?.from ?? ''] }
|
|
2642
|
+
for (let position = 0; position < steps.length; position++) {
|
|
2643
|
+
const step = steps[position]
|
|
2644
|
+
if (step === undefined) continue
|
|
2645
|
+
const scope = BinaryOperationNode.create(column(step.table, step.to), OperatorNode.create('in'), reached)
|
|
2646
|
+
await transaction.run(lockNode(step.table, step.to, scope), {
|
|
2647
|
+
root: 'SelectQueryNode',
|
|
2648
|
+
table: step.table,
|
|
2649
|
+
joins: {},
|
|
2650
|
+
scope,
|
|
2651
|
+
lock: 'share',
|
|
2652
|
+
subqueries: withColumns(context.subqueries, walked),
|
|
2653
|
+
})
|
|
2654
|
+
const next = steps[position + 1]
|
|
2655
|
+
if (next !== undefined) {
|
|
2656
|
+
reached = subquery(step.table, next.from, scope)
|
|
2657
|
+
walked[step.table] = [...(walked[step.table] ?? []), next.from]
|
|
2658
|
+
}
|
|
2659
|
+
}
|
|
2660
|
+
}
|
|
2661
|
+
const scope = AndNode.create(equals(model.name, keyOf(model), key), ParensNode.create(conditionNode(model.name, condition, new Date())))
|
|
2662
|
+
const rows = await transaction.run(locateNode(model.name, [keyOf(model)], scope), {
|
|
2663
|
+
root: 'SelectQueryNode',
|
|
2664
|
+
table: model.name,
|
|
2665
|
+
joins: {},
|
|
2666
|
+
scope,
|
|
2667
|
+
subqueries: context.subqueries,
|
|
2668
|
+
})
|
|
2669
|
+
return rows.length > 0
|
|
2670
|
+
}
|
|
2671
|
+
|
|
2672
|
+
/** `admitted` with `more` added: the columns one statement the layer builds may select in its subqueries. */
|
|
2673
|
+
function withColumns(
|
|
2674
|
+
admitted: Readonly<Record<string, readonly string[]>>,
|
|
2675
|
+
more: Readonly<Record<string, readonly string[]>>,
|
|
2676
|
+
): Readonly<Record<string, readonly string[]>> {
|
|
2677
|
+
const merged: Record<string, readonly string[]> = { ...admitted }
|
|
2678
|
+
const tables = ownKeys(more)
|
|
2679
|
+
for (let index = 0; index < tables.length; index++) {
|
|
2680
|
+
const table = tables[index] ?? ''
|
|
2681
|
+
setOwn(merged, table, [...(ownEntry(admitted, table) ?? []), ...(ownEntry(more, table) ?? [])])
|
|
2682
|
+
}
|
|
2683
|
+
return merged
|
|
2684
|
+
}
|
|
2685
|
+
|
|
2686
|
+
/** Writes each chain column the destination `Ref` settles into an insert's row. */
|
|
2687
|
+
function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
|
|
2688
|
+
for (let index = 0; index < values.length; index++) {
|
|
2689
|
+
const entry = values[index]
|
|
2690
|
+
if (entry !== undefined) {
|
|
2691
|
+
row.set(entry.link.column, entry.value)
|
|
2692
|
+
}
|
|
2693
|
+
}
|
|
2694
|
+
}
|
|
2695
|
+
|
|
2696
|
+
/** A prepared insert, with its conflict handling when the caller named one. */
|
|
2697
|
+
export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
|
|
2698
|
+
const conflict = prepared.conflict
|
|
2699
|
+
if (conflict === undefined) {
|
|
2700
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
2701
|
+
}
|
|
2702
|
+
return run.write(async (transaction) => {
|
|
2703
|
+
if (prepared.destination !== undefined) {
|
|
2704
|
+
await lockDestination(transaction, context, prepared.destination)
|
|
2705
|
+
}
|
|
2706
|
+
const before = await narrowedHolds(transaction, context, prepared)
|
|
2707
|
+
await checkPrincipalAssign(transaction, context, prepared.writer, prepared.row)
|
|
2708
|
+
await checkRevealAssign(transaction, context, prepared.writer, prepared.row)
|
|
2709
|
+
await checkMemberRevealAssign(transaction, context, prepared.writer, prepared.row)
|
|
2710
|
+
await checkPathWriters(transaction, context, prepared.writer, prepared.row)
|
|
2711
|
+
const written = await insertOnConflict(context, run, transaction, prepared.row, conflict)
|
|
2712
|
+
// A conflict writes no new row: `nothing` reads none, and `update` is judged on the stored row.
|
|
2713
|
+
if (written['inserted'] === true) {
|
|
2714
|
+
await judgeInserted(transaction, context, prepared.judged, prepared.row.get(keyOf(context.model)))
|
|
2715
|
+
await judgeNarrowed(transaction, context, prepared, before, prepared.row.get(keyOf(context.model)))
|
|
2716
|
+
}
|
|
2717
|
+
return written
|
|
2718
|
+
})
|
|
2719
|
+
}
|
|
2720
|
+
|
|
2721
|
+
/**
|
|
2722
|
+
* A source row whose principal its path's table holds, under `assign.self`: without it, the insert is refused while the
|
|
2723
|
+
* row its column names there names the writer. That row is locked `FOR SHARE` first, so it keeps its principal and
|
|
2724
|
+
* stays until the commit. One lock and one guarded select per such source, in the insert's transaction.
|
|
2725
|
+
*/
|
|
2726
|
+
async function checkPrincipalAssign(
|
|
2727
|
+
transaction: Session,
|
|
2728
|
+
context: TableContext,
|
|
2729
|
+
writer: string,
|
|
2730
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2731
|
+
): Promise<void> {
|
|
2732
|
+
const model = context.model
|
|
2733
|
+
for (let index = 0; index < model.confers.length; index++) {
|
|
2734
|
+
const source = model.confers[index]
|
|
2735
|
+
const path = source?.principalPath
|
|
2736
|
+
const value = source === undefined ? undefined : row.get(source.principal)
|
|
2737
|
+
if (source === undefined || path === undefined || source.assign === undefined || source.assign.self || value === undefined || value === null) {
|
|
2738
|
+
continue
|
|
2739
|
+
}
|
|
2740
|
+
const keyed = equals(path.table, path.key, value)
|
|
2741
|
+
await transaction.run(lockNode(path.table, path.key, keyed), { root: 'SelectQueryNode', table: path.table, joins: {}, scope: keyed, lock: 'share' })
|
|
2742
|
+
const named = allOf([keyed, equals(path.table, path.column, writer)])
|
|
2743
|
+
const rows = await transaction.run(locateNode(path.table, [path.key], named), {
|
|
2744
|
+
root: 'SelectQueryNode',
|
|
2745
|
+
table: path.table,
|
|
2746
|
+
joins: {},
|
|
2747
|
+
scope: named,
|
|
2748
|
+
})
|
|
2749
|
+
if (rows.length > 0) {
|
|
2750
|
+
throw new ConflictError(
|
|
2751
|
+
`a row of ${model.name} names its writer in ${source.relation} through ${source.principal}, which assign.self does not allow`,
|
|
2752
|
+
)
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
2756
|
+
|
|
2757
|
+
/**
|
|
2758
|
+
* An inserted row whose `readThrough` column a reveal matches through, under the reveal's `assign`: without `self`, the
|
|
2759
|
+
* insert is refused while its writer holds the reveal's relation at the node the column names, or at the ancestor of it
|
|
2760
|
+
* the relation is at. One guarded select per such reveal, in the insert's transaction.
|
|
2761
|
+
*/
|
|
2762
|
+
async function checkRevealAssign(
|
|
2763
|
+
transaction: Session,
|
|
2764
|
+
context: TableContext,
|
|
2765
|
+
writer: string,
|
|
2766
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2767
|
+
): Promise<void> {
|
|
2768
|
+
const model = context.model
|
|
2769
|
+
const now = new Date()
|
|
2770
|
+
for (let index = 0; index < model.reveals.length; index++) {
|
|
2771
|
+
const reveal = model.reveals[index]
|
|
2772
|
+
const path = reveal?.path
|
|
2773
|
+
const value = path === undefined ? undefined : row.get(path.column)
|
|
2774
|
+
if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || typeof value !== 'string') continue
|
|
2775
|
+
const source = relationSource(context.relations, reveal.relation)
|
|
2776
|
+
const tests: OperationNode[] = []
|
|
2777
|
+
const rest: OperationNode[] = [...activeRow(source, now)]
|
|
2778
|
+
if (source.dimension === path.dimension) {
|
|
2779
|
+
tests[tests.length] = equals(source.table, source.node, value)
|
|
2780
|
+
} else {
|
|
2781
|
+
const link = linkOf(path.chain, source.dimension)
|
|
2782
|
+
if (link === undefined) continue
|
|
2783
|
+
const above = subquery(path.table, link.column, equals(path.table, path.key, value))
|
|
2784
|
+
rest.unshift(BinaryOperationNode.create(column(source.table, source.node), OperatorNode.create('in'), above))
|
|
2785
|
+
}
|
|
2786
|
+
// The principal test comes last: an equality, or a path's membership after the node's equality.
|
|
2787
|
+
tests[tests.length] = namesPrincipal(source, writer)
|
|
2788
|
+
const address = allOf(tests)
|
|
2789
|
+
const scope = rest.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(rest)))
|
|
2790
|
+
const rows = await transaction.run(locateNode(source.table, [source.node], scope), {
|
|
2791
|
+
root: 'SelectQueryNode',
|
|
2792
|
+
table: source.table,
|
|
2793
|
+
joins: {},
|
|
2794
|
+
scope,
|
|
2795
|
+
subqueries: context.subqueries,
|
|
2796
|
+
})
|
|
2797
|
+
if (rows.length > 0) {
|
|
2798
|
+
throw new ConflictError(
|
|
2799
|
+
`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`,
|
|
2800
|
+
)
|
|
2801
|
+
}
|
|
2802
|
+
}
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
/**
|
|
2806
|
+
* An inserted row whose path column a member reveal matches through, under the reveal's `assign`: without `self`, the
|
|
2807
|
+
* insert is refused while its writer holds a grant the reveal counts (one of its actions, at the node itself) at the
|
|
2808
|
+
* node the column names. The grants are the request's own; the database compares them with the node's key, so every
|
|
2809
|
+
* spelling of a key it reads as one (a `uuid`) is that node. Work with no request caller has none to judge, and is
|
|
2810
|
+
* refused.
|
|
2811
|
+
*/
|
|
2812
|
+
async function checkMemberRevealAssign(
|
|
2813
|
+
transaction: Session,
|
|
2814
|
+
context: TableContext,
|
|
2815
|
+
writer: string,
|
|
2816
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2817
|
+
): Promise<void> {
|
|
2818
|
+
const model = context.model
|
|
2819
|
+
const authority = runtimeOf(context.connection).capabilities
|
|
2820
|
+
for (let index = 0; index < model.memberReveals.length; index++) {
|
|
2821
|
+
const reveal = model.memberReveals[index]
|
|
2822
|
+
const path = reveal?.path
|
|
2823
|
+
const value = path === undefined ? undefined : row.get(path.column)
|
|
2824
|
+
if (reveal === undefined || path === undefined || reveal.assign === undefined || reveal.assign.self || value === undefined || value === null) {
|
|
2825
|
+
continue
|
|
2826
|
+
}
|
|
2827
|
+
for (let position = 0; position < reveal.actions.length; position++) {
|
|
2828
|
+
const action = reveal.actions[position] ?? ''
|
|
2829
|
+
const standing = authority.standing?.(path.dimension, action)
|
|
2830
|
+
if (standing === undefined || standing.principal !== writer) {
|
|
2831
|
+
throw new ConflictError(
|
|
2832
|
+
`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`,
|
|
2833
|
+
)
|
|
2834
|
+
}
|
|
2835
|
+
if (standing.values === 'all' || standing.values.length === 0) continue
|
|
2836
|
+
const scope = AndNode.create(equals(path.table, path.key, value), inList(path.table, path.key, standing.values))
|
|
2837
|
+
const rows = await transaction.run(locateNode(path.table, [path.key], scope), {
|
|
2838
|
+
root: 'SelectQueryNode',
|
|
2839
|
+
table: path.table,
|
|
2840
|
+
joins: {},
|
|
2841
|
+
scope,
|
|
2842
|
+
})
|
|
2843
|
+
if (rows.length > 0) {
|
|
2844
|
+
throw new ConflictError(
|
|
2845
|
+
`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`,
|
|
2846
|
+
)
|
|
2847
|
+
}
|
|
2848
|
+
}
|
|
2849
|
+
}
|
|
2850
|
+
}
|
|
2851
|
+
|
|
2852
|
+
/**
|
|
2853
|
+
* An inserted row's path column that hands out actions (`writeThrough`): its writer must hold every one of them at the
|
|
2854
|
+
* node the column names, as a grant there or above it, a relation row naming it there (of a relation no `relationWhen`
|
|
2855
|
+
* narrows for the action), or a revealing row. The node's
|
|
2856
|
+
* row is locked `FOR SHARE` first, so it stays where it lies until the commit, and so is each row the writer holds it
|
|
2857
|
+
* through; IAM grants are the request's own. Judged before the insert, so the inserted row never counts. A writer
|
|
2858
|
+
* outside the bound, or work with no caller, is a 409 and nothing is written.
|
|
2859
|
+
*/
|
|
2860
|
+
async function checkPathWriters(
|
|
2861
|
+
transaction: Session,
|
|
2862
|
+
context: TableContext,
|
|
2863
|
+
writer: string,
|
|
2864
|
+
row: ReadonlyMap<string, Primitive | null>,
|
|
2865
|
+
): Promise<void> {
|
|
2866
|
+
const model = context.model
|
|
2867
|
+
const authority = runtimeOf(context.connection).capabilities
|
|
2868
|
+
for (let index = 0; index < context.writers.length; index++) {
|
|
2869
|
+
const bound = context.writers[index]
|
|
2870
|
+
const value = bound === undefined ? undefined : row.get(bound.path.column)
|
|
2871
|
+
if (bound === undefined || value === undefined || value === null) continue
|
|
2872
|
+
const { path, owner } = bound
|
|
2873
|
+
const refused = (action: string) =>
|
|
2874
|
+
new ConflictError(
|
|
2875
|
+
`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)`,
|
|
2876
|
+
)
|
|
2877
|
+
const keyed = equals(owner.name, keyOf(owner), value)
|
|
2878
|
+
const locked = await transaction.run(lockNode(owner.name, keyOf(owner), keyed), {
|
|
2879
|
+
root: 'SelectQueryNode',
|
|
2880
|
+
table: owner.name,
|
|
2881
|
+
joins: {},
|
|
2882
|
+
scope: keyed,
|
|
2883
|
+
lock: 'share',
|
|
2884
|
+
})
|
|
2885
|
+
const chain = locked.length === 0 ? null : await chainOf(owner, transaction, String(value))
|
|
2886
|
+
for (let position = 0; position < bound.actions.length; position++) {
|
|
2887
|
+
const action = bound.actions[position] ?? ''
|
|
2888
|
+
const standing = authority.standing?.(path.dimension, action)
|
|
2889
|
+
if (chain === null || standing === undefined || standing.principal !== writer) throw refused(action)
|
|
2890
|
+
if (holdsByGrant(standing, String(value), chain)) continue
|
|
2891
|
+
const holding: RefGrant = {
|
|
2892
|
+
kind: 'ref',
|
|
2893
|
+
dimension: path.dimension,
|
|
2894
|
+
action,
|
|
2895
|
+
principal: writer,
|
|
2896
|
+
id: String(value),
|
|
2897
|
+
chain,
|
|
2898
|
+
relations: unnarrowed(context.relations, standing.relations, action),
|
|
2899
|
+
revealing: standing.revealing,
|
|
2900
|
+
paths: [],
|
|
2901
|
+
}
|
|
2902
|
+
if (!(await holdingRowLocked(transaction, context, holding))) throw refused(action)
|
|
2903
|
+
}
|
|
2904
|
+
}
|
|
2905
|
+
}
|
|
2906
|
+
|
|
2907
|
+
/**
|
|
2908
|
+
* Of `relations`, those no table's `relationWhen` narrows for `action`: a relation that holds the action on some rows only
|
|
2909
|
+
* does not bound a writer who hands it out at a node.
|
|
2910
|
+
*/
|
|
2911
|
+
function unnarrowed(relations: RelationSources, held: readonly RelationHold[], action: string): readonly RelationHold[] {
|
|
2912
|
+
const kept: RelationHold[] = []
|
|
2913
|
+
for (let index = 0; index < held.length; index++) {
|
|
2914
|
+
const hold = held[index]
|
|
2915
|
+
if (hold !== undefined && !includes(knownRelation(relations, hold.relation).narrowed, action)) kept[kept.length] = hold
|
|
2916
|
+
}
|
|
2917
|
+
return kept
|
|
2918
|
+
}
|
|
2919
|
+
|
|
2920
|
+
/** Whether `standing`'s grants hold its action at `node`: everywhere, there, or at a container `chain` places it in. */
|
|
2921
|
+
function holdsByGrant(standing: WithinGrant, node: string, chain: ReadonlyMap<string, string>): boolean {
|
|
2922
|
+
if (standing.values === 'all' || includes(standing.values, node)) {
|
|
2923
|
+
return true
|
|
2924
|
+
}
|
|
2925
|
+
for (let index = 0; index < standing.containers.length; index++) {
|
|
2926
|
+
const container = standing.containers[index]
|
|
2927
|
+
const at = container === undefined ? undefined : chain.get(container.dimension)
|
|
2928
|
+
if (container !== undefined && at !== undefined && includes(container.values, at)) return true
|
|
2929
|
+
}
|
|
2930
|
+
return false
|
|
2931
|
+
}
|
|
1711
2932
|
|
|
1712
2933
|
/** `DimensionTable.insert` over a capability nobody type-checked; the table probe of `@fabrika/db/testing` calls it too. */
|
|
1713
2934
|
export function insertIntoDimension<O>(context: TableContext, run: Runner, target: unknown, values: unknown): Promise<O> {
|
|
1714
2935
|
const prepared = prepareDimensionInsert(context, target, values)
|
|
1715
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2936
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1716
2937
|
}
|
|
1717
2938
|
|
|
1718
2939
|
/** An application table's insert, for an `app` capability of its insert action. */
|
|
1719
2940
|
export function insertIntoApplication<O>(context: TableContext, run: Runner, capability: unknown, values: unknown): Promise<O> {
|
|
1720
2941
|
const prepared = prepareApplicationInsert(context, capability, values)
|
|
1721
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2942
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1722
2943
|
}
|
|
1723
2944
|
|
|
1724
2945
|
/** `ChildTable.insert` over a capability nobody type-checked. */
|
|
1725
2946
|
export function insertIntoChild<O>(context: TableContext, run: Runner, parent: unknown, values: unknown): Promise<O> {
|
|
1726
2947
|
const prepared = prepareChildInsert(context, parent, values)
|
|
1727
|
-
return insertRow(context, run, prepared.row, prepared
|
|
2948
|
+
return insertRow(context, run, prepared.row, prepared)
|
|
1728
2949
|
}
|
|
1729
2950
|
|
|
1730
2951
|
type ReadAction<P, T> = ActionOf<P, T, 'read'>
|
|
@@ -1784,7 +3005,9 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1784
3005
|
/**
|
|
1785
3006
|
* Moves the object to another container: the delete action at the source, the insert action at the target,
|
|
1786
3007
|
* whose chain is checked against the database. Every chain column changes; children that copy them follow
|
|
1787
|
-
* through `ON UPDATE CASCADE` on their composite foreign key.
|
|
3008
|
+
* through `ON UPDATE CASCADE` on their composite foreign key. The moved row is judged by the insert action's
|
|
3009
|
+
* condition and by the `relationWhen` of each relation the target holds through, as an insert into the target is.
|
|
3010
|
+
* Answers the acknowledgement and the new chain.
|
|
1788
3011
|
*/
|
|
1789
3012
|
async move(
|
|
1790
3013
|
ref: Ref<DimensionOf<P, T>, ActionOf<P, T, 'delete'>>,
|
|
@@ -1795,8 +3018,21 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1795
3018
|
if (container === undefined) {
|
|
1796
3019
|
throw new CapabilityError('table_kind', `${context.model.name} has no container to move between`)
|
|
1797
3020
|
}
|
|
1798
|
-
|
|
3021
|
+
if (delegates(context.model)) {
|
|
3022
|
+
throw new CapabilityError(
|
|
3023
|
+
'table_kind',
|
|
3024
|
+
`${context.model.name} hands out access, so a row is never moved: insert a new one`,
|
|
3025
|
+
)
|
|
3026
|
+
}
|
|
3027
|
+
// A move rewrites containment, which a grant at a node a path names gives no standing in: both Refs follow containment.
|
|
1799
3028
|
const target = refGrant(context, to, container.dimension, 'insert')
|
|
3029
|
+
if (refGrant(context, ref, dimensionScope(context.model).dimension, 'delete').paths.length > 0 || target.paths.length > 0) {
|
|
3030
|
+
throw new CapabilityError(
|
|
3031
|
+
'unenforceable',
|
|
3032
|
+
`a Ref held through a secondary path never moves a row of ${context.model.name}: a move follows containment`,
|
|
3033
|
+
)
|
|
3034
|
+
}
|
|
3035
|
+
const scope = objectPredicate(context, ref, 'delete', noPath)
|
|
1800
3036
|
const values = linkValues(context.model.name, context.model.chain, target)
|
|
1801
3037
|
const changes = new Map<string, Primitive | null>()
|
|
1802
3038
|
stampChain(changes, values)
|
|
@@ -1807,7 +3043,16 @@ export class DimensionTable<DB, P, T extends string> {
|
|
|
1807
3043
|
setOwn(chain, entry.link.dimension, entry.value)
|
|
1808
3044
|
}
|
|
1809
3045
|
}
|
|
1810
|
-
const
|
|
3046
|
+
const condition = ownEntry(context.model.when, target.action)
|
|
3047
|
+
const narrowed: NarrowedInsert[] = []
|
|
3048
|
+
for (let index = 0; index < target.relations.length; index++) {
|
|
3049
|
+
const relation = target.relations[index]?.relation ?? ''
|
|
3050
|
+
const narrowing = relationCondition(context.model, relation, target.action)
|
|
3051
|
+
if (narrowing !== undefined && !judgesRelation(narrowed, relation)) narrowed[narrowed.length] = { relation, condition: narrowing }
|
|
3052
|
+
}
|
|
3053
|
+
const judged = condition === undefined ? undefined : { action: target.action, condition }
|
|
3054
|
+
const moved: MovedRow = { destination: target, judged, narrowed }
|
|
3055
|
+
const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, moved)
|
|
1811
3056
|
return { ...acknowledged, chain }
|
|
1812
3057
|
}
|
|
1813
3058
|
|
|
@@ -1910,7 +3155,7 @@ function probeRunner(context: TableContext): { readonly run: Runner; readonly he
|
|
|
1910
3155
|
}
|
|
1911
3156
|
|
|
1912
3157
|
/**
|
|
1913
|
-
* One table's operations without the store types, for `@fabrika/db/testing` only: the
|
|
3158
|
+
* One table's operations without the store types, for `@fabrika/db/testing` only: the policy isolation kit addresses
|
|
1914
3159
|
* a table by name. Every runtime check of a store applies; a child row is addressed by its parent's capability and
|
|
1915
3160
|
* `key`, a dimension row by its capability alone.
|
|
1916
3161
|
*/
|
|
@@ -1938,15 +3183,19 @@ function probeOf(context: TableContext): TableProbe {
|
|
|
1938
3183
|
}
|
|
1939
3184
|
return objectPredicate(context, capability, operation)
|
|
1940
3185
|
}
|
|
3186
|
+
const app = (capability: unknown): boolean => runtimeOf(context.connection).capabilities.resolve(capability).kind === 'app'
|
|
1941
3187
|
// An `app` capability reads every row through ctx.db.app: its rows with appRead, its counts with appCount too.
|
|
1942
3188
|
const list = (capability: unknown, reach: AppReach): OperationNode | undefined => {
|
|
1943
|
-
if (
|
|
3189
|
+
if (app(capability)) {
|
|
1944
3190
|
return appRecordPredicate(context, capability, reach)
|
|
1945
3191
|
}
|
|
1946
3192
|
return child ? childListPredicate(context, capability, 'read') : dimensionListPredicate(context, capability, 'read')
|
|
1947
3193
|
}
|
|
1948
|
-
// A capability reads the columns of its own action, as ctx.db does.
|
|
1949
|
-
const visible = (capability: unknown): readonly string[] =>
|
|
3194
|
+
// A capability reads the columns of its own action, as ctx.db does; an `app` one those its reaching actions read alone.
|
|
3195
|
+
const visible = (capability: unknown): readonly string[] =>
|
|
3196
|
+
app(capability)
|
|
3197
|
+
? visibleThrough(context.model, appRecordRead(context, capability, 'rows').reach)
|
|
3198
|
+
: visibleFor(context.model, heldAction(context, capability))
|
|
1950
3199
|
const { run, held } = probeRunner(context)
|
|
1951
3200
|
return freeze({
|
|
1952
3201
|
mode: child ? 'child' : 'dimension',
|
|
@@ -1957,12 +3206,12 @@ function probeOf(context: TableContext): TableProbe {
|
|
|
1957
3206
|
context,
|
|
1958
3207
|
list(capability, 'rows'),
|
|
1959
3208
|
finishSelect(start, start),
|
|
1960
|
-
|
|
3209
|
+
soleAction(context, capability),
|
|
1961
3210
|
visible(capability),
|
|
1962
3211
|
)
|
|
1963
3212
|
},
|
|
1964
3213
|
group: async (capability: unknown, columns: readonly string[]) =>
|
|
1965
|
-
aggregateRows<Readonly<Record<string,
|
|
3214
|
+
aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(
|
|
1966
3215
|
context,
|
|
1967
3216
|
run,
|
|
1968
3217
|
list(capability, 'rows'),
|
|
@@ -2018,8 +3267,7 @@ function appProbeOf(context: TableContext): TableProbe {
|
|
|
2018
3267
|
mode: 'app',
|
|
2019
3268
|
get: async (capability: unknown, key?: string) => {
|
|
2020
3269
|
if (scoped(capability)) {
|
|
2021
|
-
scopedApplicationRead(context, capability)
|
|
2022
|
-
return selectOne<Readonly<Record<string, unknown>>>(context, run, appKeyPredicate(context.model, key))
|
|
3270
|
+
return selectOne<Readonly<Record<string, unknown>>>(context, run, scopedApplicationRead(context, capability, appKeyPredicate(context.model, key)))
|
|
2023
3271
|
}
|
|
2024
3272
|
return selectOne<Readonly<Record<string, unknown>>>(context, run, appRowPredicate(context, capability, key, 'read'))
|
|
2025
3273
|
},
|
|
@@ -2029,12 +3277,12 @@ function appProbeOf(context: TableContext): TableProbe {
|
|
|
2029
3277
|
context,
|
|
2030
3278
|
every(capability),
|
|
2031
3279
|
finishSelect(start, start),
|
|
2032
|
-
|
|
3280
|
+
soleAction(context, capability),
|
|
2033
3281
|
)
|
|
2034
3282
|
},
|
|
2035
3283
|
count,
|
|
2036
3284
|
group: async (capability: unknown, columns: readonly string[]) =>
|
|
2037
|
-
aggregateRows<Readonly<Record<string,
|
|
3285
|
+
aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
|
|
2038
3286
|
groupBy: columns,
|
|
2039
3287
|
count: true,
|
|
2040
3288
|
}),
|
|
@@ -2068,11 +3316,11 @@ function destinationOf(models: TableModels, model: TableModel, parent: TableMode
|
|
|
2068
3316
|
|
|
2069
3317
|
/** What a select or an aggregate of a capability that reads `visible` may name: those columns, and no join. */
|
|
2070
3318
|
export function actionShape(model: TableModel, visible: readonly string[]): TableShape {
|
|
2071
|
-
return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates })
|
|
3319
|
+
return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates, json: model.json })
|
|
2072
3320
|
}
|
|
2073
3321
|
|
|
2074
3322
|
function shapeOf(model: TableModel, joinable: Readonly<Record<string, JoinShape>>): TableShape {
|
|
2075
|
-
return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates })
|
|
3323
|
+
return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates, json: model.json })
|
|
2076
3324
|
}
|
|
2077
3325
|
|
|
2078
3326
|
function joinShapes(models: TableModels, parent: TableModel): Readonly<Record<string, JoinShape>> {
|
|
@@ -2120,6 +3368,8 @@ export interface ScopedDatabase<DB, P> extends DataLayer {
|
|
|
2120
3368
|
export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
2121
3369
|
const models = tableModels(tables)
|
|
2122
3370
|
const connection: Connection = { runtime: undefined }
|
|
3371
|
+
const layer = layerReach(models)
|
|
3372
|
+
const { relations, members, subqueries } = layer
|
|
2123
3373
|
|
|
2124
3374
|
function contextFor(table: string, mode: 'dimension' | 'child' | 'app'): TableContext {
|
|
2125
3375
|
const model = typeof table === 'string' ? modelOf(models, table) : undefined
|
|
@@ -2131,6 +3381,15 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2131
3381
|
|
|
2132
3382
|
function contextOf(model: TableModel): TableContext {
|
|
2133
3383
|
const parent = model.scope.mode === 'child' ? modelOf(models, model.scope.parent) : undefined
|
|
3384
|
+
const through = model.view && model.scope.mode === 'child' && parent?.scope.mode === 'dimension'
|
|
3385
|
+
? freeze({
|
|
3386
|
+
column: model.scope.column,
|
|
3387
|
+
table: parent.name,
|
|
3388
|
+
key: parent.scope.key,
|
|
3389
|
+
access: viewAccessLinks(model, model.scope.key),
|
|
3390
|
+
context: contextOf(freeze({ ...parent, when: freeze({}), relationWhen: freeze({}) })),
|
|
3391
|
+
})
|
|
3392
|
+
: undefined
|
|
2134
3393
|
const joinable = joinShapes(models, model)
|
|
2135
3394
|
const joins: Record<string, readonly ForeignKeyPair[]> = {}
|
|
2136
3395
|
const children = ownKeys(joinable)
|
|
@@ -2149,6 +3408,13 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2149
3408
|
}
|
|
2150
3409
|
}
|
|
2151
3410
|
const shape = shapeOf(model, joinable)
|
|
3411
|
+
const writers: PathBound[] = []
|
|
3412
|
+
const declared = pathWriters(models, model)
|
|
3413
|
+
for (let index = 0; index < declared.length; index++) {
|
|
3414
|
+
const writer = declared[index]
|
|
3415
|
+
const owner = writer === undefined ? undefined : modelOf(models, writer.path.table)
|
|
3416
|
+
if (writer !== undefined && owner !== undefined) writers[writers.length] = freeze({ ...writer, owner })
|
|
3417
|
+
}
|
|
2152
3418
|
return freeze({
|
|
2153
3419
|
model,
|
|
2154
3420
|
parent,
|
|
@@ -2157,6 +3423,11 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2157
3423
|
joins: freeze(joins),
|
|
2158
3424
|
children: freeze(childModels),
|
|
2159
3425
|
connection,
|
|
3426
|
+
relations,
|
|
3427
|
+
members,
|
|
3428
|
+
subqueries,
|
|
3429
|
+
through,
|
|
3430
|
+
writers: freeze(writers),
|
|
2160
3431
|
})
|
|
2161
3432
|
}
|
|
2162
3433
|
|
|
@@ -2186,6 +3457,20 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2186
3457
|
connection.runtime = bound
|
|
2187
3458
|
return freeze({
|
|
2188
3459
|
locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
|
|
3460
|
+
relates: async (relation: string, node: string, principal: string) =>
|
|
3461
|
+
relationHolds(models, relations, subqueries, bound, relation, node, principal),
|
|
3462
|
+
reveals: async (relation: string, dimension: string, node: string, principal: string, action: string) =>
|
|
3463
|
+
revealHolds(relations, subqueries, bound, relation, dimension, node, principal, action),
|
|
3464
|
+
holdsThrough: async (
|
|
3465
|
+
dimension: string,
|
|
3466
|
+
id: string,
|
|
3467
|
+
action: string,
|
|
3468
|
+
principal: string,
|
|
3469
|
+
relations: readonly RelationHold[],
|
|
3470
|
+
paths: readonly ContainerGrant[],
|
|
3471
|
+
) => heldThroughPaths(models, layer, bound, dimension, id, action, principal, relations, paths),
|
|
3472
|
+
revealsToMembers: async (revealing: string, values: readonly string[], dimension: string, node: string, action: string) =>
|
|
3473
|
+
membersRevealed(members, subqueries, bound, revealing, values, dimension, node, action),
|
|
2189
3474
|
release() {
|
|
2190
3475
|
if (connection.runtime === bound) {
|
|
2191
3476
|
connection.runtime = undefined
|
|
@@ -2199,6 +3484,9 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2199
3484
|
wakes: jobWakes(() => runtimeOf(connection)),
|
|
2200
3485
|
admissions: admissions(() => runtimeOf(connection)),
|
|
2201
3486
|
files: storedFiles(() => runtimeOf(connection)),
|
|
3487
|
+
receipts: requestReceipts(),
|
|
3488
|
+
push: pushSubscriptions(),
|
|
3489
|
+
notifications: notifications(),
|
|
2202
3490
|
}),
|
|
2203
3491
|
data: dataAccess({
|
|
2204
3492
|
models,
|
|
@@ -2218,6 +3506,150 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
|
|
|
2218
3506
|
return database
|
|
2219
3507
|
}
|
|
2220
3508
|
|
|
3509
|
+
/**
|
|
3510
|
+
* Every relation of the layer by name, and the tables a scope predicate's subqueries read (a relation's source by its
|
|
3511
|
+
* node column, a condition path's target by its key), which the guard admits and nothing else.
|
|
3512
|
+
*/
|
|
3513
|
+
function layerReach(
|
|
3514
|
+
models: TableModels,
|
|
3515
|
+
): { readonly relations: RelationSources; readonly members: MemberReveals; readonly subqueries: Readonly<Record<string, readonly string[]>> } {
|
|
3516
|
+
const relations: Record<string, LayerRelation | AccessRelation> = {}
|
|
3517
|
+
const members: Record<string, MemberRevealModel[]> = {}
|
|
3518
|
+
const selected: Record<string, string[]> = {}
|
|
3519
|
+
const select = (table: string, column: string): void => {
|
|
3520
|
+
const columns = ownEntry(selected, table) ?? []
|
|
3521
|
+
if (!includes(columns, column)) columns[columns.length] = column
|
|
3522
|
+
setOwn(selected, table, columns)
|
|
3523
|
+
}
|
|
3524
|
+
const names = ownKeys(models)
|
|
3525
|
+
const reveals: Record<string, RevealModel[]> = {}
|
|
3526
|
+
const narrowed: Record<string, string[]> = {}
|
|
3527
|
+
for (let index = 0; index < names.length; index++) {
|
|
3528
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3529
|
+
const conditioned = model === undefined ? [] : ownKeys(model.relationWhen)
|
|
3530
|
+
for (let position = 0; model !== undefined && position < conditioned.length; position++) {
|
|
3531
|
+
const relation = conditioned[position] ?? ''
|
|
3532
|
+
const conditions = ownEntry(model.relationWhen, relation) ?? {}
|
|
3533
|
+
const actions = ownKeys(conditions)
|
|
3534
|
+
const listed = ownEntry(narrowed, relation) ?? []
|
|
3535
|
+
for (let next = 0; next < actions.length; next++) {
|
|
3536
|
+
const action = actions[next] ?? ''
|
|
3537
|
+
if (!includes(listed, action)) listed[listed.length] = action
|
|
3538
|
+
const condition = ownEntry(conditions, action)
|
|
3539
|
+
if (condition !== undefined) addReach(condition, select)
|
|
3540
|
+
}
|
|
3541
|
+
setOwn(narrowed, relation, listed)
|
|
3542
|
+
}
|
|
3543
|
+
for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
|
|
3544
|
+
const reveal = model.reveals[position]
|
|
3545
|
+
if (reveal === undefined) continue
|
|
3546
|
+
const listed = ownEntry(reveals, reveal.relation) ?? []
|
|
3547
|
+
listed[listed.length] = reveal
|
|
3548
|
+
setOwn(reveals, reveal.relation, listed)
|
|
3549
|
+
select(reveal.table, reveal.column)
|
|
3550
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
3551
|
+
}
|
|
3552
|
+
for (let position = 0; model !== undefined && position < model.memberReveals.length; position++) {
|
|
3553
|
+
const reveal = model.memberReveals[position]
|
|
3554
|
+
if (reveal === undefined) continue
|
|
3555
|
+
const listed = ownEntry(members, reveal.source) ?? []
|
|
3556
|
+
listed[listed.length] = reveal
|
|
3557
|
+
setOwn(members, reveal.source, listed)
|
|
3558
|
+
select(reveal.table, reveal.column)
|
|
3559
|
+
if (reveal.when !== undefined) addReach(reveal.when, select)
|
|
3560
|
+
}
|
|
3561
|
+
}
|
|
3562
|
+
for (let index = 0; index < names.length; index++) {
|
|
3563
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3564
|
+
if (model === undefined) continue
|
|
3565
|
+
for (let position = 0; position < model.confers.length; position++) {
|
|
3566
|
+
const source = model.confers[position]
|
|
3567
|
+
if (source === undefined) continue
|
|
3568
|
+
const revealed = ownEntry(reveals, source.relation) ?? []
|
|
3569
|
+
const placed: Record<string, Readonly<Record<string, string>>> = {}
|
|
3570
|
+
setOwn(placed, model.name, placementOf(model))
|
|
3571
|
+
for (let next = 0; next < revealed.length; next++) {
|
|
3572
|
+
const table = revealed[next]?.table ?? ''
|
|
3573
|
+
const at = modelOf(models, table)
|
|
3574
|
+
if (at !== undefined) setOwn(placed, table, placementOf(at))
|
|
3575
|
+
}
|
|
3576
|
+
setOwn(
|
|
3577
|
+
relations,
|
|
3578
|
+
source.relation,
|
|
3579
|
+
freeze({
|
|
3580
|
+
...source,
|
|
3581
|
+
kind: 'source',
|
|
3582
|
+
reveals: freeze(revealed),
|
|
3583
|
+
narrowed: freeze(ownEntry(narrowed, source.relation) ?? []),
|
|
3584
|
+
placed: freeze(placed),
|
|
3585
|
+
}),
|
|
3586
|
+
)
|
|
3587
|
+
select(source.table, source.node)
|
|
3588
|
+
if (source.principalPath !== undefined) select(source.principalPath.table, source.principalPath.key)
|
|
3589
|
+
if (source.when !== undefined) addReach(source.when, select)
|
|
3590
|
+
}
|
|
3591
|
+
for (let position = 0; position < model.access.length; position++) {
|
|
3592
|
+
const access = model.access[position]
|
|
3593
|
+
if (access === undefined) continue
|
|
3594
|
+
select(access.view, access.row)
|
|
3595
|
+
}
|
|
3596
|
+
for (let position = 0; position < model.readThrough.length; position++) {
|
|
3597
|
+
const path = model.readThrough[position]
|
|
3598
|
+
if (path === undefined) continue
|
|
3599
|
+
select(path.table, path.key)
|
|
3600
|
+
if (path.via !== undefined) select(path.via.table, path.via.key)
|
|
3601
|
+
for (let link = 0; link < path.chain.length; link++) select(path.table, path.chain[link]?.column ?? path.key)
|
|
3602
|
+
}
|
|
3603
|
+
const actions = ownKeys(model.when)
|
|
3604
|
+
for (let position = 0; position < actions.length; position++) {
|
|
3605
|
+
const condition = ownEntry(model.when, actions[position] ?? '')
|
|
3606
|
+
if (condition !== undefined) addReach(condition, select)
|
|
3607
|
+
}
|
|
3608
|
+
}
|
|
3609
|
+
// A relation no table confers is served by the access views alone; a table that confers it adds them to its source.
|
|
3610
|
+
for (let index = 0; index < names.length; index++) {
|
|
3611
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3612
|
+
for (let position = 0; model !== undefined && position < model.access.length; position++) {
|
|
3613
|
+
const access = model.access[position]
|
|
3614
|
+
if (access === undefined || ownEntry(relations, access.relation) !== undefined) continue
|
|
3615
|
+
const relation = access.relation
|
|
3616
|
+
setOwn(
|
|
3617
|
+
relations,
|
|
3618
|
+
relation,
|
|
3619
|
+
freeze({ kind: 'access', relation, dimension: access.dimension, narrowed: freeze(ownEntry(narrowed, relation) ?? []) }),
|
|
3620
|
+
)
|
|
3621
|
+
}
|
|
3622
|
+
}
|
|
3623
|
+
const subqueries: Record<string, readonly string[]> = {}
|
|
3624
|
+
const tablesRead = ownKeys(selected)
|
|
3625
|
+
for (let index = 0; index < tablesRead.length; index++) {
|
|
3626
|
+
const table = tablesRead[index] ?? ''
|
|
3627
|
+
setOwn(subqueries, table, freeze(ownEntry(selected, table) ?? []))
|
|
3628
|
+
}
|
|
3629
|
+
const revealing: Record<string, readonly MemberRevealModel[]> = {}
|
|
3630
|
+
const sources = ownKeys(members)
|
|
3631
|
+
for (let index = 0; index < sources.length; index++) {
|
|
3632
|
+
const source = sources[index] ?? ''
|
|
3633
|
+
setOwn(revealing, source, freeze(ownEntry(members, source) ?? []))
|
|
3634
|
+
}
|
|
3635
|
+
return { relations: freeze(relations), members: freeze(revealing), subqueries: freeze(subqueries) }
|
|
3636
|
+
}
|
|
3637
|
+
|
|
3638
|
+
/** `model`'s column for each dimension a row of it lies at: its key at its own dimension, then each link of its chain. */
|
|
3639
|
+
function placementOf(model: TableModel): Readonly<Record<string, string>> {
|
|
3640
|
+
const placed: Record<string, string> = {}
|
|
3641
|
+
if (model.scope.mode === 'dimension') setOwn(placed, model.scope.dimension, model.scope.key)
|
|
3642
|
+
for (let index = 0; index < model.chain.length; index++) {
|
|
3643
|
+
const link = model.chain[index]
|
|
3644
|
+
if (link !== undefined && ownEntry(placed, link.dimension) === undefined) setOwn(placed, link.dimension, link.column)
|
|
3645
|
+
}
|
|
3646
|
+
return freeze(placed)
|
|
3647
|
+
}
|
|
3648
|
+
|
|
3649
|
+
function addReach(condition: Parameters<typeof conditionReach>[0], select: (table: string, column: string) => void): void {
|
|
3650
|
+
conditionReach(condition, select)
|
|
3651
|
+
}
|
|
3652
|
+
|
|
2221
3653
|
/** The context of `table` in the layer `scoped` created, for the framework's own store builders below. */
|
|
2222
3654
|
function storeContext(database: DataLayer, table: string, mode: 'dimension' | 'child'): TableContext {
|
|
2223
3655
|
const side = frameworkSideOf(database)
|
|
@@ -2260,6 +3692,42 @@ export function ownerOf(models: TableModels, dimension: string): TableModel | un
|
|
|
2260
3692
|
return undefined
|
|
2261
3693
|
}
|
|
2262
3694
|
|
|
3695
|
+
/**
|
|
3696
|
+
* Whether an access view of `relation` lists `node` for `principal`: a guarded select of the row of the table that owns
|
|
3697
|
+
* the relation's dimension, by its key, under the access term. Only a principal-bound view answers; one bound to a
|
|
3698
|
+
* member node lists nothing for a hold anywhere, which is all `relates` asks about.
|
|
3699
|
+
*/
|
|
3700
|
+
async function accessHolds(
|
|
3701
|
+
models: TableModels,
|
|
3702
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3703
|
+
runtime: DataLayerRuntime,
|
|
3704
|
+
relation: string,
|
|
3705
|
+
dimension: string,
|
|
3706
|
+
node: string,
|
|
3707
|
+
principal: string,
|
|
3708
|
+
): Promise<boolean> {
|
|
3709
|
+
const names = ownKeys(models)
|
|
3710
|
+
for (let index = 0; index < names.length; index++) {
|
|
3711
|
+
const model = modelOf(models, names[index] ?? '')
|
|
3712
|
+
if (model === undefined || model.scope.mode !== 'dimension' || model.scope.dimension !== dimension) continue
|
|
3713
|
+
const terms = relationTerms(
|
|
3714
|
+
{ [relation]: freeze({ kind: 'access', relation, dimension, narrowed: freeze([]) }) },
|
|
3715
|
+
model,
|
|
3716
|
+
{ relation, inside: null },
|
|
3717
|
+
principal,
|
|
3718
|
+
'',
|
|
3719
|
+
new Date(),
|
|
3720
|
+
noPath,
|
|
3721
|
+
)
|
|
3722
|
+
if (terms.length === 0) continue
|
|
3723
|
+
const scope = AndNode.create(equals(model.name, keyOf(model), node), anyOf(terms))
|
|
3724
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: model.name, joins: {}, scope, subqueries }
|
|
3725
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(model.name, [keyOf(model)], scope), context)
|
|
3726
|
+
if (rows.length > 0) return true
|
|
3727
|
+
}
|
|
3728
|
+
return false
|
|
3729
|
+
}
|
|
3730
|
+
|
|
2263
3731
|
/** The table that owns `dimension`, which the locator reads; a dimension no table owns is located by nothing. */
|
|
2264
3732
|
function locatedOwner(models: TableModels, dimension: unknown): TableModel {
|
|
2265
3733
|
const owner = typeof dimension === 'string' ? ownerOf(models, dimension) : undefined
|
|
@@ -2269,6 +3737,298 @@ function locatedOwner(models: TableModels, dimension: unknown): TableModel {
|
|
|
2269
3737
|
return owner
|
|
2270
3738
|
}
|
|
2271
3739
|
|
|
3740
|
+
/** One guarded select of a source row naming `principal` at `node` that confers `relation` now. */
|
|
3741
|
+
async function relationHolds(
|
|
3742
|
+
models: TableModels,
|
|
3743
|
+
relations: RelationSources,
|
|
3744
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3745
|
+
runtime: DataLayerRuntime,
|
|
3746
|
+
relation: string,
|
|
3747
|
+
node: string,
|
|
3748
|
+
principal: string,
|
|
3749
|
+
): Promise<boolean> {
|
|
3750
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
3751
|
+
throw new QueryRefusedError('row_address', `a ${relation} row is addressed by its node and its principal, non-empty strings`)
|
|
3752
|
+
}
|
|
3753
|
+
const known = knownRelation(relations, relation)
|
|
3754
|
+
if (known.kind === 'access') {
|
|
3755
|
+
return accessHolds(models, subqueries, runtime, relation, known.dimension, node, principal)
|
|
3756
|
+
}
|
|
3757
|
+
const source = relationSource(relations, relation)
|
|
3758
|
+
const address = allOf([equals(source.table, source.node, node), namesPrincipal(source, principal)])
|
|
3759
|
+
const active = activeRow(source, new Date())
|
|
3760
|
+
const scope = active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active)))
|
|
3761
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: source.table, joins: {}, scope, subqueries }
|
|
3762
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(source.table, [source.node], scope), context)
|
|
3763
|
+
// A relation with a source table may also name access views: the same term answers through them.
|
|
3764
|
+
return rows.length > 0 || accessHolds(models, subqueries, runtime, relation, source.dimension, node, principal)
|
|
3765
|
+
}
|
|
3766
|
+
|
|
3767
|
+
/**
|
|
3768
|
+
* Locks the first row that holds `grant`'s action for its principal at its object or a container on its chain, if any:
|
|
3769
|
+
* a source row naming it there, a row the relation reaches that reveals that node, or a row at a node the Ref's
|
|
3770
|
+
* revealing grants name that reveals it to its members.
|
|
3771
|
+
*/
|
|
3772
|
+
async function holdingRowLocked(transaction: Session, context: TableContext, grant: RefGrant): Promise<boolean> {
|
|
3773
|
+
const now = new Date()
|
|
3774
|
+
const nodeOf = (dimension: string) => (dimension === grant.dimension ? grant.id : grant.chain.get(dimension))
|
|
3775
|
+
const candidates: { table: string; column: string; scope: OperationNode }[] = []
|
|
3776
|
+
for (let index = 0; index < grant.revealing.length; index++) {
|
|
3777
|
+
const revealing = grant.revealing[index]
|
|
3778
|
+
const reveals = revealing === undefined ? [] : ownEntry(context.members, revealing.dimension) ?? []
|
|
3779
|
+
for (let position = 0; revealing !== undefined && position < reveals.length; position++) {
|
|
3780
|
+
const reveal = reveals[position]
|
|
3781
|
+
const held = reveal !== undefined && includes(reveal.actions, grant.action)
|
|
3782
|
+
&& (reveal.path === undefined || includes(reveal.path.writes, grant.action))
|
|
3783
|
+
const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
|
|
3784
|
+
if (reveal === undefined || revealed === undefined || revealing.values.length === 0) continue
|
|
3785
|
+
candidates[candidates.length] = { table: reveal.table, column: reveal.key, scope: memberAddress(reveal, revealing.values, revealed, now) }
|
|
3786
|
+
}
|
|
3787
|
+
}
|
|
3788
|
+
for (let index = 0; index < grant.relations.length; index++) {
|
|
3789
|
+
const hold = grant.relations[index]
|
|
3790
|
+
// An access view's base rows are not the data layer's to lock (ADR-0076): such a hold holds no destination here.
|
|
3791
|
+
if (hold === undefined || knownRelation(context.relations, hold.relation).kind === 'access') continue
|
|
3792
|
+
const source = relationSource(context.relations, hold.relation)
|
|
3793
|
+
const node = nodeOf(source.dimension)
|
|
3794
|
+
const sourceInside = insideRow(source, source.table, hold)
|
|
3795
|
+
if (node !== undefined && sourceInside !== null) {
|
|
3796
|
+
const parts = [equals(source.table, source.node, node), namesPrincipal(source, grant.principal)]
|
|
3797
|
+
if (sourceInside !== undefined) parts[parts.length] = sourceInside
|
|
3798
|
+
const address = allOf(parts)
|
|
3799
|
+
const active = activeRow(source, now)
|
|
3800
|
+
candidates[candidates.length] = {
|
|
3801
|
+
table: source.table,
|
|
3802
|
+
column: source.node,
|
|
3803
|
+
scope: active.length === 0 ? address : AndNode.create(address, ParensNode.create(allOf(active))),
|
|
3804
|
+
}
|
|
3805
|
+
}
|
|
3806
|
+
for (let position = 0; position < source.reveals.length; position++) {
|
|
3807
|
+
const reveal = source.reveals[position]
|
|
3808
|
+
const held = reveal !== undefined && includes(reveal.actions, grant.action)
|
|
3809
|
+
&& (reveal.path === undefined || includes(reveal.path.writes, grant.action))
|
|
3810
|
+
const revealed = reveal === undefined || !held ? undefined : nodeOf(reveal.dimension)
|
|
3811
|
+
const revealInside = reveal === undefined ? null : insideRow(source, reveal.table, hold)
|
|
3812
|
+
if (reveal !== undefined && revealed !== undefined && revealInside !== null) {
|
|
3813
|
+
const address = revealAddress(source, reveal, revealed, grant.principal, now)
|
|
3814
|
+
candidates[candidates.length] = {
|
|
3815
|
+
table: reveal.table,
|
|
3816
|
+
column: reveal.column,
|
|
3817
|
+
scope: revealInside === undefined ? address : allOf([address, revealInside]),
|
|
3818
|
+
}
|
|
3819
|
+
}
|
|
3820
|
+
}
|
|
3821
|
+
}
|
|
3822
|
+
for (let position = 0; position < candidates.length; position++) {
|
|
3823
|
+
const candidate = candidates[position]
|
|
3824
|
+
if (candidate === undefined) continue
|
|
3825
|
+
const rows = await transaction.run(lockNode(candidate.table, candidate.column, candidate.scope), {
|
|
3826
|
+
root: 'SelectQueryNode',
|
|
3827
|
+
table: candidate.table,
|
|
3828
|
+
joins: {},
|
|
3829
|
+
scope: candidate.scope,
|
|
3830
|
+
lock: 'share',
|
|
3831
|
+
subqueries: context.subqueries,
|
|
3832
|
+
})
|
|
3833
|
+
if (rows.length > 0) return true
|
|
3834
|
+
}
|
|
3835
|
+
return false
|
|
3836
|
+
}
|
|
3837
|
+
|
|
3838
|
+
/**
|
|
3839
|
+
* What a row of `table` (the relation's source or a reveal's table) must meet to hold under `hold`: nothing
|
|
3840
|
+
* (`undefined`) for a hold anywhere, its column for the hold's dimension among the hold's values for one inside a node,
|
|
3841
|
+
* and null when it has no such column, so it is not inside and holds nothing.
|
|
3842
|
+
*/
|
|
3843
|
+
function insideRow(source: LayerRelation, table: string, hold: RelationHold): OperationNode | undefined | null {
|
|
3844
|
+
if (hold.inside === null) {
|
|
3845
|
+
return undefined
|
|
3846
|
+
}
|
|
3847
|
+
const placed = ownEntry(source.placed, table)
|
|
3848
|
+
const column = placed === undefined ? undefined : ownEntry(placed, hold.inside.dimension)
|
|
3849
|
+
return column === undefined || hold.inside.values.length === 0 ? null : isIn(table, column, valueList(hold.inside.values))
|
|
3850
|
+
}
|
|
3851
|
+
|
|
3852
|
+
/** `R.<ancestor> = $node and (R.<key> in (values) and <when>)`: a row at a node `values` name that reveals `node` now. */
|
|
3853
|
+
function memberAddress(reveal: MemberRevealModel, values: readonly string[], node: string, now: Date): OperationNode {
|
|
3854
|
+
const named = inList(reveal.table, reveal.key, values)
|
|
3855
|
+
const held = reveal.when === undefined ? named : allOf([named, conditionNode(reveal.table, reveal.when, now)])
|
|
3856
|
+
return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(held))
|
|
3857
|
+
}
|
|
3858
|
+
|
|
3859
|
+
/** `R.<ancestor> = $node and (R.<ancestor> in (<revealed nodes>))`: a row of the reveal's table revealing `node` now. */
|
|
3860
|
+
function revealAddress(source: LayerRelation, reveal: RevealModel, node: string, principal: string, now: Date): OperationNode {
|
|
3861
|
+
const revealed = BinaryOperationNode.create(
|
|
3862
|
+
column(reveal.table, reveal.column),
|
|
3863
|
+
OperatorNode.create('in'),
|
|
3864
|
+
revealedNodes(source, reveal, principal, now),
|
|
3865
|
+
)
|
|
3866
|
+
return AndNode.create(equals(reveal.table, reveal.column, node), ParensNode.create(revealed))
|
|
3867
|
+
}
|
|
3868
|
+
|
|
3869
|
+
/** One guarded select of a row that `relation` reaches for `principal` and that reveals `node` of `dimension` now. */
|
|
3870
|
+
async function revealHolds(
|
|
3871
|
+
relations: RelationSources,
|
|
3872
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3873
|
+
runtime: DataLayerRuntime,
|
|
3874
|
+
relation: string,
|
|
3875
|
+
dimension: string,
|
|
3876
|
+
node: string,
|
|
3877
|
+
principal: string,
|
|
3878
|
+
action: string,
|
|
3879
|
+
): Promise<boolean> {
|
|
3880
|
+
if (typeof node !== 'string' || node.length === 0 || typeof principal !== 'string' || principal.length === 0) {
|
|
3881
|
+
throw new QueryRefusedError('row_address', `a node ${relation} reveals is addressed by its node and its principal, non-empty strings`)
|
|
3882
|
+
}
|
|
3883
|
+
const source = relationSource(relations, relation)
|
|
3884
|
+
for (let index = 0; index < source.reveals.length; index++) {
|
|
3885
|
+
const reveal = source.reveals[index]
|
|
3886
|
+
// A reveal matched through a secondary path holds a Ref's action only where the path holds it (`writeThrough`).
|
|
3887
|
+
if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
|
|
3888
|
+
if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
|
|
3889
|
+
const address = revealAddress(source, reveal, node, principal, new Date())
|
|
3890
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope: address, subqueries }
|
|
3891
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(locateNode(reveal.table, [reveal.column], address), context)
|
|
3892
|
+
if (rows.length > 0) return true
|
|
3893
|
+
}
|
|
3894
|
+
return false
|
|
3895
|
+
}
|
|
3896
|
+
|
|
3897
|
+
/**
|
|
3898
|
+
* Of `values`, nodes of `revealing` at which the caller holds `action`, the ones whose row reveals `node` of `dimension`
|
|
3899
|
+
* for it now: one guarded select per member reveal of `revealing` to `dimension` that lists `action`.
|
|
3900
|
+
*/
|
|
3901
|
+
async function membersRevealed(
|
|
3902
|
+
members: MemberReveals,
|
|
3903
|
+
subqueries: Readonly<Record<string, readonly string[]>>,
|
|
3904
|
+
runtime: DataLayerRuntime,
|
|
3905
|
+
revealing: string,
|
|
3906
|
+
values: readonly string[],
|
|
3907
|
+
dimension: string,
|
|
3908
|
+
node: string,
|
|
3909
|
+
action: string,
|
|
3910
|
+
): Promise<readonly string[]> {
|
|
3911
|
+
if (typeof node !== 'string' || node.length === 0 || !isArray(values) || values.length > MAX_WITHIN_VALUES) {
|
|
3912
|
+
throw new QueryRefusedError('row_address', `a node ${revealing} reveals is addressed by its node and at most ${MAX_WITHIN_VALUES} grants`)
|
|
3913
|
+
}
|
|
3914
|
+
for (let index = 0; index < values.length; index++) {
|
|
3915
|
+
if (typeof values[index] !== 'string' || values[index] === '') {
|
|
3916
|
+
throw new QueryRefusedError('row_address', `a grant at ${revealing} names its node, a non-empty string`)
|
|
3917
|
+
}
|
|
3918
|
+
}
|
|
3919
|
+
const reveals = ownEntry(members, revealing) ?? []
|
|
3920
|
+
const found: string[] = []
|
|
3921
|
+
for (let index = 0; values.length > 0 && index < reveals.length; index++) {
|
|
3922
|
+
const reveal = reveals[index]
|
|
3923
|
+
if (reveal === undefined || reveal.dimension !== dimension || !includes(reveal.actions, action)) continue
|
|
3924
|
+
if (reveal.path !== undefined && !includes(reveal.path.writes, action)) continue
|
|
3925
|
+
const scope = memberAddress(reveal, values, node, new Date())
|
|
3926
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: reveal.table, joins: {}, scope, subqueries }
|
|
3927
|
+
// Grouped, not limited: through a path many rows name one grant's node, and every grant matched is carried.
|
|
3928
|
+
const rows = await sessionOf(runtime).run<Readonly<Record<string, unknown>>>(valuesNode(reveal.table, reveal.key, scope), context)
|
|
3929
|
+
for (let position = 0; position < rows.length; position++) {
|
|
3930
|
+
const key = ownEntry(rows[position] ?? {}, reveal.key)
|
|
3931
|
+
if (typeof key === 'string' && !includes(found, key)) found[found.length] = key
|
|
3932
|
+
}
|
|
3933
|
+
}
|
|
3934
|
+
return freeze(found)
|
|
3935
|
+
}
|
|
3936
|
+
|
|
3937
|
+
/**
|
|
3938
|
+
* Of `relations` and `paths`, the caller's relations and grants of `action` that reach the object `id` of `dimension`
|
|
3939
|
+
* through a relation row, a reveal or a secondary path that holds the action for a `Ref` (`writeThrough`): one guarded
|
|
3940
|
+
* select per candidate. What `on` and `in` mint a `Ref` held through a path with, and through a relation held inside a
|
|
3941
|
+
* node: the statement compares the object's column for the node's dimension with the held values, and the relation
|
|
3942
|
+
* comes back held inside the node that column stores, so every spelling the database equates is one node.
|
|
3943
|
+
*/
|
|
3944
|
+
async function heldThroughPaths(
|
|
3945
|
+
models: TableModels,
|
|
3946
|
+
layer: ReturnType<typeof layerReach>,
|
|
3947
|
+
runtime: DataLayerRuntime,
|
|
3948
|
+
dimension: string,
|
|
3949
|
+
id: string,
|
|
3950
|
+
action: string,
|
|
3951
|
+
principal: string,
|
|
3952
|
+
relations: readonly RelationHold[],
|
|
3953
|
+
paths: readonly ContainerGrant[],
|
|
3954
|
+
): Promise<{ readonly relations: readonly RelationHold[]; readonly paths: readonly ContainerGrant[] }> {
|
|
3955
|
+
const owner = locatedOwner(models, dimension)
|
|
3956
|
+
if (typeof id !== 'string' || id.length === 0 || typeof principal !== 'string' || principal.length === 0 || typeof action !== 'string') {
|
|
3957
|
+
throw new QueryRefusedError('row_address', `a ${dimension} held through a path is addressed by its key, the principal and the action`)
|
|
3958
|
+
}
|
|
3959
|
+
let count = 0
|
|
3960
|
+
const grantOf = (grant: unknown, what: string): ContainerGrant => {
|
|
3961
|
+
const at: unknown = typeof grant === 'object' && grant !== null ? ownDescriptor(grant, 'dimension')?.value : undefined
|
|
3962
|
+
const values = typeof grant === 'object' && grant !== null
|
|
3963
|
+
? parseList(ownDescriptor(grant, 'values')?.value, (value) => {
|
|
3964
|
+
if (typeof value !== 'string' || value === '') throw new QueryRefusedError('row_address', 'a grant names its node, a non-empty string')
|
|
3965
|
+
return value
|
|
3966
|
+
})
|
|
3967
|
+
: undefined
|
|
3968
|
+
if (typeof at !== 'string' || values === undefined) {
|
|
3969
|
+
throw new QueryRefusedError('row_address', `${what} names its dimension and its nodes`)
|
|
3970
|
+
}
|
|
3971
|
+
count += values.length
|
|
3972
|
+
return freeze({ dimension: at, values: freeze(values) })
|
|
3973
|
+
}
|
|
3974
|
+
const named = parseList(relations, (hold): RelationHold => {
|
|
3975
|
+
const relation: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'relation')?.value : undefined
|
|
3976
|
+
const inside: unknown = typeof hold === 'object' && hold !== null ? ownDescriptor(hold, 'inside')?.value : undefined
|
|
3977
|
+
if (typeof relation !== 'string') throw new QueryRefusedError('row_address', 'a relation is named by its name')
|
|
3978
|
+
return freeze({ relation, inside: inside === null ? null : grantOf(inside, 'a relation held inside a node') })
|
|
3979
|
+
})
|
|
3980
|
+
const grants = parseList(paths, (grant): ContainerGrant => grantOf(grant, 'a grant of a path'))
|
|
3981
|
+
if (named === undefined || grants === undefined) {
|
|
3982
|
+
throw new QueryRefusedError('row_address', 'the candidates of a path are plain arrays')
|
|
3983
|
+
}
|
|
3984
|
+
if (count > MAX_WITHIN_VALUES) {
|
|
3985
|
+
throw new QueryRefusedError('row_address', `the grants of a path carry at most ${MAX_WITHIN_VALUES} nodes`)
|
|
3986
|
+
}
|
|
3987
|
+
const now = new Date()
|
|
3988
|
+
const session = sessionOf(runtime)
|
|
3989
|
+
const reached = async (
|
|
3990
|
+
terms: readonly OperationNode[],
|
|
3991
|
+
column: string,
|
|
3992
|
+
inside?: readonly string[],
|
|
3993
|
+
): Promise<Readonly<Record<string, unknown>> | undefined> => {
|
|
3994
|
+
if (terms.length === 0) return undefined
|
|
3995
|
+
const found = AndNode.create(equals(owner.name, keyOf(owner), id), anyOf(terms))
|
|
3996
|
+
// A member-bound access term is not narrowed to the node (ADR-0076): the object's own column is, as the database compares it.
|
|
3997
|
+
const scope = inside === undefined ? found : AndNode.create(found, ParensNode.create(isIn(owner.name, column, valueList(inside))))
|
|
3998
|
+
const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope, subqueries: layer.subqueries }
|
|
3999
|
+
const columns = column === keyOf(owner) ? [column] : [keyOf(owner), column]
|
|
4000
|
+
const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
|
|
4001
|
+
return row
|
|
4002
|
+
}
|
|
4003
|
+
const held: RelationHold[] = []
|
|
4004
|
+
for (let index = 0; index < named.length; index++) {
|
|
4005
|
+
const hold = named[index]
|
|
4006
|
+
if (hold === undefined) continue
|
|
4007
|
+
const column = hold.inside === null ? keyOf(owner) : nodeColumnOf(owner, hold.inside.dimension)
|
|
4008
|
+
const row = column === undefined
|
|
4009
|
+
? undefined
|
|
4010
|
+
: await reached(relationTerms(layer.relations, owner, hold, principal, action, now, heldThrough(action)), column, hold.inside?.values)
|
|
4011
|
+
if (row === undefined || column === undefined) continue
|
|
4012
|
+
if (hold.inside === null) {
|
|
4013
|
+
held[held.length] = hold
|
|
4014
|
+
continue
|
|
4015
|
+
}
|
|
4016
|
+
const node = ownEntry(row, column)
|
|
4017
|
+
if (typeof node !== 'string') {
|
|
4018
|
+
throw new PolicyError(`${owner.name}.${column} came back as ${typeof node}; a containment column holds its scope value as text`)
|
|
4019
|
+
}
|
|
4020
|
+
held[held.length] = freeze({ relation: hold.relation, inside: freeze({ dimension: hold.inside.dimension, values: freeze([node]) }) })
|
|
4021
|
+
}
|
|
4022
|
+
const through: ContainerGrant[] = []
|
|
4023
|
+
for (let index = 0; index < grants.length; index++) {
|
|
4024
|
+
const grant = grants[index]
|
|
4025
|
+
if (grant !== undefined && (await reached(pathTerms(owner, [grant], heldThrough(action)), keyOf(owner))) !== undefined) {
|
|
4026
|
+
through[through.length] = grant
|
|
4027
|
+
}
|
|
4028
|
+
}
|
|
4029
|
+
return freeze({ relations: freeze(held), paths: freeze(through) })
|
|
4030
|
+
}
|
|
4031
|
+
|
|
2272
4032
|
/** One guarded select by key of the containment columns the policy declares; the generated locator of the dimension. */
|
|
2273
4033
|
async function locateObject(
|
|
2274
4034
|
models: TableModels,
|
|
@@ -2281,6 +4041,11 @@ async function locateObject(
|
|
|
2281
4041
|
if (typeof id !== 'string' || id.length === 0) {
|
|
2282
4042
|
throw new QueryRefusedError('row_address', `a ${dimension} is located by its ${keyOf(owner)}, a non-empty string`)
|
|
2283
4043
|
}
|
|
4044
|
+
return chainOf(owner, using ?? sessionOf(runtime), id)
|
|
4045
|
+
}
|
|
4046
|
+
|
|
4047
|
+
/** The containers of `owner`'s row keyed `id`, by dimension, read in `session`; `null` for no such row. */
|
|
4048
|
+
async function chainOf(owner: TableModel, session: Session, id: string): Promise<ReadonlyMap<string, string> | null> {
|
|
2284
4049
|
const key = keyOf(owner)
|
|
2285
4050
|
const scope = equals(owner.name, key, id)
|
|
2286
4051
|
const columns: string[] = [key]
|
|
@@ -2288,7 +4053,7 @@ async function locateObject(
|
|
|
2288
4053
|
columns[columns.length] = owner.chain[index]?.column ?? ''
|
|
2289
4054
|
}
|
|
2290
4055
|
const context: GuardContext = { root: 'SelectQueryNode', table: owner.name, joins: {}, scope }
|
|
2291
|
-
const [row] = await
|
|
4056
|
+
const [row] = await session.run<Readonly<Record<string, unknown>>>(locateNode(owner.name, columns, scope), context)
|
|
2292
4057
|
if (row === undefined) {
|
|
2293
4058
|
return null
|
|
2294
4059
|
}
|