@fabrika/db 0.9.0-dev.12 → 0.9.0-dev.14

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/src/policy.ts CHANGED
@@ -8,16 +8,24 @@ import {
8
8
  type NameSet,
9
9
  nameSet,
10
10
  namesOf,
11
- OBJECT_PROTOTYPE,
12
- ownDescriptor,
13
11
  ownEntry,
14
12
  ownKeys,
15
- ownNames,
16
- ownSymbols,
17
13
  parseList,
18
- prototypeOf,
14
+ plainRecord,
19
15
  setOwn,
20
16
  } from './builtins'
17
+ import {
18
+ type ConditionHop,
19
+ type ConditionModel,
20
+ type ConditionPolicy,
21
+ conditionReach,
22
+ type ConditionTable,
23
+ type HopRule,
24
+ insertProblem,
25
+ parseCondition,
26
+ singleForeignKey,
27
+ splitPath,
28
+ } from './conditions'
21
29
  import { PolicyError } from './errors'
22
30
  import { isPlainIdentifier } from './identifier'
23
31
  import type { Unavailable } from './orm-types'
@@ -91,6 +99,98 @@ interface WritablePolicy<Col extends string, A extends string, V extends Col, Ac
91
99
  * file reference. The table's actions are the file's authority.
92
100
  */
93
101
  readonly files?: FilePolicies<Col>
102
+ /** The relations this table's rows confer (`relations` of the vocabulary): each row holds one principal at one node. */
103
+ readonly confers?: { readonly [relation: string]: ConfersPolicy<Col> }
104
+ /** Conditions that narrow an action of this table: a row the condition does not admit is out of that action's reach. */
105
+ readonly when?: { readonly [action in A]?: ConditionPolicy<Col> }
106
+ /**
107
+ * Relation → action → a condition on the rows that relation reaches for that action: it narrows the relation's terms
108
+ * only, never an IAM grant, a member reveal or a path grant of the action.
109
+ */
110
+ readonly relationWhen?: { readonly [relation: string]: { readonly [action in A]?: ConditionPolicy<Col> } }
111
+ /** Relation of this table's own dimension, or of one it reads through → the ancestor node a row the relation reaches reveals. */
112
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
113
+ /**
114
+ * Dimension outside the chain → the foreign key column a read reaches a row through: a `Within` of the dimension, or a
115
+ * relation at it, reads the row, and every write follows containment only. No update writes the column. Or
116
+ * `<nearest container column>.<its column>`: the row is read through its nearest container's own read path.
117
+ */
118
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
119
+ /**
120
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds on the table's rows, writes included:
121
+ * a grant of one of them at the node the path names, or above it, reaches the row for that action. Whoever inserts
122
+ * the path's column must hold every listed action at the node it names.
123
+ */
124
+ readonly writeThrough?: { readonly [dimension: string]: readonly A[] }
125
+ /**
126
+ * This table's own dimension, or one it reads through (`readThrough`) → the ancestor node a row reveals to its
127
+ * members: a grant of one of `actions` at the row's own node, or at the node its path names, holds that action at its
128
+ * node in `to` too, while `when` admits the row.
129
+ */
130
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
131
+ /**
132
+ * Relation → an access view that lists the rows the relation reaches: the escape path for a rule no structured
133
+ * declaration expresses. The view's SQL decides; the layer binds only the caller's principal and the nodes it holds
134
+ * the relation inside, never a handler value.
135
+ */
136
+ readonly access?: { readonly [relation: string]: AccessPolicy }
137
+ }
138
+
139
+ /** An access view: `row` names this table's key; `principal` is compared to the caller, `member` to the nodes it holds the relation inside. */
140
+ export interface AccessPolicy {
141
+ readonly view: string
142
+ readonly row: string
143
+ readonly principal?: string
144
+ readonly member?: string
145
+ }
146
+
147
+ /** What a row reveals to a caller with a grant at its node: its node in `to`, for `actions`, while `when` admits the row. */
148
+ export interface MemberRevealsPolicy<Col extends string, A extends string> {
149
+ readonly to: string
150
+ readonly actions: readonly A[]
151
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
152
+ readonly when?: ConditionPolicy<Col>
153
+ /** Through a path, on a table with an insert action: the writer picks the node, and `self` lets it pick its own. */
154
+ readonly assign?: { readonly self?: true }
155
+ }
156
+
157
+ /**
158
+ * A row of the table that a relation reaches reveals its node in `to`, an ancestor dimension of its chain: the relation
159
+ * then holds `actions` (those of them its roles list in `via`) there, while `when` admits the row.
160
+ */
161
+ export interface RevealsPolicy<Col extends string, A extends string> {
162
+ readonly to: string
163
+ readonly actions: readonly A[]
164
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
165
+ readonly when?: ConditionPolicy<Col>
166
+ /**
167
+ * Required on a reveal matched through `readThrough` of a table with an insert action: the row's writer picks the node,
168
+ * so an insert delegates. Without `self`, an insert that names a node where its writer holds the relation is refused.
169
+ */
170
+ readonly assign?: { readonly self?: true }
171
+ }
172
+
173
+ /**
174
+ * A relation source: each row says that the principal in `principal` stands in the relation to the node `node` holds,
175
+ * until `expires` (none: no deadline) and while `when` admits the row. Writing a row is delegation.
176
+ */
177
+ export interface ConfersPolicy<Col extends string> {
178
+ /**
179
+ * The column that holds the principal, or `<column>.<principal column>`: one foreign key of the table into the key of
180
+ * the table whose column holds it. The table's `createdBy` names the row's writer (it needs `assign.self`).
181
+ */
182
+ readonly principal: Col | `${Col}.${string}`
183
+ /** The column that names the node; by default the table's column for the relation's dimension (its key or its chain). */
184
+ readonly node?: Col
185
+ /** A timestamp column: the row confers nothing once it passed. */
186
+ readonly expires?: Col
187
+ /** A condition on the row's own columns (no foreign-key path): `{ revoked_at: { isNull: true } }`. */
188
+ readonly when?: ConditionPolicy<Col>
189
+ /**
190
+ * Inserting a row delegates the relation's actions to its principal, bounded by the inserting Ref's node: at most
191
+ * `maxDays` ahead (which needs `expires`), and to the inserting principal itself only with `self`.
192
+ */
193
+ readonly assign?: { readonly maxDays?: number; readonly self?: true }
94
194
  }
95
195
 
96
196
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
@@ -164,6 +264,11 @@ export interface TableColumns<Col extends string = string, Table extends string
164
264
  readonly booleans?: readonly Col[]
165
265
  /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
166
266
  readonly json?: readonly Col[]
267
+ /**
268
+ * The columns declared NOT NULL; absent when none. A foreign key that holds a row's tenant needs its ancestor columns
269
+ * among them: under MATCH SIMPLE a null in one skips the whole key.
270
+ */
271
+ readonly notNull?: readonly Col[]
167
272
  /** A view: read-only, with no foreign key; absent for a table. */
168
273
  readonly view?: true
169
274
  }
@@ -231,6 +336,8 @@ export interface TableModel {
231
336
  readonly booleans: NameSet
232
337
  /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
233
338
  readonly json: NameSet
339
+ /** The columns the column list declares NOT NULL. */
340
+ readonly notNull: NameSet
234
341
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
235
342
  readonly foreignKeys: readonly ForeignKey[]
236
343
  /** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
@@ -240,6 +347,122 @@ export interface TableModel {
240
347
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
241
348
  */
242
349
  readonly chain: readonly Container[]
350
+ /** The relations this table's rows confer, each with its columns, its condition and its delegation bound. */
351
+ readonly confers: readonly RelationSource[]
352
+ /** The condition each action of the table holds a row under; an action without one is not narrowed. */
353
+ readonly when: Readonly<Record<string, ConditionModel>>
354
+ /** Relation → action → the condition the rows that relation reaches hold for that action under; ANDed onto its terms only. */
355
+ readonly relationWhen: Readonly<Record<string, Readonly<Record<string, ConditionModel>>>>
356
+ /** The ancestor nodes this table's rows reveal to a relation of its own dimension or of one it reads through. */
357
+ readonly reveals: readonly RevealModel[]
358
+ /** The secondary read paths: a dimension outside the chain, by the column that holds the row's node in it. */
359
+ readonly readThrough: readonly SecondaryPath[]
360
+ /** The ancestor nodes this table's rows reveal to a grant at their own node. */
361
+ readonly memberReveals: readonly MemberRevealModel[]
362
+ /** The access views of the relations whose reach a view's SQL decides. */
363
+ readonly access: readonly AccessModel[]
364
+ }
365
+
366
+ /** A relation's access view over this table: `T.<key> in (select V.<row> from V where <bindings>)`. */
367
+ export interface AccessModel {
368
+ readonly relation: string
369
+ /** The relation's dimension: a hold inside a node of it alone binds `member`. */
370
+ readonly dimension: string
371
+ readonly view: string
372
+ readonly row: string
373
+ readonly principal: string | undefined
374
+ readonly member: string | undefined
375
+ }
376
+
377
+ /**
378
+ * A read path to a dimension outside the chain: `column` holds a key of `table`, which owns `dimension` and lies in
379
+ * `chain`. The column's foreign key covers every ancestor the two chains share, so the node lies in the row's own tenant.
380
+ */
381
+ export interface SecondaryPath {
382
+ readonly dimension: string
383
+ readonly column: string
384
+ readonly table: string
385
+ readonly key: string
386
+ readonly chain: readonly Container[]
387
+ /**
388
+ * The nearest container whose own path this is: the row's `column` of it, its `table` and `key`. `column` above is
389
+ * then the container's column, and the path is read as `T.<via column> in (select C.<key> from C where …)`.
390
+ */
391
+ readonly via: ContainerHop | undefined
392
+ /** The actions a `Ref` held through the path holds on the table's rows (`writeThrough`); a `Within` reads through every path. */
393
+ readonly writes: readonly string[]
394
+ }
395
+
396
+ /** The row's nearest containment column, and the table and key it names. */
397
+ export interface ContainerHop {
398
+ readonly column: string
399
+ readonly table: string
400
+ readonly key: string
401
+ }
402
+
403
+ /**
404
+ * A row of `table` that `relation` reaches reveals its node in `dimension`, held in `column`: the relation holds
405
+ * `actions` at that node while `when` admits the row.
406
+ */
407
+ export interface RevealModel {
408
+ readonly relation: string
409
+ readonly table: string
410
+ /** The table's key, which the relation's nodes match unless the reveal is matched through `path`. */
411
+ readonly key: string
412
+ /**
413
+ * The secondary path whose node, or an ancestor of it, the relation's nodes match. A reveal matched through one holds
414
+ * a `Ref` of an action only where the path does (`writeThrough`).
415
+ */
416
+ readonly path: SecondaryPath | undefined
417
+ /** The bound on an insert's delegation through `path`: `undefined` when no handler inserts a row of the table. */
418
+ readonly assign: { readonly self: boolean } | undefined
419
+ readonly dimension: string
420
+ readonly column: string
421
+ readonly actions: readonly string[]
422
+ readonly when: ConditionModel | undefined
423
+ }
424
+
425
+ /**
426
+ * A row of `table`, a node of `source` (its own dimension, keyed by `key`), reveals its node in `dimension`, held in
427
+ * `column`: a grant of one of `actions` at the row's node holds the action there too, for a `Within`'s reads, while
428
+ * `when` admits the row. Only a grant at the node itself counts, never one at a container of it: an insert would
429
+ * otherwise reveal the ancestor to the container's members at once.
430
+ */
431
+ export interface MemberRevealModel {
432
+ readonly source: string
433
+ readonly table: string
434
+ /** The column a grant's nodes match: the table's key, or `path`'s column. */
435
+ readonly key: string
436
+ /** The secondary path whose node a grant names; a `Ref` holds an action through it only where the path does. */
437
+ readonly path: SecondaryPath | undefined
438
+ /** The bound on an insert's pick of the node through `path`: `undefined` when no handler inserts a row of the table. */
439
+ readonly assign: { readonly self: boolean } | undefined
440
+ readonly dimension: string
441
+ readonly column: string
442
+ readonly actions: readonly string[]
443
+ readonly when: ConditionModel | undefined
444
+ }
445
+
446
+ /** One relation's source table: what a relation term reads, and what a write of its rows is bounded by. */
447
+ export interface RelationSource {
448
+ readonly relation: string
449
+ readonly dimension: string
450
+ readonly table: string
451
+ /** The source's column that decides the principal: it holds it, or it references the row of `principalPath` that does. */
452
+ readonly principal: string
453
+ readonly principalPath: PrincipalPath | undefined
454
+ readonly node: string
455
+ readonly expires: string | undefined
456
+ readonly when: ConditionModel | undefined
457
+ /** `undefined` when the table has no insert action, so no handler writes a row of it. */
458
+ readonly assign: { readonly maxDays: number | undefined; readonly self: boolean } | undefined
459
+ }
460
+
461
+ /** `S.<principal>` references `key` of `table`, whose `column` holds the principal the source row names. */
462
+ export interface PrincipalPath {
463
+ readonly table: string
464
+ readonly key: string
465
+ readonly column: string
243
466
  }
244
467
 
245
468
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -253,7 +476,19 @@ type ParsedScope =
253
476
  readonly inherit: readonly string[] | undefined
254
477
  }
255
478
 
256
- type ParsedTable = Omit<TableModel, 'chain' | 'scope'> & { readonly scope: ParsedScope }
479
+ type ParsedTable =
480
+ & Omit<TableModel, 'chain' | 'scope' | 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
481
+ & {
482
+ readonly scope: ParsedScope
483
+ readonly confersInput: unknown
484
+ readonly whenInput: unknown
485
+ readonly relationWhenInput: unknown
486
+ readonly revealsInput: unknown
487
+ readonly readThroughInput: unknown
488
+ readonly writeThroughInput: unknown
489
+ readonly memberRevealsInput: unknown
490
+ readonly accessInput: unknown
491
+ }
257
492
 
258
493
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
259
494
  let hasModels: (value: object) => boolean = () => false
@@ -326,8 +561,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
326
561
  interface VocabularyModel {
327
562
  readonly dimensions: Containment
328
563
  readonly actions: NameSet
564
+ /** Each relation of the vocabulary, by name, with the dimension its nodes are of. */
565
+ readonly relations: Readonly<Record<string, string>>
329
566
  }
330
567
 
568
+ /** A relation's name: it travels in a token's pseudo-scope `~rel:<name>`, so it is a plain word. */
569
+ const RELATION_NAME = /^[a-z][A-Za-z0-9]*$/
570
+
331
571
  function parseVocabulary(input: unknown): VocabularyModel {
332
572
  const vocabulary = plainRecord(input, 'the vocabulary')
333
573
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -351,12 +591,54 @@ function parseVocabulary(input: unknown): VocabularyModel {
351
591
  }
352
592
  }
353
593
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
354
- return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
594
+ const relationsInput = ownEntry(vocabulary, 'relations')
595
+ const relations: Record<string, string> = {}
596
+ if (relationsInput !== undefined) {
597
+ const declared = plainRecord(relationsInput, 'the vocabulary relations')
598
+ const relationNames = ownKeys(declared)
599
+ for (let index = 0; index < relationNames.length; index++) {
600
+ const relation = relationNames[index] ?? ''
601
+ if (!RELATION_NAME.test(relation)) {
602
+ throw new PolicyError(`the vocabulary relation ${relation}: a relation name must match ${RELATION_NAME.source}`)
603
+ }
604
+ const dimension = ownEntry(plainRecord(ownEntry(declared, relation), `the vocabulary relation ${relation}`), 'dimension')
605
+ if (typeof dimension !== 'string' || !hasOwn(dimensions, dimension)) {
606
+ throw new PolicyError(`the vocabulary relation ${relation} is of ${String(dimension)}, which is not one of its dimensions`)
607
+ }
608
+ setOwn(relations, relation, dimension)
609
+ }
610
+ }
611
+ return freeze({ dimensions: freeze(containment), actions: nameSet(actions), relations: freeze(relations) })
355
612
  }
356
613
 
357
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'view'])
614
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
358
615
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
359
- const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
616
+ const POLICY_FIELDS = nameSet([
617
+ 'scope',
618
+ 'actions',
619
+ 'insert',
620
+ 'update',
621
+ 'version',
622
+ 'createdBy',
623
+ 'columns',
624
+ 'queue',
625
+ 'files',
626
+ 'confers',
627
+ 'when',
628
+ 'relationWhen',
629
+ 'reveals',
630
+ 'readThrough',
631
+ 'writeThrough',
632
+ 'memberReveals',
633
+ 'access',
634
+ ])
635
+ const REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
636
+ const MEMBER_REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
637
+ const REVEAL_ASSIGN_FIELDS = nameSet(['self'])
638
+ const CONFERS_FIELDS = nameSet(['principal', 'node', 'expires', 'when', 'assign'])
639
+ const ASSIGN_FIELDS = nameSet(['maxDays', 'self'])
640
+ /** A delegated row lasts at most ten years ahead: a bound, not a convenience. */
641
+ const MAX_ASSIGN_DAYS = 3650
360
642
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
361
643
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
362
644
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -366,25 +648,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
366
648
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
367
649
  const COLUMN_FIELDS = nameSet(['read', 'write'])
368
650
 
369
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
370
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
371
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
372
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
373
- throw new PolicyError(`${what} must be a plain object`)
374
- }
375
- const copy: Record<string, unknown> = {}
376
- const keys = ownNames(value)
377
- for (let index = 0; index < keys.length; index++) {
378
- const key = keys[index] ?? ''
379
- const descriptor = ownDescriptor(value, key)
380
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
381
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
382
- }
383
- setOwn(copy, key, descriptor.value)
384
- }
385
- return freeze(copy)
386
- }
387
-
388
651
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
389
652
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
390
653
  const keys = ownKeys(record)
@@ -408,10 +671,15 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
408
671
  }
409
672
  }
410
673
  const parsed: ParsedTable[] = []
674
+ const views: Record<string, ViewColumns> = {}
411
675
  for (let index = 0; index < tables.length; index++) {
412
676
  const table = tables[index] ?? ''
413
677
  const policy = ownEntry(policies, table)
414
678
  const entry = ownEntry(columns, table)
679
+ if (isViewEntry(table, entry)) {
680
+ const names = parseList(ownEntry(plainRecord(entry, `${table}: the column list entry`), 'columns'), (name) => String(name))
681
+ setOwn(views, table, freeze({ columns: nameSet(names ?? []), policy: policy !== undefined }))
682
+ }
415
683
  // A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
416
684
  if (policy === undefined && isViewEntry(table, entry)) {
417
685
  continue
@@ -421,7 +689,7 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
421
689
  }
422
690
  parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
423
691
  }
424
- return linkTables(parsed, vocabulary.dimensions)
692
+ return linkTables(parsed, vocabulary, views)
425
693
  }
426
694
 
427
695
  /** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
@@ -568,6 +836,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
568
836
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
569
837
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
570
838
  const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
839
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
571
840
  const queue = queueInput === undefined
572
841
  ? undefined
573
842
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -597,8 +866,17 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
597
866
  timestamps,
598
867
  booleans,
599
868
  json,
869
+ notNull,
600
870
  foreignKeys,
601
871
  view,
872
+ confersInput: ownEntry(policy, 'confers'),
873
+ whenInput: ownEntry(policy, 'when'),
874
+ relationWhenInput: ownEntry(policy, 'relationWhen'),
875
+ revealsInput: ownEntry(policy, 'reveals'),
876
+ readThroughInput: ownEntry(policy, 'readThrough'),
877
+ writeThroughInput: ownEntry(policy, 'writeThrough'),
878
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
879
+ accessInput: ownEntry(policy, 'access'),
602
880
  }
603
881
  }
604
882
 
@@ -720,7 +998,10 @@ function parseQueue(
720
998
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
721
999
  }
722
1000
 
723
- /** The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`) or JSON (`json`) columns, each one of the table's. */
1001
+ /**
1002
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
1003
+ * (`notNull`) columns, each one of the table's.
1004
+ */
724
1005
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
725
1006
  if (input === undefined) {
726
1007
  return nameSet([])
@@ -1073,7 +1354,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1073
1354
  }
1074
1355
 
1075
1356
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1076
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1357
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel, views: Readonly<Record<string, ViewColumns>>): TableModels {
1358
+ const containment = vocabulary.dimensions
1077
1359
  const byName: Record<string, ParsedTable> = {}
1078
1360
  const owners: Record<string, ParsedTable> = {}
1079
1361
  for (let index = 0; index < parsed.length; index++) {
@@ -1123,17 +1405,1226 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1123
1405
  return result
1124
1406
  }
1125
1407
 
1408
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1409
+ const linkedTable = (name: string): LinkedTable | undefined => {
1410
+ const target = ownEntry(byName, name)
1411
+ if (target === undefined) return undefined
1412
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, ...rest } = target
1413
+ return { ...rest, ...resolve(target, []) }
1414
+ }
1415
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1416
+ const source = ownEntry(byName, from)
1417
+ const target = ownEntry(byName, to)
1418
+ if (target?.scope.mode === 'reference') {
1419
+ return !backward
1420
+ }
1421
+ if (source === undefined || target === undefined) {
1422
+ return false
1423
+ }
1424
+ const into = resolve(target, [])
1425
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1426
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1427
+ return false
1428
+ }
1429
+ const scope = resolve(source, []).scope
1430
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1431
+ if (
1432
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1433
+ && into.scope.dimension === scope.container.dimension
1434
+ ) {
1435
+ return true
1436
+ }
1437
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1438
+ return true
1439
+ }
1440
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1441
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1442
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1443
+ return false
1444
+ }
1445
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1446
+ return true
1447
+ }
1448
+ const sources: Record<string, string> = {}
1449
+ const viewed: Record<string, string> = {}
1126
1450
  const models: Record<string, TableModel> = {}
1127
1451
  for (let index = 0; index < parsed.length; index++) {
1128
1452
  const table = parsed[index]
1129
1453
  if (table !== undefined) {
1130
1454
  const { scope, chain } = resolve(table, [])
1131
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1455
+ const { confersInput, whenInput, relationWhenInput, revealsInput, readThroughInput, writeThroughInput, memberRevealsInput, accessInput, ...rest } =
1456
+ table
1457
+ const linked = { ...rest, scope, chain }
1458
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1459
+ const owner = ownEntry(owners, dimension)
1460
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1461
+ }
1462
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1463
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1464
+ const declared = ownEntry(byName, container)?.readThroughInput
1465
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1466
+ const target = linkedTable(container)
1467
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1468
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1469
+ }
1470
+ const readThrough = parseWriteThrough(
1471
+ linked,
1472
+ parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath),
1473
+ writeThroughInput,
1474
+ vocabulary,
1475
+ )
1476
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1477
+ for (let position = 0; position < confers.length; position++) {
1478
+ const relation = confers[position]?.relation ?? ''
1479
+ const earlier = ownEntry(sources, relation)
1480
+ if (earlier !== undefined) {
1481
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1482
+ }
1483
+ setOwn(sources, relation, table.name)
1484
+ }
1485
+ const root = conditionRoot(linked, byName)
1486
+ const when = parseWhen(linked, root, whenInput, conditionTable, hopRule)
1487
+ const relationWhen = parseRelationWhen(linked, root, relationWhenInput, vocabulary, conditionTable, hopRule)
1488
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1489
+ const memberReveals = parseMemberReveals(linked, readThrough, memberRevealsInput, vocabulary, conditionTable, hopRule)
1490
+ const access = parseAccess(linked, accessInput, vocabulary, views)
1491
+ for (let position = 0; position < access.length; position++) {
1492
+ const relation = access[position]?.relation ?? ''
1493
+ if (!hasOwn(viewed, relation)) setOwn(viewed, relation, table.name)
1494
+ }
1495
+ setOwn(models, table.name, freeze({ ...linked, confers, when, relationWhen, reveals, readThrough, memberReveals, access }))
1132
1496
  }
1133
1497
  }
1498
+ checkRelationWhenReach(models, vocabulary)
1499
+ const relations = ownKeys(vocabulary.relations)
1500
+ for (let index = 0; index < relations.length; index++) {
1501
+ const relation = relations[index] ?? ''
1502
+ if (!hasOwn(sources, relation) && !hasOwn(viewed, relation)) {
1503
+ throw new PolicyError(
1504
+ `the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it, or name an access view for it`,
1505
+ )
1506
+ }
1507
+ }
1508
+ checkRevealSources(models, sources)
1134
1509
  return freeze(models)
1135
1510
  }
1136
1511
 
1512
+ /** A reveal is matched through the relation's source rows, so a relation that access views alone serve reveals nothing. */
1513
+ function checkRevealSources(models: Readonly<Record<string, TableModel>>, sources: Readonly<Record<string, string>>): void {
1514
+ const tables = ownKeys(models)
1515
+ for (let index = 0; index < tables.length; index++) {
1516
+ const model = ownEntry(models, tables[index] ?? '')
1517
+ const reveals = model?.reveals ?? []
1518
+ for (let position = 0; position < reveals.length; position++) {
1519
+ const relation = reveals[position]?.relation ?? ''
1520
+ if (model !== undefined && !hasOwn(sources, relation)) {
1521
+ throw new PolicyError(
1522
+ `${model.name}: reveals.${relation} is matched through the rows that confer it, and only access views serve it; declare confers.${relation}`,
1523
+ )
1524
+ }
1525
+ }
1526
+ }
1527
+ }
1528
+
1529
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'relationWhen' | 'reveals' | 'readThrough' | 'memberReveals' | 'access'>
1530
+
1531
+ /** A view of the column list: its columns, and whether a policy makes it a table of the layer. */
1532
+ interface ViewColumns {
1533
+ readonly columns: NameSet
1534
+ readonly policy: boolean
1535
+ }
1536
+
1537
+ const ACCESS_FIELDS = nameSet(['view', 'row', 'principal', 'member'])
1538
+
1539
+ /**
1540
+ * `access`: relation → the view whose rows name the table's rows the relation reaches. The view is one the column list
1541
+ * marks, `row` and each binding are its columns, and at least one binding is stated, so the subquery never reads every
1542
+ * row: `principal` is compared to the caller, `member` to the nodes of the relation's dimension it holds the relation in.
1543
+ */
1544
+ function parseAccess(
1545
+ table: LinkedTable,
1546
+ input: unknown,
1547
+ vocabulary: VocabularyModel,
1548
+ views: Readonly<Record<string, ViewColumns>>,
1549
+ ): readonly AccessModel[] {
1550
+ if (input === undefined) {
1551
+ return freeze([])
1552
+ }
1553
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1554
+ throw new PolicyError(`${table.name}: only a dimension or child table, or a child view, takes access; its rows are what a relation reaches`)
1555
+ }
1556
+ const declared = plainRecord(input, `${table.name}: access`)
1557
+ const relations = ownKeys(declared)
1558
+ const parsed: AccessModel[] = []
1559
+ for (let index = 0; index < relations.length; index++) {
1560
+ const relation = relations[index] ?? ''
1561
+ const what = `${table.name}: access.${relation}`
1562
+ if (!hasOwn(vocabulary.relations, relation)) {
1563
+ throw new PolicyError(`${what} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`)
1564
+ }
1565
+ const entry = plainRecord(ownEntry(declared, relation), what)
1566
+ onlyFields(entry, ACCESS_FIELDS, what)
1567
+ const view = ownEntry(entry, 'view')
1568
+ const named = typeof view === 'string' ? ownEntry(views, view) : undefined
1569
+ if (typeof view !== 'string' || named === undefined) {
1570
+ throw new PolicyError(`${what}.view names ${String(view)}, which the column list does not mark as a view`)
1571
+ }
1572
+ // Read directly, the view would show the caller who else reaches which row.
1573
+ if (named.policy) {
1574
+ throw new PolicyError(`${what}.view names ${view}, which has a policy; an access view takes none, so only the relation's term reads it`)
1575
+ }
1576
+ const columns = named.columns
1577
+ const viewColumn = (field: string, required: boolean): string | undefined => {
1578
+ const name = ownEntry(entry, field)
1579
+ if (name === undefined && !required) return undefined
1580
+ if (typeof name !== 'string' || !inSet(columns, name)) {
1581
+ throw new PolicyError(`${what}.${field} names ${String(name)}, which is not a column of ${view}`)
1582
+ }
1583
+ return name
1584
+ }
1585
+ const row = viewColumn('row', true) ?? ''
1586
+ const principal = viewColumn('principal', false)
1587
+ const member = viewColumn('member', false)
1588
+ if (principal === undefined && member === undefined) {
1589
+ throw new PolicyError(`${what} binds neither principal nor member: an access view is read for the caller, never whole`)
1590
+ }
1591
+ parsed[parsed.length] = freeze({ relation, dimension: ownEntry(vocabulary.relations, relation) ?? '', view, row, principal, member })
1592
+ }
1593
+ return freeze(parsed)
1594
+ }
1595
+
1596
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1597
+ function tableActionNames(table: LinkedTable): NameSet {
1598
+ const names: string[] = []
1599
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1600
+ for (let list = 0; list < lists.length; list++) {
1601
+ const actions = lists[list] ?? []
1602
+ for (let index = 0; index < actions.length; index++) {
1603
+ names[names.length] = actions[index] ?? ''
1604
+ }
1605
+ }
1606
+ const reads = ownKeys(table.columnReads)
1607
+ for (let index = 0; index < reads.length; index++) {
1608
+ names[names.length] = ownEntry(table.columnReads, reads[index] ?? '') ?? ''
1609
+ }
1610
+ const writes = ownKeys(table.columnWrites)
1611
+ for (let index = 0; index < writes.length; index++) {
1612
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1613
+ }
1614
+ return nameSet(names)
1615
+ }
1616
+
1617
+ /**
1618
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1619
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1620
+ */
1621
+ function parseWhen(
1622
+ table: LinkedTable,
1623
+ root: ConditionTable,
1624
+ input: unknown,
1625
+ tables: (name: string) => ConditionTable | undefined,
1626
+ hops: HopRule,
1627
+ ): Readonly<Record<string, ConditionModel>> {
1628
+ if (input === undefined) {
1629
+ return freeze({})
1630
+ }
1631
+ if (table.scope.mode === 'reference') {
1632
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1633
+ }
1634
+ const declared = plainRecord(input, `${table.name}: when`)
1635
+ const named = tableActionNames(table)
1636
+ const actions = ownKeys(declared)
1637
+ const when: Record<string, ConditionModel> = {}
1638
+ for (let index = 0; index < actions.length; index++) {
1639
+ const action = actions[index] ?? ''
1640
+ if (!inSet(named, action)) {
1641
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1642
+ }
1643
+ const what = `${table.name}: when.${action}`
1644
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1645
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1646
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1647
+ if (problem !== undefined) {
1648
+ throw new PolicyError(`${what}: ${problem}`)
1649
+ }
1650
+ setOwn(when, action, condition)
1651
+ }
1652
+ return freeze(when)
1653
+ }
1654
+
1655
+ /**
1656
+ * `relationWhen`: relation → action → a condition on the rows the relation reaches for the action, parsed as `when` is
1657
+ * (the same root, hop rule and insert rule). The relation must be the vocabulary's and the action the table's; whether
1658
+ * the relation reaches the table at all is checked once every table is parsed (`checkRelationWhenReach`).
1659
+ */
1660
+ function parseRelationWhen(
1661
+ table: LinkedTable,
1662
+ root: ConditionTable,
1663
+ input: unknown,
1664
+ vocabulary: VocabularyModel,
1665
+ tables: (name: string) => ConditionTable | undefined,
1666
+ hops: HopRule,
1667
+ ): Readonly<Record<string, Readonly<Record<string, ConditionModel>>>> {
1668
+ if (input === undefined) {
1669
+ return freeze({})
1670
+ }
1671
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1672
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table takes no relationWhen; no relation reaches its rows`)
1673
+ }
1674
+ const declared = plainRecord(input, `${table.name}: relationWhen`)
1675
+ const relations = ownKeys(declared)
1676
+ const named = tableActionNames(table)
1677
+ const parsed: Record<string, Readonly<Record<string, ConditionModel>>> = {}
1678
+ for (let index = 0; index < relations.length; index++) {
1679
+ const relation = relations[index] ?? ''
1680
+ if (!hasOwn(vocabulary.relations, relation)) {
1681
+ throw new PolicyError(
1682
+ `${table.name}: relationWhen.${relation} names a relation the vocabulary does not declare (${ownKeys(vocabulary.relations).join(', ')})`,
1683
+ )
1684
+ }
1685
+ const perAction = plainRecord(ownEntry(declared, relation), `${table.name}: relationWhen.${relation}`)
1686
+ const actions = ownKeys(perAction)
1687
+ if (actions.length === 0) {
1688
+ throw new PolicyError(`${table.name}: relationWhen.${relation} names no action`)
1689
+ }
1690
+ const conditions: Record<string, ConditionModel> = {}
1691
+ for (let position = 0; position < actions.length; position++) {
1692
+ const action = actions[position] ?? ''
1693
+ const what = `${table.name}: relationWhen.${relation}.${action}`
1694
+ if (!inSet(named, action)) {
1695
+ throw new PolicyError(`${what} names an action the table does not name (${namesOf(named).join(', ')})`)
1696
+ }
1697
+ const condition = parseCondition(ownEntry(perAction, action), root, tables, what, hops)
1698
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1699
+ if (problem !== undefined) {
1700
+ throw new PolicyError(`${what}: ${problem}`)
1701
+ }
1702
+ setOwn(conditions, action, condition)
1703
+ }
1704
+ setOwn(parsed, relation, freeze(conditions))
1705
+ }
1706
+ return freeze(parsed)
1707
+ }
1708
+
1709
+ /**
1710
+ * Every `relationWhen` names a relation that reaches the table for its action: the relation's dimension is the table's
1711
+ * or on its chain, a secondary path reaches it, or a reveal of the relation for the action reveals a node the table
1712
+ * lies at. A child view is reached through its parent row, so its parent is what the relation must reach.
1713
+ */
1714
+ function checkRelationWhenReach(models: Readonly<Record<string, TableModel>>, vocabulary: VocabularyModel): void {
1715
+ const names = ownKeys(models)
1716
+ const reveals: RevealModel[] = []
1717
+ for (let index = 0; index < names.length; index++) {
1718
+ const model = ownEntry(models, names[index] ?? '')
1719
+ for (let position = 0; model !== undefined && position < model.reveals.length; position++) {
1720
+ const reveal = model.reveals[position]
1721
+ if (reveal !== undefined) reveals[reveals.length] = reveal
1722
+ }
1723
+ }
1724
+ for (let index = 0; index < names.length; index++) {
1725
+ const model = ownEntry(models, names[index] ?? '')
1726
+ if (model === undefined) continue
1727
+ const reached = model.view && model.scope.mode === 'child' ? ownEntry(models, model.scope.parent) ?? model : model
1728
+ const relations = ownKeys(model.relationWhen)
1729
+ for (let position = 0; position < relations.length; position++) {
1730
+ const relation = relations[position] ?? ''
1731
+ const dimension = ownEntry(vocabulary.relations, relation) ?? ''
1732
+ const actions = ownKeys(ownEntry(model.relationWhen, relation) ?? {})
1733
+ for (let next = 0; next < actions.length; next++) {
1734
+ const action = actions[next] ?? ''
1735
+ if (!relationReaches(reached, relation, dimension, action, reveals)) {
1736
+ throw new PolicyError(
1737
+ `${model.name}: relationWhen.${relation}.${action} names a relation that reaches no row of ${reached.name} for ${action}: neither its chain nor a secondary path holds ${dimension}, and no reveal of ${relation} for ${action} names a node it lies at`,
1738
+ )
1739
+ }
1740
+ }
1741
+ }
1742
+ }
1743
+ }
1744
+
1745
+ /** Whether `relation` of `dimension` reaches a row of `model` for `action`, as the relation terms of the store find one. */
1746
+ function relationReaches(model: TableModel, relation: string, dimension: string, action: string, reveals: readonly RevealModel[]): boolean {
1747
+ if (nodeColumnOf(model, dimension) !== undefined || model.access.some((access) => access.relation === relation)) {
1748
+ return true
1749
+ }
1750
+ for (let index = 0; index < model.readThrough.length; index++) {
1751
+ const path = model.readThrough[index]
1752
+ if (path === undefined) continue
1753
+ if (path.dimension === dimension) return true
1754
+ for (let link = 0; link < path.chain.length; link++) {
1755
+ if (path.chain[link]?.dimension === dimension) return true
1756
+ }
1757
+ }
1758
+ for (let index = 0; index < reveals.length; index++) {
1759
+ const reveal = reveals[index]
1760
+ if (
1761
+ reveal !== undefined && reveal.relation === relation && includes(reveal.actions, action) && nodeColumnOf(model, reveal.dimension) !== undefined
1762
+ ) {
1763
+ return true
1764
+ }
1765
+ }
1766
+ return false
1767
+ }
1768
+
1769
+ /**
1770
+ * The table a `when` of `table` starts at. A child view's parent column is a foreign key to its parent's key that no
1771
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
1772
+ */
1773
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
1774
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
1775
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
1776
+ return table
1777
+ }
1778
+ const foreignKeys: ForeignKey[] = []
1779
+ for (let index = 0; index < table.foreignKeys.length; index++) {
1780
+ const key = table.foreignKeys[index]
1781
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
1782
+ }
1783
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
1784
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
1785
+ }
1786
+
1787
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
1788
+ interface ResolvedOwner extends Resolved {
1789
+ readonly name: string
1790
+ }
1791
+
1792
+ /**
1793
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
1794
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
1795
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
1796
+ * nearest container's own path instead (`containerPath`).
1797
+ */
1798
+ function parseReadThrough(
1799
+ table: LinkedTable,
1800
+ input: unknown,
1801
+ vocabulary: VocabularyModel,
1802
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1803
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1804
+ ): readonly SecondaryPath[] {
1805
+ if (input === undefined) {
1806
+ return freeze([])
1807
+ }
1808
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1809
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
1810
+ }
1811
+ if (table.queue !== undefined) {
1812
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
1813
+ }
1814
+ const declared = plainRecord(input, `${table.name}: readThrough`)
1815
+ const dimensions = ownKeys(declared)
1816
+ const paths: SecondaryPath[] = []
1817
+ for (let index = 0; index < dimensions.length; index++) {
1818
+ const dimension = dimensions[index] ?? ''
1819
+ const what = `${table.name}: readThrough.${dimension}`
1820
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
1821
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
1822
+ }
1823
+ if (nodeColumnOf(table, dimension) !== undefined) {
1824
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
1825
+ }
1826
+ const column = ownEntry(declared, dimension)
1827
+ const segments = typeof column === 'string' ? splitPath(column) : []
1828
+ if (segments.length === 2) {
1829
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
1830
+ continue
1831
+ }
1832
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
1833
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
1834
+ }
1835
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
1836
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
1837
+ }
1838
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
1839
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
1840
+ }
1841
+ for (let position = 0; position < table.chain.length; position++) {
1842
+ if (table.chain[position]?.column === column) {
1843
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
1844
+ }
1845
+ }
1846
+ const owner = ownerOf(dimension)
1847
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
1848
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
1849
+ }
1850
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
1851
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
1852
+ if (!covered) {
1853
+ const columns: string[] = []
1854
+ const referenced: string[] = []
1855
+ for (let position = 0; position < pairs.length; position++) {
1856
+ columns[position] = pairs[position]?.[0] ?? ''
1857
+ referenced[position] = pairs[position]?.[1] ?? ''
1858
+ }
1859
+ throw new PolicyError(
1860
+ `${what}: ${column} and every ancestor ${table.name} shares with ${owner.name} must be one foreign key of exactly these columns, so the node lies in the row's own tenant; declare foreign key (${
1861
+ columns.join(', ')
1862
+ }) references ${owner.name} (${referenced.join(', ')})`,
1863
+ )
1864
+ }
1865
+ requireNotNullAncestors(what, table, pairs)
1866
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined, writes: freeze([]) })
1867
+ }
1868
+ return freeze(paths)
1869
+ }
1870
+
1871
+ /**
1872
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
1873
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
1874
+ * container's own path column, which no update of the container writes; so the read follows containment and the
1875
+ * container's path, and nothing the row's writer picks.
1876
+ */
1877
+ function throughContainer(
1878
+ table: LinkedTable,
1879
+ link: string,
1880
+ column: string,
1881
+ dimension: string,
1882
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1883
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1884
+ what: string,
1885
+ ): SecondaryPath {
1886
+ const nearest = table.chain[0]
1887
+ if (nearest === undefined || nearest.column !== link) {
1888
+ throw new PolicyError(
1889
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
1890
+ nearest === undefined ? '' : ` (${nearest.column})`
1891
+ }; a path through a container starts at the row's own container`,
1892
+ )
1893
+ }
1894
+ const container = ownerOf(nearest.dimension)
1895
+ if (container === undefined || container.scope.mode !== 'dimension') {
1896
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
1897
+ }
1898
+ const path = containerPath(container.name, dimension)
1899
+ if (path === undefined) {
1900
+ throw new PolicyError(
1901
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
1902
+ )
1903
+ }
1904
+ if (path.column !== column) {
1905
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
1906
+ }
1907
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }), writes: freeze([]) })
1908
+ }
1909
+
1910
+ /**
1911
+ * `writeThrough`: a dimension the table reads through → the actions a `Ref` held through that path holds. Each is an
1912
+ * action of the vocabulary: the table's own, or one a reveal matched through the path or a table below reaches the row
1913
+ * for. The path's column is the delegation: whoever inserts it must hold every listed action at the node it names, and
1914
+ * for a path through the container, whoever inserts the container's column (`pathWriters`).
1915
+ */
1916
+ function parseWriteThrough(
1917
+ table: LinkedTable,
1918
+ readThrough: readonly SecondaryPath[],
1919
+ input: unknown,
1920
+ vocabulary: VocabularyModel,
1921
+ ): readonly SecondaryPath[] {
1922
+ if (input === undefined) {
1923
+ return readThrough
1924
+ }
1925
+ const declared = plainRecord(input, `${table.name}: writeThrough`)
1926
+ const dimensions = ownKeys(declared)
1927
+ const writes: Record<string, readonly string[]> = {}
1928
+ for (let index = 0; index < dimensions.length; index++) {
1929
+ const dimension = dimensions[index] ?? ''
1930
+ const what = `${table.name}: writeThrough.${dimension}`
1931
+ let declaredPath = false
1932
+ for (let position = 0; position < readThrough.length; position++) {
1933
+ if (readThrough[position]?.dimension === dimension) declaredPath = true
1934
+ }
1935
+ if (!declaredPath) {
1936
+ throw new PolicyError(`${what}: ${table.name} reads no path to ${dimension}; declare readThrough.${dimension} first`)
1937
+ }
1938
+ const actions = parseList(ownEntry(declared, dimension), (action) => {
1939
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
1940
+ throw new PolicyError(`${what} names ${String(action)}, which is not an action of the vocabulary`)
1941
+ }
1942
+ return action
1943
+ })
1944
+ if (actions === undefined) {
1945
+ throw new PolicyError(`${what} takes a plain array of the vocabulary's actions`)
1946
+ }
1947
+ const listed: string[] = []
1948
+ for (let position = 0; position < actions.length; position++) {
1949
+ const action = actions[position] ?? ''
1950
+ if (!includes(listed, action)) listed[listed.length] = action
1951
+ }
1952
+ if (listed.length === 0) {
1953
+ throw new PolicyError(`${what} names no action; leave the dimension out to hold nothing through the path`)
1954
+ }
1955
+ setOwn(writes, dimension, freeze(listed))
1956
+ }
1957
+ const paths: SecondaryPath[] = []
1958
+ for (let index = 0; index < readThrough.length; index++) {
1959
+ const path = readThrough[index]
1960
+ if (path === undefined) continue
1961
+ const listed = ownEntry(writes, path.dimension)
1962
+ paths[paths.length] = listed === undefined ? path : freeze({ ...path, writes: listed })
1963
+ }
1964
+ return freeze(paths)
1965
+ }
1966
+
1967
+ /**
1968
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
1969
+ * matches the row's key, or of a dimension the table reaches, so it matches that path's column; the ancestor is a link of the chain, whose column the layer stamps and a move rewrites, so the
1970
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
1971
+ */
1972
+ function parseReveals(
1973
+ table: LinkedTable,
1974
+ readThrough: readonly SecondaryPath[],
1975
+ input: unknown,
1976
+ vocabulary: VocabularyModel,
1977
+ tables: (name: string) => ConditionTable | undefined,
1978
+ hops: HopRule,
1979
+ ): readonly RevealModel[] {
1980
+ if (input === undefined) {
1981
+ return freeze([])
1982
+ }
1983
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1984
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
1985
+ }
1986
+ if (table.queue !== undefined) {
1987
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
1988
+ }
1989
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
1990
+ const key = table.scope.key
1991
+ const declared = plainRecord(input, `${table.name}: reveals`)
1992
+ const names = ownKeys(declared)
1993
+ const reveals: RevealModel[] = []
1994
+ for (let index = 0; index < names.length; index++) {
1995
+ const relation = names[index] ?? ''
1996
+ const what = `${table.name}: reveals.${relation}`
1997
+ const dimension = ownEntry(vocabulary.relations, relation)
1998
+ if (dimension === undefined) {
1999
+ throw new PolicyError(
2000
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
2001
+ )
2002
+ }
2003
+ const paths: SecondaryPath[] = []
2004
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
2005
+ const path = readThrough[position]
2006
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
2007
+ }
2008
+ if (dimension !== own && paths.length !== 1) {
2009
+ throw new PolicyError(
2010
+ paths.length === 0
2011
+ ? `${what}: ${relation} is of ${dimension}, which is neither ${table.name}'s own dimension nor one it reads through, or above one; a table reveals for a relation that reaches its rows`
2012
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
2013
+ )
2014
+ }
2015
+ const policy = plainRecord(ownEntry(declared, relation), what)
2016
+ onlyFields(policy, REVEALS_FIELDS, what)
2017
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2018
+ const path = paths[0]
2019
+ if (path?.via !== undefined) {
2020
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
2021
+ throw new PolicyError(
2022
+ `${what}: ${table.name} reads ${dimension} through its container ${path.via.table}, so a reveal matched through it reads too deep; reveal from ${path.via.table} instead`,
2023
+ )
2024
+ }
2025
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2026
+ throw new PolicyError(
2027
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a reveal through a secondary path reveals the nearest container only`,
2028
+ )
2029
+ }
2030
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2031
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
2032
+ }
2033
+ return freeze(reveals)
2034
+ }
2035
+
2036
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
2037
+ function parseRevealed(
2038
+ table: LinkedTable,
2039
+ policy: Readonly<Record<string, unknown>>,
2040
+ what: string,
2041
+ vocabulary: VocabularyModel,
2042
+ tables: (name: string) => ConditionTable | undefined,
2043
+ hops: HopRule,
2044
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
2045
+ const to = ownEntry(policy, 'to')
2046
+ let column: string | undefined
2047
+ for (let position = 0; position < table.chain.length; position++) {
2048
+ const link = table.chain[position]
2049
+ if (link !== undefined && link.dimension === to) column = link.column
2050
+ }
2051
+ if (typeof to !== 'string' || column === undefined) {
2052
+ const above: string[] = []
2053
+ for (let position = 0; position < table.chain.length; position++) {
2054
+ above[above.length] = table.chain[position]?.dimension ?? ''
2055
+ }
2056
+ throw new PolicyError(
2057
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
2058
+ )
2059
+ }
2060
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
2061
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
2062
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
2063
+ }
2064
+ return action
2065
+ })
2066
+ if (actions === undefined) {
2067
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
2068
+ }
2069
+ const listed: string[] = []
2070
+ for (let position = 0; position < actions.length; position++) {
2071
+ const action = actions[position] ?? ''
2072
+ if (!includes(listed, action)) listed[listed.length] = action
2073
+ }
2074
+ if (listed.length === 0) {
2075
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
2076
+ }
2077
+ const whenInput = ownEntry(policy, 'when')
2078
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
2079
+ return { to, column, actions: freeze(listed), when }
2080
+ }
2081
+
2082
+ /**
2083
+ * `memberReveals`: the table's own dimension, or one it reads through, → the ancestor its rows reveal to a grant at the
2084
+ * node. By its own key only a dimension table reveals so: the layer generates the key, so no writer picks a node someone
2085
+ * already holds a grant at. Through a direct path the writer picks it, so an insertable table states `assign`, and the
2086
+ * row reveals its nearest container only, whose column no move of an ancestor rewrites. A queue table's rows move on
2087
+ * every claim.
2088
+ */
2089
+ function parseMemberReveals(
2090
+ table: LinkedTable,
2091
+ readThrough: readonly SecondaryPath[],
2092
+ input: unknown,
2093
+ vocabulary: VocabularyModel,
2094
+ tables: (name: string) => ConditionTable | undefined,
2095
+ hops: HopRule,
2096
+ ): readonly MemberRevealModel[] {
2097
+ if (input === undefined) {
2098
+ return freeze([])
2099
+ }
2100
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2101
+ throw new PolicyError(
2102
+ `${table.name}: a ${table.scope.mode} table reveals nothing to members; only a dimension or child table's rows name a node a grant is at`,
2103
+ )
2104
+ }
2105
+ if (table.queue !== undefined) {
2106
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
2107
+ }
2108
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
2109
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
2110
+ const names = ownKeys(declared)
2111
+ const reveals: MemberRevealModel[] = []
2112
+ for (let index = 0; index < names.length; index++) {
2113
+ const source = names[index] ?? ''
2114
+ const what = `${table.name}: memberReveals.${source}`
2115
+ let path: SecondaryPath | undefined
2116
+ for (let position = 0; source !== own && position < readThrough.length; position++) {
2117
+ if (readThrough[position]?.dimension === source) path = readThrough[position]
2118
+ }
2119
+ if (source !== own && path === undefined) {
2120
+ throw new PolicyError(
2121
+ `${what}: ${source} is neither the own dimension of ${table.name} (${
2122
+ own ?? 'none'
2123
+ }) nor one it reads through; a row reveals to a grant at its own node or at the node its path names`,
2124
+ )
2125
+ }
2126
+ const policy = plainRecord(ownEntry(declared, source), what)
2127
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
2128
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
2129
+ if (path?.via !== undefined) {
2130
+ throw new PolicyError(
2131
+ `${what}: ${table.name} reads ${source} through its container ${path.via.table}; declare the member reveal on ${path.via.table}`,
2132
+ )
2133
+ }
2134
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
2135
+ throw new PolicyError(
2136
+ `${what}.to: ${to} lies above ${table.name}'s nearest container; a move of an ancestor rewrites ${column}, so a member reveal through a path reveals the nearest container only`,
2137
+ )
2138
+ }
2139
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
2140
+ const key = path === undefined ? table.scope.key : path.column
2141
+ reveals[reveals.length] = freeze({ source, table: table.name, key, path, assign, dimension: to, column, actions, when })
2142
+ }
2143
+ return freeze(reveals)
2144
+ }
2145
+
2146
+ /**
2147
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
2148
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
2149
+ */
2150
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
2151
+ if (path === undefined || table.actions.insert.length === 0) {
2152
+ if (input !== undefined) {
2153
+ throw new PolicyError(
2154
+ path === undefined
2155
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
2156
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
2157
+ )
2158
+ }
2159
+ return undefined
2160
+ }
2161
+ if (input === undefined) {
2162
+ throw new PolicyError(
2163
+ `${what}: inserting a row of ${table.name} (${
2164
+ table.actions.insert.join(', ')
2165
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
2166
+ )
2167
+ }
2168
+ const assign = plainRecord(input, `${what}.assign`)
2169
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
2170
+ const self = ownEntry(assign, 'self')
2171
+ if (self !== undefined && self !== true) {
2172
+ throw new PolicyError(`${what}.assign.self takes true`)
2173
+ }
2174
+ return freeze({ self: self === true })
2175
+ }
2176
+
2177
+ /**
2178
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
2179
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
2180
+ */
2181
+ export function delegates(model: TableModel): boolean {
2182
+ for (let index = 0; index < model.reveals.length; index++) {
2183
+ if (model.reveals[index]?.path !== undefined) return true
2184
+ }
2185
+ return model.confers.length > 0 || model.memberReveals.length > 0
2186
+ }
2187
+
2188
+ /**
2189
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
2190
+ * source, a path reveal or a path column that holds actions (`writeThrough`), whose writer the layer bounds; a
2191
+ * member-revealing table, whose key the layer generates so no write revives a node a stale grant still names; and the
2192
+ * tables a principal path or a relation's condition reads, whose columns decide whom a source row names and what it
2193
+ * confers.
2194
+ */
2195
+ export function accessTablesOf(models: TableModels): readonly string[] {
2196
+ const tables: string[] = []
2197
+ const names = ownKeys(models)
2198
+ for (let index = 0; index < names.length; index++) {
2199
+ const model = modelOf(models, names[index] ?? '')
2200
+ if (model !== undefined && (delegates(model) || pathWriters(models, model).length > 0)) {
2201
+ tables[tables.length] = model.name.toLowerCase()
2202
+ }
2203
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
2204
+ const source = model.confers[position]
2205
+ const path = source?.principalPath
2206
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
2207
+ if (source?.when !== undefined) {
2208
+ conditionReach(source.when, (table) => {
2209
+ tables[tables.length] = table.toLowerCase()
2210
+ })
2211
+ }
2212
+ }
2213
+ }
2214
+ return tables
2215
+ }
2216
+
2217
+ /** A path column whose insert hands out the listed actions at the node it names: the bound its writer is held to. */
2218
+ export interface PathWriter {
2219
+ readonly path: SecondaryPath
2220
+ /** The path's own `writes` and those of every table that reads the same dimension through this table's column. */
2221
+ readonly actions: readonly string[]
2222
+ }
2223
+
2224
+ /**
2225
+ * The columns of `model` whose insert hands out actions through a secondary path: its own paths that hold actions, and
2226
+ * its paths that a table below follows through it (`'<link>.<column>'`) with actions of its own. Such a table is written
2227
+ * only through the handles, so no write sets the column past the bound.
2228
+ */
2229
+ export function pathWriters(models: Readonly<Record<string, TableModel>>, model: TableModel): readonly PathWriter[] {
2230
+ const writers: PathWriter[] = []
2231
+ const names = ownKeys(models)
2232
+ for (let index = 0; index < model.readThrough.length; index++) {
2233
+ const path = model.readThrough[index]
2234
+ if (path === undefined || path.via !== undefined) continue
2235
+ const actions: string[] = []
2236
+ for (let position = 0; position < path.writes.length; position++) {
2237
+ const action = path.writes[position] ?? ''
2238
+ if (!includes(actions, action)) actions[actions.length] = action
2239
+ }
2240
+ for (let position = 0; position < names.length; position++) {
2241
+ const below = ownEntry(models, names[position] ?? '')
2242
+ for (let at = 0; below !== undefined && at < below.readThrough.length; at++) {
2243
+ const through = below.readThrough[at]
2244
+ if (through?.via?.table !== model.name || through.dimension !== path.dimension) continue
2245
+ for (let written = 0; written < through.writes.length; written++) {
2246
+ const action = through.writes[written] ?? ''
2247
+ if (!includes(actions, action)) actions[actions.length] = action
2248
+ }
2249
+ }
2250
+ }
2251
+ if (actions.length > 0) writers[writers.length] = freeze({ path, actions: freeze(actions) })
2252
+ }
2253
+ return freeze(writers)
2254
+ }
2255
+
2256
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
2257
+ for (let index = 0; index < chain.length; index++) {
2258
+ if (chain[index]?.dimension === dimension) return true
2259
+ }
2260
+ return false
2261
+ }
2262
+
2263
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
2264
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
2265
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
2266
+ return table.scope.key
2267
+ }
2268
+ for (let index = 0; index < table.chain.length; index++) {
2269
+ const link = table.chain[index]
2270
+ if (link?.dimension === dimension) {
2271
+ return link.column
2272
+ }
2273
+ }
2274
+ return undefined
2275
+ }
2276
+
2277
+ /**
2278
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
2279
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
2280
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
2281
+ * insert action bounds (`assign`).
2282
+ */
2283
+ function parseConfers(
2284
+ table: LinkedTable,
2285
+ input: unknown,
2286
+ relations: Readonly<Record<string, string>>,
2287
+ tables: (name: string) => ConditionTable | undefined,
2288
+ linked: (name: string) => LinkedTable | undefined,
2289
+ hops: HopRule,
2290
+ ): readonly RelationSource[] {
2291
+ if (input === undefined) {
2292
+ return freeze([])
2293
+ }
2294
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
2295
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
2296
+ }
2297
+ if (table.view) {
2298
+ throw new PolicyError(
2299
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
2300
+ )
2301
+ }
2302
+ if (table.queue !== undefined) {
2303
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
2304
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
2305
+ }
2306
+ const declared = plainRecord(input, `${table.name}: confers`)
2307
+ const names = ownKeys(declared)
2308
+ const sources: RelationSource[] = []
2309
+ for (let index = 0; index < names.length; index++) {
2310
+ const relation = names[index] ?? ''
2311
+ const what = `${table.name}: confers.${relation}`
2312
+ const dimension = ownEntry(relations, relation)
2313
+ if (dimension === undefined) {
2314
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
2315
+ }
2316
+ const policy = plainRecord(ownEntry(declared, relation), what)
2317
+ onlyFields(policy, CONFERS_FIELDS, what)
2318
+ const column = (value: unknown, field: string): string => {
2319
+ if (!inSet(table.columns, value)) {
2320
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
2321
+ }
2322
+ return value
2323
+ }
2324
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
2325
+ const placed = nodeColumnOf(table, dimension)
2326
+ if (placed === undefined) {
2327
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
2328
+ }
2329
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
2330
+ if (!own && table.chain[0]?.column !== placed) {
2331
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
2332
+ throw new PolicyError(
2333
+ `${what}: ${dimension} is above ${table.name}'s own container, and a move of an ancestor rewrites ${placed}; a relation's node is the row's key or its own container or parent column`,
2334
+ )
2335
+ }
2336
+ const nodeInput = ownEntry(policy, 'node')
2337
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
2338
+ if (node !== placed) {
2339
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
2340
+ }
2341
+ const expiresInput = ownEntry(policy, 'expires')
2342
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
2343
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
2344
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
2345
+ }
2346
+ const whenInput = ownEntry(policy, 'when')
2347
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
2348
+ const fixed: string[] = [principal]
2349
+ if (expires !== undefined) fixed[fixed.length] = expires
2350
+ const read = when === undefined ? [] : conditionColumns(when)
2351
+ for (let position = 0; position < read.length; position++) {
2352
+ fixed[fixed.length] = read[position] ?? ''
2353
+ }
2354
+ for (let position = 0; position < fixed.length; position++) {
2355
+ const name = fixed[position] ?? ''
2356
+ if (name === table.version) {
2357
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
2358
+ }
2359
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
2360
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
2361
+ }
2362
+ }
2363
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
2364
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
2365
+ }
2366
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
2367
+ const assign = parseAssign(table, policy, expires, what)
2368
+ if (principal === table.createdBy && principalPath !== undefined) {
2369
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
2370
+ }
2371
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
2372
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
2373
+ throw new PolicyError(
2374
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
2375
+ )
2376
+ }
2377
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
2378
+ }
2379
+ return freeze(sources)
2380
+ }
2381
+
2382
+ /**
2383
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
2384
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
2385
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
2386
+ */
2387
+ function parseSourceWhen(
2388
+ table: LinkedTable,
2389
+ input: unknown,
2390
+ tables: (name: string) => ConditionTable | undefined,
2391
+ linked: (name: string) => LinkedTable | undefined,
2392
+ hops: HopRule,
2393
+ what: string,
2394
+ ): ConditionModel {
2395
+ const condition = parseCondition(input, table, tables, what, hops)
2396
+ const visit = (node: ConditionModel): void => {
2397
+ if (node.kind === 'not') {
2398
+ visit(node.term)
2399
+ } else if (node.kind === 'some') {
2400
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2401
+ throw new PolicyError(
2402
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2403
+ )
2404
+ } else if (node.kind === 'test') {
2405
+ const hop = node.hops[0]
2406
+ if (node.hops.length > 1) {
2407
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2408
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2409
+ }
2410
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2411
+ } else {
2412
+ for (let index = 0; index < node.terms.length; index++) {
2413
+ const term = node.terms[index]
2414
+ if (term !== undefined) visit(term)
2415
+ }
2416
+ }
2417
+ }
2418
+ visit(condition)
2419
+ return condition
2420
+ }
2421
+
2422
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2423
+ function farColumn(
2424
+ table: LinkedTable,
2425
+ hop: ConditionHop,
2426
+ held: string,
2427
+ linked: (name: string) => LinkedTable | undefined,
2428
+ what: string,
2429
+ ): void {
2430
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2431
+ const target = linked(hop.table)
2432
+ if (target === undefined) {
2433
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2434
+ }
2435
+ if (target.view) {
2436
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2437
+ }
2438
+ if (target.queue !== undefined) {
2439
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2440
+ }
2441
+ const scope = target.scope
2442
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2443
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2444
+ throw new PolicyError(
2445
+ `${what}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; a relation's condition reads a row whose key the layer generates`,
2446
+ )
2447
+ }
2448
+ if (scope.mode !== 'reference') {
2449
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2450
+ }
2451
+ if (held === target.version) {
2452
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2453
+ }
2454
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2455
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2456
+ }
2457
+ if (chainColumn(target, held)) {
2458
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2459
+ }
2460
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2461
+ }
2462
+
2463
+ /**
2464
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2465
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2466
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2467
+ */
2468
+ function parsePrincipal(
2469
+ table: LinkedTable,
2470
+ input: unknown,
2471
+ linked: (name: string) => LinkedTable | undefined,
2472
+ what: string,
2473
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2474
+ const field = `${what}.principal`
2475
+ if (typeof input !== 'string') {
2476
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2477
+ }
2478
+ const segments = splitPath(input)
2479
+ if (segments.length === 1) {
2480
+ if (!inSet(table.columns, input)) {
2481
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2482
+ }
2483
+ return { column: input, path: undefined }
2484
+ }
2485
+ if (segments.length !== 2) {
2486
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2487
+ }
2488
+ const column = segments[0] ?? ''
2489
+ const held = segments[1] ?? ''
2490
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2491
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2492
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2493
+ throw new PolicyError(
2494
+ `${field}: ${table.name}.${column} is a key, a containment, a version or a file column, which the layer stamps or a move rewrites; a principal path starts at a foreign key no update writes`,
2495
+ )
2496
+ }
2497
+ const hop = singleForeignKey(table, column, field)
2498
+ const target = linked(hop.table)
2499
+ if (target === undefined) {
2500
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2501
+ }
2502
+ if (target.view) {
2503
+ throw new PolicyError(`${field}: ${hop.table} is a view, whose rows change with every write to the tables it reads; a table holds the principal`)
2504
+ }
2505
+ if (target.queue !== undefined) {
2506
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2507
+ }
2508
+ const scope = target.scope
2509
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2510
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2511
+ }
2512
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2513
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2514
+ throw new PolicyError(
2515
+ `${field}: ${hop.table} is a top-level dimension table, whose key an insert takes from its Ref; the principal is held by a table whose key the layer generates`,
2516
+ )
2517
+ }
2518
+ if (scope.key !== hop.key) {
2519
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2520
+ }
2521
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2522
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2523
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2524
+ if (!inSet(target.columns, held)) {
2525
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2526
+ }
2527
+ if (held === target.version) {
2528
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2529
+ }
2530
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2531
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2532
+ }
2533
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2534
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2535
+ }
2536
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2537
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2538
+ }
2539
+
2540
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2541
+ for (let index = 0; index < table.chain.length; index++) {
2542
+ if (table.chain[index]?.column === column) return true
2543
+ }
2544
+ return false
2545
+ }
2546
+
2547
+ /**
2548
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2549
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2550
+ * the referenced table change whom every row names.
2551
+ */
2552
+ function refuseReferencing(
2553
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2554
+ column: string,
2555
+ field: string,
2556
+ role: string,
2557
+ hop: { readonly table: string; readonly key: string } | undefined,
2558
+ ): void {
2559
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2560
+ const key = table.foreignKeys[index]
2561
+ if (key === undefined) continue
2562
+ for (let position = 0; position < key.columns.length; position++) {
2563
+ if (key.columns[position] !== column) continue
2564
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2565
+ throw new PolicyError(
2566
+ `${field}: ${table.name}.${column} ${role} and is a column of a foreign key to ${key.table}, which an update there may rewrite; it references nothing else`,
2567
+ )
2568
+ }
2569
+ }
2570
+ }
2571
+
2572
+ function parseAssign(
2573
+ table: LinkedTable,
2574
+ policy: Readonly<Record<string, unknown>>,
2575
+ expires: string | undefined,
2576
+ what: string,
2577
+ ): RelationSource['assign'] {
2578
+ const input = ownEntry(policy, 'assign')
2579
+ if (table.actions.insert.length === 0) {
2580
+ if (input !== undefined) {
2581
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2582
+ }
2583
+ return undefined
2584
+ }
2585
+ if (input === undefined) {
2586
+ throw new PolicyError(
2587
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2588
+ )
2589
+ }
2590
+ const assign = plainRecord(input, `${what}.assign`)
2591
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2592
+ const maxDays = ownEntry(assign, 'maxDays')
2593
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2594
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2595
+ }
2596
+ if (maxDays !== undefined && expires === undefined) {
2597
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2598
+ }
2599
+ const self = ownEntry(assign, 'self')
2600
+ if (self !== undefined && self !== true) {
2601
+ throw new PolicyError(`${what}.assign.self takes true`)
2602
+ }
2603
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2604
+ }
2605
+
2606
+ /** The own columns a condition reads. */
2607
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2608
+ if (condition.kind === 'test') {
2609
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2610
+ }
2611
+ if (condition.kind === 'not') {
2612
+ return conditionColumns(condition.term)
2613
+ }
2614
+ if (condition.kind === 'some') {
2615
+ return [condition.hops[0]?.column ?? condition.key]
2616
+ }
2617
+ const columns: string[] = []
2618
+ for (let index = 0; index < condition.terms.length; index++) {
2619
+ const term = condition.terms[index]
2620
+ const inner = term === undefined ? [] : conditionColumns(term)
2621
+ for (let position = 0; position < inner.length; position++) {
2622
+ columns[columns.length] = inner[position] ?? ''
2623
+ }
2624
+ }
2625
+ return columns
2626
+ }
2627
+
1137
2628
  /** A table's scope with nothing left to derive, and its containment chain. */
1138
2629
  interface Resolved {
1139
2630
  readonly scope: ScopeModel
@@ -1184,6 +2675,20 @@ function resolveChain(
1184
2675
  for (let index = 0; index < parentChain.length; index++) {
1185
2676
  expected[index] = parentChain[index]?.column ?? ''
1186
2677
  }
2678
+ const dimension = parent.scope.dimension
2679
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2680
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2681
+ if (table.view) {
2682
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2683
+ for (let index = 0; index < inherit.length; index++) {
2684
+ if (!includes(expected, inherit[index])) {
2685
+ throw new PolicyError(
2686
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2687
+ )
2688
+ }
2689
+ }
2690
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2691
+ }
1187
2692
  const inherit = scope.inherit ?? freeze(expected)
1188
2693
  const inherited = nameSet(inherit)
1189
2694
  let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
@@ -1197,19 +2702,24 @@ function resolveChain(
1197
2702
  }), so a composite foreign key keeps it in scope`,
1198
2703
  )
1199
2704
  }
1200
- const dimension = parent.scope.dimension
1201
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1202
- // A view has no foreign key: its SQL alone states its containment, and the approver reviews it (ADR-0072).
1203
- if (!table.view) {
1204
- requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1205
- requireCoveringKey(table, link, parent, parentChain)
1206
- }
2705
+ requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
2706
+ requireCoveringKey(table, link, parent, parentChain)
1207
2707
  return {
1208
2708
  scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }),
1209
2709
  chain: prepend(link, parentChain),
1210
2710
  }
1211
2711
  }
1212
2712
 
2713
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2714
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2715
+ const found: string[] = []
2716
+ for (let index = 0; index < names.length; index++) {
2717
+ const name = names[index] ?? ''
2718
+ if (inSet(table.columns, name)) found[found.length] = name
2719
+ }
2720
+ return found
2721
+ }
2722
+
1213
2723
  /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1214
2724
  function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1215
2725
  for (let index = 0; index < table.foreignKeys.length; index++) {
@@ -1289,6 +2799,53 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1289
2799
  )
1290
2800
  }
1291
2801
 
2802
+ /**
2803
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
2804
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
2805
+ */
2806
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
2807
+ const pairs: [string, string][] = [[column, key]]
2808
+ for (let index = 0; index < chain.length; index++) {
2809
+ const link = chain[index]
2810
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
2811
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
2812
+ }
2813
+ return pairs
2814
+ }
2815
+
2816
+ /**
2817
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
2818
+ * the key, and a row written raw with it null would reach another tenant's row.
2819
+ */
2820
+ function requireNotNullAncestors(
2821
+ what: string,
2822
+ table: { readonly name: string; readonly notNull: NameSet },
2823
+ pairs: readonly (readonly [string, string])[],
2824
+ ): void {
2825
+ const nullable: string[] = []
2826
+ for (let index = 1; index < pairs.length; index++) {
2827
+ const column = pairs[index]?.[0] ?? ''
2828
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
2829
+ }
2830
+ if (nullable.length > 0) {
2831
+ throw new PolicyError(
2832
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
2833
+ nullable.join(', ')
2834
+ } not null and run fabrika db codegen`,
2835
+ )
2836
+ }
2837
+ }
2838
+
2839
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
2840
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
2841
+ for (let index = 0; index < foreignKeys.length; index++) {
2842
+ const foreignKey = foreignKeys[index]
2843
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
2844
+ return true
2845
+ }
2846
+ }
2847
+ return false
2848
+ }
1292
2849
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1293
2850
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1294
2851
  for (let index = 0; index < pairs.length; index++) {