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