@fabrika/db 0.9.0-dev.11 → 0.9.0-dev.13

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,21 +8,29 @@ 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'
24
32
  export type { RowOf } from './orm-types'
25
- import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
33
+ import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
26
34
 
27
35
  export interface DimensionScope<Col extends string> {
28
36
  readonly dimension: string
@@ -91,6 +99,70 @@ 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
+ /** Relation of this table's own dimension, or of one it reads through → the ancestor node a row the relation reaches reveals. */
107
+ readonly reveals?: { readonly [relation: string]: RevealsPolicy<Col, A> }
108
+ /**
109
+ * Dimension outside the chain → the foreign key column a read reaches a row through: a `Within` of the dimension, or a
110
+ * relation at it, reads the row, and every write follows containment only. No update writes the column. Or
111
+ * `<nearest container column>.<its column>`: the row is read through its nearest container's own read path.
112
+ */
113
+ readonly readThrough?: { readonly [dimension: string]: Col | `${Col}.${string}` }
114
+ /**
115
+ * This table's own dimension → the ancestor node a row reveals to its members: a grant of one of `actions` at the
116
+ * row's own node holds that action at its node in `to` too, for a `Within`'s reads, while `when` admits the row.
117
+ */
118
+ readonly memberReveals?: { readonly [dimension: string]: MemberRevealsPolicy<Col, A> }
119
+ }
120
+
121
+ /** What a row reveals to a caller with a grant at its node: its node in `to`, for `actions`, while `when` admits the row. */
122
+ export interface MemberRevealsPolicy<Col extends string, A extends string> {
123
+ readonly to: string
124
+ readonly actions: readonly A[]
125
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
126
+ readonly when?: ConditionPolicy<Col>
127
+ }
128
+
129
+ /**
130
+ * A row of the table that a relation reaches reveals its node in `to`, an ancestor dimension of its chain: the relation
131
+ * then holds `actions` (those of them its roles list in `via`) there, while `when` admits the row.
132
+ */
133
+ export interface RevealsPolicy<Col extends string, A extends string> {
134
+ readonly to: string
135
+ readonly actions: readonly A[]
136
+ /** A condition on the revealing row, under the same path rule as an action's `when`. */
137
+ readonly when?: ConditionPolicy<Col>
138
+ /**
139
+ * Required on a reveal matched through `readThrough` of a table with an insert action: the row's writer picks the node,
140
+ * so an insert delegates. Without `self`, an insert that names a node where its writer holds the relation is refused.
141
+ */
142
+ readonly assign?: { readonly self?: true }
143
+ }
144
+
145
+ /**
146
+ * A relation source: each row says that the principal in `principal` stands in the relation to the node `node` holds,
147
+ * until `expires` (none: no deadline) and while `when` admits the row. Writing a row is delegation.
148
+ */
149
+ export interface ConfersPolicy<Col extends string> {
150
+ /**
151
+ * The column that holds the principal, or `<column>.<principal column>`: one foreign key of the table into the key of
152
+ * the table whose column holds it. The table's `createdBy` names the row's writer (it needs `assign.self`).
153
+ */
154
+ readonly principal: Col | `${Col}.${string}`
155
+ /** The column that names the node; by default the table's column for the relation's dimension (its key or its chain). */
156
+ readonly node?: Col
157
+ /** A timestamp column: the row confers nothing once it passed. */
158
+ readonly expires?: Col
159
+ /** A condition on the row's own columns (no foreign-key path): `{ revoked_at: { isNull: true } }`. */
160
+ readonly when?: ConditionPolicy<Col>
161
+ /**
162
+ * Inserting a row delegates the relation's actions to its principal, bounded by the inserting Ref's node: at most
163
+ * `maxDays` ahead (which needs `expires`), and to the inserting principal itself only with `self`.
164
+ */
165
+ readonly assign?: { readonly maxDays?: number; readonly self?: true }
94
166
  }
95
167
 
96
168
  /** A table's file columns: column → the name of a file kind of the contract (`c.files`). */
@@ -164,6 +236,13 @@ export interface TableColumns<Col extends string = string, Table extends string
164
236
  readonly booleans?: readonly Col[]
165
237
  /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
166
238
  readonly json?: readonly Col[]
239
+ /**
240
+ * The columns declared NOT NULL; absent when none. A foreign key that holds a row's tenant needs its ancestor columns
241
+ * among them: under MATCH SIMPLE a null in one skips the whole key.
242
+ */
243
+ readonly notNull?: readonly Col[]
244
+ /** A view: read-only, with no foreign key; absent for a table. */
245
+ readonly view?: true
167
246
  }
168
247
 
169
248
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -229,13 +308,111 @@ export interface TableModel {
229
308
  readonly booleans: NameSet
230
309
  /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
231
310
  readonly json: NameSet
311
+ /** The columns the column list declares NOT NULL. */
312
+ readonly notNull: NameSet
232
313
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
233
314
  readonly foreignKeys: readonly ForeignKey[]
315
+ /** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
316
+ readonly view: boolean
234
317
  /**
235
318
  * The containment links this table carries a column for, nearest first: a dimension table's container and
236
319
  * the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
237
320
  */
238
321
  readonly chain: readonly Container[]
322
+ /** The relations this table's rows confer, each with its columns, its condition and its delegation bound. */
323
+ readonly confers: readonly RelationSource[]
324
+ /** The condition each action of the table holds a row under; an action without one is not narrowed. */
325
+ readonly when: Readonly<Record<string, ConditionModel>>
326
+ /** The ancestor nodes this table's rows reveal to a relation of its own dimension or of one it reads through. */
327
+ readonly reveals: readonly RevealModel[]
328
+ /** The secondary read paths: a dimension outside the chain, by the column that holds the row's node in it. */
329
+ readonly readThrough: readonly SecondaryPath[]
330
+ /** The ancestor nodes this table's rows reveal to a grant at their own node. */
331
+ readonly memberReveals: readonly MemberRevealModel[]
332
+ }
333
+
334
+ /**
335
+ * A read path to a dimension outside the chain: `column` holds a key of `table`, which owns `dimension` and lies in
336
+ * `chain`. The column's foreign key covers every ancestor the two chains share, so the node lies in the row's own tenant.
337
+ */
338
+ export interface SecondaryPath {
339
+ readonly dimension: string
340
+ readonly column: string
341
+ readonly table: string
342
+ readonly key: string
343
+ readonly chain: readonly Container[]
344
+ /**
345
+ * The nearest container whose own path this is: the row's `column` of it, its `table` and `key`. `column` above is
346
+ * then the container's column, and the path is read as `T.<via column> in (select C.<key> from C where …)`.
347
+ */
348
+ readonly via: ContainerHop | undefined
349
+ }
350
+
351
+ /** The row's nearest containment column, and the table and key it names. */
352
+ export interface ContainerHop {
353
+ readonly column: string
354
+ readonly table: string
355
+ readonly key: string
356
+ }
357
+
358
+ /**
359
+ * A row of `table` that `relation` reaches reveals its node in `dimension`, held in `column`: the relation holds
360
+ * `actions` at that node while `when` admits the row.
361
+ */
362
+ export interface RevealModel {
363
+ readonly relation: string
364
+ readonly table: string
365
+ /** The table's key, which the relation's nodes match unless the reveal is matched through `path`. */
366
+ readonly key: string
367
+ /**
368
+ * The secondary path whose node, or an ancestor of it, the relation's nodes match. A reveal matched through one holds
369
+ * its actions for a `Within`'s reads only, as the path itself does.
370
+ */
371
+ readonly path: SecondaryPath | undefined
372
+ /** The bound on an insert's delegation through `path`: `undefined` when no handler inserts a row of the table. */
373
+ readonly assign: { readonly self: boolean } | undefined
374
+ readonly dimension: string
375
+ readonly column: string
376
+ readonly actions: readonly string[]
377
+ readonly when: ConditionModel | undefined
378
+ }
379
+
380
+ /**
381
+ * A row of `table`, a node of `source` (its own dimension, keyed by `key`), reveals its node in `dimension`, held in
382
+ * `column`: a grant of one of `actions` at the row's node holds the action there too, for a `Within`'s reads, while
383
+ * `when` admits the row. Only a grant at the node itself counts, never one at a container of it: an insert would
384
+ * otherwise reveal the ancestor to the container's members at once.
385
+ */
386
+ export interface MemberRevealModel {
387
+ readonly source: string
388
+ readonly table: string
389
+ readonly key: string
390
+ readonly dimension: string
391
+ readonly column: string
392
+ readonly actions: readonly string[]
393
+ readonly when: ConditionModel | undefined
394
+ }
395
+
396
+ /** One relation's source table: what a relation term reads, and what a write of its rows is bounded by. */
397
+ export interface RelationSource {
398
+ readonly relation: string
399
+ readonly dimension: string
400
+ readonly table: string
401
+ /** The source's column that decides the principal: it holds it, or it references the row of `principalPath` that does. */
402
+ readonly principal: string
403
+ readonly principalPath: PrincipalPath | undefined
404
+ readonly node: string
405
+ readonly expires: string | undefined
406
+ readonly when: ConditionModel | undefined
407
+ /** `undefined` when the table has no insert action, so no handler writes a row of it. */
408
+ readonly assign: { readonly maxDays: number | undefined; readonly self: boolean } | undefined
409
+ }
410
+
411
+ /** `S.<principal>` references `key` of `table`, whose `column` holds the principal the source row names. */
412
+ export interface PrincipalPath {
413
+ readonly table: string
414
+ readonly key: string
415
+ readonly column: string
239
416
  }
240
417
 
241
418
  /** A child's `column` and `inherit`, when omitted, are derived from its parent while the tables are linked. */
@@ -249,7 +426,14 @@ type ParsedScope =
249
426
  readonly inherit: readonly string[] | undefined
250
427
  }
251
428
 
252
- type ParsedTable = Omit<TableModel, 'chain' | 'scope'> & { readonly scope: ParsedScope }
429
+ type ParsedTable = Omit<TableModel, 'chain' | 'scope' | 'confers' | 'when' | 'reveals' | 'readThrough' | 'memberReveals'> & {
430
+ readonly scope: ParsedScope
431
+ readonly confersInput: unknown
432
+ readonly whenInput: unknown
433
+ readonly revealsInput: unknown
434
+ readonly readThroughInput: unknown
435
+ readonly memberRevealsInput: unknown
436
+ }
253
437
 
254
438
  let readModels: <DB, P>(tables: Tables<DB, P>) => TableModels
255
439
  let hasModels: (value: object) => boolean = () => false
@@ -305,7 +489,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
305
489
  /** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
306
490
  export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
307
491
  ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
308
- : DefineVocabularyPolicies<ColumnTypes<C>, V>
492
+ : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
309
493
 
310
494
  /**
311
495
  * The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
@@ -322,8 +506,13 @@ type Containment = Readonly<Record<string, { readonly container: string | undefi
322
506
  interface VocabularyModel {
323
507
  readonly dimensions: Containment
324
508
  readonly actions: NameSet
509
+ /** Each relation of the vocabulary, by name, with the dimension its nodes are of. */
510
+ readonly relations: Readonly<Record<string, string>>
325
511
  }
326
512
 
513
+ /** A relation's name: it travels in a token's pseudo-scope `~rel:<name>`, so it is a plain word. */
514
+ const RELATION_NAME = /^[a-z][A-Za-z0-9]*$/
515
+
327
516
  function parseVocabulary(input: unknown): VocabularyModel {
328
517
  const vocabulary = plainRecord(input, 'the vocabulary')
329
518
  const dimensions = plainRecord(ownEntry(vocabulary, 'dimensions'), 'the vocabulary dimensions')
@@ -347,12 +536,51 @@ function parseVocabulary(input: unknown): VocabularyModel {
347
536
  }
348
537
  }
349
538
  const actions = ownKeys(plainRecord(ownEntry(vocabulary, 'actions'), 'the vocabulary actions'))
350
- return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
539
+ const relationsInput = ownEntry(vocabulary, 'relations')
540
+ const relations: Record<string, string> = {}
541
+ if (relationsInput !== undefined) {
542
+ const declared = plainRecord(relationsInput, 'the vocabulary relations')
543
+ const relationNames = ownKeys(declared)
544
+ for (let index = 0; index < relationNames.length; index++) {
545
+ const relation = relationNames[index] ?? ''
546
+ if (!RELATION_NAME.test(relation)) {
547
+ throw new PolicyError(`the vocabulary relation ${relation}: a relation name must match ${RELATION_NAME.source}`)
548
+ }
549
+ const dimension = ownEntry(plainRecord(ownEntry(declared, relation), `the vocabulary relation ${relation}`), 'dimension')
550
+ if (typeof dimension !== 'string' || !hasOwn(dimensions, dimension)) {
551
+ throw new PolicyError(`the vocabulary relation ${relation} is of ${String(dimension)}, which is not one of its dimensions`)
552
+ }
553
+ setOwn(relations, relation, dimension)
554
+ }
555
+ }
556
+ return freeze({ dimensions: freeze(containment), actions: nameSet(actions), relations: freeze(relations) })
351
557
  }
352
558
 
353
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json'])
559
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'notNull', 'view'])
354
560
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
355
- const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
561
+ const POLICY_FIELDS = nameSet([
562
+ 'scope',
563
+ 'actions',
564
+ 'insert',
565
+ 'update',
566
+ 'version',
567
+ 'createdBy',
568
+ 'columns',
569
+ 'queue',
570
+ 'files',
571
+ 'confers',
572
+ 'when',
573
+ 'reveals',
574
+ 'readThrough',
575
+ 'memberReveals',
576
+ ])
577
+ const REVEALS_FIELDS = nameSet(['to', 'actions', 'when', 'assign'])
578
+ const MEMBER_REVEALS_FIELDS = nameSet(['to', 'actions', 'when'])
579
+ const REVEAL_ASSIGN_FIELDS = nameSet(['self'])
580
+ const CONFERS_FIELDS = nameSet(['principal', 'node', 'expires', 'when', 'assign'])
581
+ const ASSIGN_FIELDS = nameSet(['maxDays', 'self'])
582
+ /** A delegated row lasts at most ten years ahead: a bound, not a convenience. */
583
+ const MAX_ASSIGN_DAYS = 3650
356
584
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
357
585
  const ACTION_FIELDS = nameSet(['read', 'insert', 'update', 'delete', 'appRead', 'appCount'])
358
586
  const DIMENSION_FIELDS = nameSet(['dimension', 'key', 'in'])
@@ -362,25 +590,6 @@ const REFERENCE_FIELDS = nameSet(['reference'])
362
590
  const APPLICATION_FIELDS = nameSet(['app', 'key'])
363
591
  const COLUMN_FIELDS = nameSet(['read', 'write'])
364
592
 
365
- /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
366
- function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
367
- const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
368
- if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
369
- throw new PolicyError(`${what} must be a plain object`)
370
- }
371
- const copy: Record<string, unknown> = {}
372
- const keys = ownNames(value)
373
- for (let index = 0; index < keys.length; index++) {
374
- const key = keys[index] ?? ''
375
- const descriptor = ownDescriptor(value, key)
376
- if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
377
- throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
378
- }
379
- setOwn(copy, key, descriptor.value)
380
- }
381
- return freeze(copy)
382
- }
383
-
384
593
  /** Unknown keys are refused, not dropped: a misspelt `insrt` would otherwise leave the table without its column list. */
385
594
  function onlyFields(record: Readonly<Record<string, unknown>>, allowed: NameSet, what: string): void {
386
595
  const keys = ownKeys(record)
@@ -407,12 +616,26 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
407
616
  for (let index = 0; index < tables.length; index++) {
408
617
  const table = tables[index] ?? ''
409
618
  const policy = ownEntry(policies, table)
619
+ const entry = ownEntry(columns, table)
620
+ // A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
621
+ if (policy === undefined && isViewEntry(table, entry)) {
622
+ continue
623
+ }
410
624
  if (policy === undefined) {
411
625
  throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
412
626
  }
413
- parsed[index] = parseTable(table, ownEntry(columns, table), policy, vocabulary)
627
+ parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
628
+ }
629
+ return linkTables(parsed, vocabulary)
630
+ }
631
+
632
+ /** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
633
+ function isViewEntry(table: string, entry: unknown): boolean {
634
+ const view = ownEntry(plainRecord(entry, `${table}: the column list entry`), 'view')
635
+ if (view !== undefined && view !== true) {
636
+ throw new PolicyError(`${table}: the column list entry's view is true or absent`)
414
637
  }
415
- return linkTables(parsed, vocabulary.dimensions)
638
+ return view === true
416
639
  }
417
640
 
418
641
  /** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
@@ -468,6 +691,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
468
691
  const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
469
692
  const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
470
693
  const scope = parseScope(table, scopeInput, { column, columnsOf, derived }, vocabulary.dimensions)
694
+ const view = isViewEntry(table, entry)
695
+ if (view && scope.mode !== 'child' && scope.mode !== 'reference') {
696
+ throw new PolicyError(
697
+ `${table}: a view is read-only, so it takes a child scope, { child, key?, column?, inherit? }, or { reference }; ${
698
+ scope.mode === 'app' ? 'an application' : 'a dimension'
699
+ } table's rows are written`,
700
+ )
701
+ }
471
702
  const action = (value: unknown, field: string): string => {
472
703
  const name = nonEmpty(table, value, field)
473
704
  if (!inSet(vocabulary.actions, name)) {
@@ -507,6 +738,9 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
507
738
  restricted[restricted.length] = name
508
739
  }
509
740
  }
741
+ if (writeInput !== undefined && view) {
742
+ throw new PolicyError(viewWrite(table))
743
+ }
510
744
  if (writeInput !== undefined) {
511
745
  setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
512
746
  }
@@ -520,20 +754,26 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
520
754
  if (version !== undefined && hasOwn(columnPolicies, version)) {
521
755
  throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
522
756
  }
523
- const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
757
+ const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
524
758
  const queueInput = ownEntry(policy, 'queue')
525
759
  const filesInput = ownEntry(policy, 'files')
760
+ // On a view, an empty insert or update list is refused too: it states a write the view never takes.
761
+ if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
762
+ throw new PolicyError(viewWrite(table))
763
+ }
526
764
  if (
527
765
  !writable
528
766
  && (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
529
- || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined)
767
+ || ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
768
+ || actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
530
769
  ) {
531
- throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
770
+ throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
532
771
  }
533
772
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
534
773
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
535
774
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
536
775
  const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
776
+ const notNull = parseColumnSet(table, ownEntry(entry, 'notNull'), column, 'notNull')
537
777
  const queue = queueInput === undefined
538
778
  ? undefined
539
779
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -563,7 +803,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
563
803
  timestamps,
564
804
  booleans,
565
805
  json,
806
+ notNull,
566
807
  foreignKeys,
808
+ view,
809
+ confersInput: ownEntry(policy, 'confers'),
810
+ whenInput: ownEntry(policy, 'when'),
811
+ revealsInput: ownEntry(policy, 'reveals'),
812
+ readThroughInput: ownEntry(policy, 'readThrough'),
813
+ memberRevealsInput: ownEntry(policy, 'memberReveals'),
567
814
  }
568
815
  }
569
816
 
@@ -685,7 +932,10 @@ function parseQueue(
685
932
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
686
933
  }
687
934
 
688
- /** The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`) or JSON (`json`) columns, each one of the table's. */
935
+ /**
936
+ * The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`), JSON (`json`) or NOT NULL
937
+ * (`notNull`) columns, each one of the table's.
938
+ */
689
939
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
690
940
  if (input === undefined) {
691
941
  return nameSet([])
@@ -860,6 +1110,10 @@ function parseContainer(
860
1110
  return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
861
1111
  }
862
1112
 
1113
+ function viewWrite(table: string): string {
1114
+ return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
1115
+ }
1116
+
863
1117
  function parseActions(
864
1118
  table: string,
865
1119
  scope: Readonly<Record<string, unknown>>,
@@ -985,6 +1239,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
985
1239
  if (stamp === undefined) {
986
1240
  continue
987
1241
  }
1242
+ // Nothing writes a view, so its key may be its parent column; a predicate still compares each.
1243
+ if (table.view) {
1244
+ if (inSet(table.json, stamp.column)) {
1245
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
1246
+ }
1247
+ continue
1248
+ }
988
1249
  for (let other = 0; other < index; other++) {
989
1250
  const earlier = stamps[other]
990
1251
  if (earlier !== undefined && earlier.column === stamp.column) {
@@ -1027,7 +1288,8 @@ export function includes(names: readonly string[], name: unknown): boolean {
1027
1288
  }
1028
1289
 
1029
1290
  /** Resolves every table's containment chain and refuses a shape the layer cannot enforce. */
1030
- function linkTables(parsed: readonly ParsedTable[], containment: Containment): TableModels {
1291
+ function linkTables(parsed: readonly ParsedTable[], vocabulary: VocabularyModel): TableModels {
1292
+ const containment = vocabulary.dimensions
1031
1293
  const byName: Record<string, ParsedTable> = {}
1032
1294
  const owners: Record<string, ParsedTable> = {}
1033
1295
  for (let index = 0; index < parsed.length; index++) {
@@ -1077,17 +1339,893 @@ function linkTables(parsed: readonly ParsedTable[], containment: Containment): T
1077
1339
  return result
1078
1340
  }
1079
1341
 
1342
+ const conditionTable = (name: string): ConditionTable | undefined => ownEntry(byName, name)
1343
+ const linkedTable = (name: string): LinkedTable | undefined => {
1344
+ const target = ownEntry(byName, name)
1345
+ if (target === undefined) return undefined
1346
+ const { confersInput, whenInput, revealsInput, readThroughInput, memberRevealsInput, ...rest } = target
1347
+ return { ...rest, ...resolve(target, []) }
1348
+ }
1349
+ const hopRule: HopRule = (from, column, to, key, backward) => {
1350
+ const source = ownEntry(byName, from)
1351
+ const target = ownEntry(byName, to)
1352
+ if (target?.scope.mode === 'reference') {
1353
+ return !backward
1354
+ }
1355
+ if (source === undefined || target === undefined) {
1356
+ return false
1357
+ }
1358
+ const into = resolve(target, [])
1359
+ // The hop reads the row its foreign key references, so that must be the row the rules below place: the one with the key.
1360
+ if ((into.scope.mode !== 'dimension' && into.scope.mode !== 'child') || into.scope.key !== key) {
1361
+ return false
1362
+ }
1363
+ const scope = resolve(source, []).scope
1364
+ // The container column must lead to the table that owns the container dimension, not to any table its key references.
1365
+ if (
1366
+ scope.mode === 'dimension' && scope.container !== undefined && scope.container.column === column && into.scope.mode === 'dimension'
1367
+ && into.scope.dimension === scope.container.dimension
1368
+ ) {
1369
+ return true
1370
+ }
1371
+ if (scope.mode === 'child' && scope.column === column && scope.parent === to) {
1372
+ return true
1373
+ }
1374
+ // Any other foreign key reaches a row of the same tenant only when it also holds every ancestor the two share.
1375
+ const pairs = tenantPairs(resolve(source, []), column, into.scope.key, into.chain)
1376
+ if (pairs.length < 2 || !holdsExactly(source.foreignKeys, to, pairs)) {
1377
+ return false
1378
+ }
1379
+ requireNotNullAncestors(`${from}.${column}`, source, pairs)
1380
+ return true
1381
+ }
1382
+ const sources: Record<string, string> = {}
1080
1383
  const models: Record<string, TableModel> = {}
1081
1384
  for (let index = 0; index < parsed.length; index++) {
1082
1385
  const table = parsed[index]
1083
1386
  if (table !== undefined) {
1084
1387
  const { scope, chain } = resolve(table, [])
1085
- setOwn(models, table.name, freeze({ ...table, scope, chain }))
1388
+ const { confersInput, whenInput, revealsInput, readThroughInput, memberRevealsInput, ...rest } = table
1389
+ const linked = { ...rest, scope, chain }
1390
+ const ownerOf = (dimension: string): ResolvedOwner | undefined => {
1391
+ const owner = ownEntry(owners, dimension)
1392
+ return owner === undefined ? undefined : { name: owner.name, ...resolve(owner, []) }
1393
+ }
1394
+ // A container's own path, parsed from its own declaration; one through its container in turn is none.
1395
+ const containerPath = (container: string, dimension: string): SecondaryPath | undefined => {
1396
+ const declared = ownEntry(byName, container)?.readThroughInput
1397
+ const column = declared === undefined ? undefined : ownEntry(plainRecord(declared, `${container}: readThrough`), dimension)
1398
+ const target = linkedTable(container)
1399
+ if (target === undefined || typeof column !== 'string' || splitPath(column).length !== 1) return undefined
1400
+ return parseReadThrough(target, { [dimension]: column }, vocabulary, ownerOf, () => undefined)[0]
1401
+ }
1402
+ const readThrough = parseReadThrough(linked, readThroughInput, vocabulary, ownerOf, containerPath)
1403
+ const confers = parseConfers(linked, confersInput, vocabulary.relations, conditionTable, linkedTable, hopRule)
1404
+ for (let position = 0; position < confers.length; position++) {
1405
+ const relation = confers[position]?.relation ?? ''
1406
+ const earlier = ownEntry(sources, relation)
1407
+ if (earlier !== undefined) {
1408
+ throw new PolicyError(`${table.name}: the relation ${relation} is already conferred by ${earlier}; a relation has one source table`)
1409
+ }
1410
+ setOwn(sources, relation, table.name)
1411
+ }
1412
+ const when = parseWhen(linked, conditionRoot(linked, byName), whenInput, conditionTable, hopRule)
1413
+ const reveals = parseReveals(linked, readThrough, revealsInput, vocabulary, conditionTable, hopRule)
1414
+ const memberReveals = parseMemberReveals(linked, memberRevealsInput, vocabulary, conditionTable, hopRule)
1415
+ setOwn(models, table.name, freeze({ ...linked, confers, when, reveals, readThrough, memberReveals }))
1416
+ }
1417
+ }
1418
+ const relations = ownKeys(vocabulary.relations)
1419
+ for (let index = 0; index < relations.length; index++) {
1420
+ const relation = relations[index] ?? ''
1421
+ if (!hasOwn(sources, relation)) {
1422
+ throw new PolicyError(`the vocabulary relation ${relation} has no source: declare confers.${relation} on the table whose rows hold it`)
1086
1423
  }
1087
1424
  }
1088
1425
  return freeze(models)
1089
1426
  }
1090
1427
 
1428
+ type LinkedTable = Omit<TableModel, 'confers' | 'when' | 'reveals' | 'readThrough' | 'memberReveals'>
1429
+
1430
+ /** Every action a table names: its operations', `appRead`, `appCount` and its columns' own. */
1431
+ function tableActionNames(table: LinkedTable): NameSet {
1432
+ const names: string[] = []
1433
+ const lists = [table.actions.read, table.actions.insert, table.actions.update, table.actions.delete, table.actions.appRead, table.actions.appCount]
1434
+ for (let list = 0; list < lists.length; list++) {
1435
+ const actions = lists[list] ?? []
1436
+ for (let index = 0; index < actions.length; index++) {
1437
+ names[names.length] = actions[index] ?? ''
1438
+ }
1439
+ }
1440
+ const reads = ownKeys(table.columnReads)
1441
+ for (let index = 0; index < reads.length; index++) {
1442
+ names[names.length] = ownEntry(table.columnReads, reads[index] ?? '') ?? ''
1443
+ }
1444
+ const writes = ownKeys(table.columnWrites)
1445
+ for (let index = 0; index < writes.length; index++) {
1446
+ names[names.length] = ownEntry(table.columnWrites, writes[index] ?? '') ?? ''
1447
+ }
1448
+ return nameSet(names)
1449
+ }
1450
+
1451
+ /**
1452
+ * `when`: action → the condition a row must meet for it. An insert action's condition is judged on the inserted row and
1453
+ * the existing rows its paths reach (`insertProblem`); a reference table is read by every site and takes none.
1454
+ */
1455
+ function parseWhen(
1456
+ table: LinkedTable,
1457
+ root: ConditionTable,
1458
+ input: unknown,
1459
+ tables: (name: string) => ConditionTable | undefined,
1460
+ hops: HopRule,
1461
+ ): Readonly<Record<string, ConditionModel>> {
1462
+ if (input === undefined) {
1463
+ return freeze({})
1464
+ }
1465
+ if (table.scope.mode === 'reference') {
1466
+ throw new PolicyError(`${table.name}: a reference table takes no when; every site reads it`)
1467
+ }
1468
+ const declared = plainRecord(input, `${table.name}: when`)
1469
+ const named = tableActionNames(table)
1470
+ const actions = ownKeys(declared)
1471
+ const when: Record<string, ConditionModel> = {}
1472
+ for (let index = 0; index < actions.length; index++) {
1473
+ const action = actions[index] ?? ''
1474
+ if (!inSet(named, action)) {
1475
+ throw new PolicyError(`${table.name}: when.${action} names an action the table does not name (${namesOf(named).join(', ')})`)
1476
+ }
1477
+ const what = `${table.name}: when.${action}`
1478
+ const condition = parseCondition(ownEntry(declared, action), root, tables, what, hops)
1479
+ // An insert reads the rows its foreign keys reach in its transaction, locked until the commit (`judgeInserted`).
1480
+ const problem = includes(table.actions.insert, action) ? insertProblem(condition, table.name) : undefined
1481
+ if (problem !== undefined) {
1482
+ throw new PolicyError(`${what}: ${problem}`)
1483
+ }
1484
+ setOwn(when, action, condition)
1485
+ }
1486
+ return freeze(when)
1487
+ }
1488
+
1489
+ /**
1490
+ * 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
1491
+ * column list declares, so a path follows it to the parent row, and the parent's own foreign keys from there.
1492
+ */
1493
+ function conditionRoot(table: LinkedTable, byName: Readonly<Record<string, ParsedTable>>): ConditionTable {
1494
+ const parent = table.view && table.scope.mode === 'child' ? ownEntry(byName, table.scope.parent) : undefined
1495
+ if (table.scope.mode !== 'child' || parent === undefined || parent.scope.mode !== 'dimension') {
1496
+ return table
1497
+ }
1498
+ const foreignKeys: ForeignKey[] = []
1499
+ for (let index = 0; index < table.foreignKeys.length; index++) {
1500
+ const key = table.foreignKeys[index]
1501
+ if (key !== undefined) foreignKeys[foreignKeys.length] = key
1502
+ }
1503
+ foreignKeys[foreignKeys.length] = freeze({ columns: freeze([table.scope.column]), table: parent.name, references: freeze([parent.scope.key]) })
1504
+ return freeze({ ...table, foreignKeys: freeze(foreignKeys) })
1505
+ }
1506
+
1507
+ /** A dimension's owning table, resolved: what a secondary path's column references. */
1508
+ interface ResolvedOwner extends Resolved {
1509
+ readonly name: string
1510
+ }
1511
+
1512
+ /**
1513
+ * `readThrough`: dimension → the column a `Within`'s read reaches a row through. The dimension lies outside the row's chain and a table
1514
+ * owns it; the column is a foreign key to that table's key that no update writes, and it covers every ancestor the two
1515
+ * chains share, so the database keeps the node in the row's own tenant. `<column>.<column>` reads the row through its
1516
+ * nearest container's own path instead (`containerPath`).
1517
+ */
1518
+ function parseReadThrough(
1519
+ table: LinkedTable,
1520
+ input: unknown,
1521
+ vocabulary: VocabularyModel,
1522
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1523
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1524
+ ): readonly SecondaryPath[] {
1525
+ if (input === undefined) {
1526
+ return freeze([])
1527
+ }
1528
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1529
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table has no containment, so no secondary read path`)
1530
+ }
1531
+ if (table.queue !== undefined) {
1532
+ throw new PolicyError(`${table.name}: a queue table has no secondary read path; a claim follows containment only`)
1533
+ }
1534
+ const declared = plainRecord(input, `${table.name}: readThrough`)
1535
+ const dimensions = ownKeys(declared)
1536
+ const paths: SecondaryPath[] = []
1537
+ for (let index = 0; index < dimensions.length; index++) {
1538
+ const dimension = dimensions[index] ?? ''
1539
+ const what = `${table.name}: readThrough.${dimension}`
1540
+ if (!hasOwn(vocabulary.dimensions, dimension)) {
1541
+ throw new PolicyError(`${what}: ${dimension} is not a dimension of the vocabulary`)
1542
+ }
1543
+ if (nodeColumnOf(table, dimension) !== undefined) {
1544
+ throw new PolicyError(`${what}: ${table.name} already lies in ${dimension}; a secondary path reaches a dimension outside its chain`)
1545
+ }
1546
+ const column = ownEntry(declared, dimension)
1547
+ const segments = typeof column === 'string' ? splitPath(column) : []
1548
+ if (segments.length === 2) {
1549
+ paths[paths.length] = throughContainer(table, segments[0] ?? '', segments[1] ?? '', dimension, ownerOf, containerPath, what)
1550
+ continue
1551
+ }
1552
+ if (typeof column !== 'string' || !inSet(table.columns, column)) {
1553
+ throw new PolicyError(`${what} names ${String(column)}, which is not a column of ${table.name}`)
1554
+ }
1555
+ if (inSet(table.update, column) || hasOwn(table.columnWrites, column) || hasOwn(table.files, column)) {
1556
+ throw new PolicyError(`${what}: ${column} places the row on a read path, so no update writes it`)
1557
+ }
1558
+ if (column === table.version || column === table.createdBy || column === table.scope.key) {
1559
+ throw new PolicyError(`${what}: ${column} is a column the layer writes itself, not a node of ${dimension}`)
1560
+ }
1561
+ for (let position = 0; position < table.chain.length; position++) {
1562
+ if (table.chain[position]?.column === column) {
1563
+ throw new PolicyError(`${what}: ${column} is a containment column of ${table.name}`)
1564
+ }
1565
+ }
1566
+ const owner = ownerOf(dimension)
1567
+ if (owner === undefined || owner.scope.mode !== 'dimension') {
1568
+ throw new PolicyError(`${what}: no table owns ${dimension}, so no foreign key ties ${column} to a node of it`)
1569
+ }
1570
+ const pairs = tenantPairs(table, column, owner.scope.key, owner.chain)
1571
+ const covered = holdsExactly(table.foreignKeys, owner.name, pairs)
1572
+ if (!covered) {
1573
+ const columns: string[] = []
1574
+ const referenced: string[] = []
1575
+ for (let position = 0; position < pairs.length; position++) {
1576
+ columns[position] = pairs[position]?.[0] ?? ''
1577
+ referenced[position] = pairs[position]?.[1] ?? ''
1578
+ }
1579
+ throw new PolicyError(
1580
+ `${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 (${
1581
+ columns.join(', ')
1582
+ }) references ${owner.name} (${referenced.join(', ')})`,
1583
+ )
1584
+ }
1585
+ requireNotNullAncestors(what, table, pairs)
1586
+ paths[paths.length] = freeze({ dimension, column, table: owner.name, key: owner.scope.key, chain: owner.chain, via: undefined })
1587
+ }
1588
+ return freeze(paths)
1589
+ }
1590
+
1591
+ /**
1592
+ * `readThrough.<dimension>: '<link>.<column>'`: the row is read through the path its nearest container declares for the
1593
+ * dimension. `<link>` is the row's nearest containment column, which places it in the container now, and `<column>` the
1594
+ * container's own path column, which no update of the container writes; so the read follows containment and the
1595
+ * container's path, and nothing the row's writer picks.
1596
+ */
1597
+ function throughContainer(
1598
+ table: LinkedTable,
1599
+ link: string,
1600
+ column: string,
1601
+ dimension: string,
1602
+ ownerOf: (dimension: string) => ResolvedOwner | undefined,
1603
+ containerPath: (container: string, dimension: string) => SecondaryPath | undefined,
1604
+ what: string,
1605
+ ): SecondaryPath {
1606
+ const nearest = table.chain[0]
1607
+ if (nearest === undefined || nearest.column !== link) {
1608
+ throw new PolicyError(
1609
+ `${what}: ${link} is not ${table.name}'s nearest containment column${
1610
+ nearest === undefined ? '' : ` (${nearest.column})`
1611
+ }; a path through a container starts at the row's own container`,
1612
+ )
1613
+ }
1614
+ const container = ownerOf(nearest.dimension)
1615
+ if (container === undefined || container.scope.mode !== 'dimension') {
1616
+ throw new PolicyError(`${what}: no table owns ${nearest.dimension}, so no container row holds a path to ${dimension}`)
1617
+ }
1618
+ const path = containerPath(container.name, dimension)
1619
+ if (path === undefined) {
1620
+ throw new PolicyError(
1621
+ `${what}: ${container.name} declares no readThrough.${dimension} through a column of its own, so ${table.name} has no container path to follow`,
1622
+ )
1623
+ }
1624
+ if (path.column !== column) {
1625
+ throw new PolicyError(`${what}: ${container.name} reads ${dimension} through ${path.column}, not ${column}`)
1626
+ }
1627
+ return freeze({ ...path, via: freeze({ column: link, table: container.name, key: container.scope.key }) })
1628
+ }
1629
+
1630
+ /**
1631
+ * `reveals`: relation → the ancestor its rows reveal. The relation is of the table's own dimension, so its term
1632
+ * 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
1633
+ * revealed node follows the row's containment now. A queue table reveals nothing: a claim rewrites its rows.
1634
+ */
1635
+ function parseReveals(
1636
+ table: LinkedTable,
1637
+ readThrough: readonly SecondaryPath[],
1638
+ input: unknown,
1639
+ vocabulary: VocabularyModel,
1640
+ tables: (name: string) => ConditionTable | undefined,
1641
+ hops: HopRule,
1642
+ ): readonly RevealModel[] {
1643
+ if (input === undefined) {
1644
+ return freeze([])
1645
+ }
1646
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1647
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table reveals nothing; its rows lie at no node a relation reaches`)
1648
+ }
1649
+ if (table.queue !== undefined) {
1650
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
1651
+ }
1652
+ const own = table.scope.mode === 'dimension' ? table.scope.dimension : undefined
1653
+ const key = table.scope.key
1654
+ const declared = plainRecord(input, `${table.name}: reveals`)
1655
+ const names = ownKeys(declared)
1656
+ const reveals: RevealModel[] = []
1657
+ for (let index = 0; index < names.length; index++) {
1658
+ const relation = names[index] ?? ''
1659
+ const what = `${table.name}: reveals.${relation}`
1660
+ const dimension = ownEntry(vocabulary.relations, relation)
1661
+ if (dimension === undefined) {
1662
+ throw new PolicyError(
1663
+ `${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(vocabulary.relations).join(', ') || 'none'})`,
1664
+ )
1665
+ }
1666
+ const paths: SecondaryPath[] = []
1667
+ for (let position = 0; dimension !== own && position < readThrough.length; position++) {
1668
+ const path = readThrough[position]
1669
+ if (path !== undefined && (path.dimension === dimension || containsLink(path.chain, dimension))) paths[paths.length] = path
1670
+ }
1671
+ if (dimension !== own && paths.length !== 1) {
1672
+ throw new PolicyError(
1673
+ paths.length === 0
1674
+ ? `${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`
1675
+ : `${what}: ${table.name} reads through more than one path to ${dimension}, so the reveal matches no one column`,
1676
+ )
1677
+ }
1678
+ const policy = plainRecord(ownEntry(declared, relation), what)
1679
+ onlyFields(policy, REVEALS_FIELDS, what)
1680
+ const { to, column, actions: listed, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
1681
+ const path = paths[0]
1682
+ if (path?.via !== undefined) {
1683
+ // The relation's nodes would sit one subquery below the container's, past the guard's bound under a reveal.
1684
+ throw new PolicyError(
1685
+ `${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`,
1686
+ )
1687
+ }
1688
+ if (path !== undefined && table.chain[0]?.dimension !== to) {
1689
+ throw new PolicyError(
1690
+ `${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`,
1691
+ )
1692
+ }
1693
+ const assign = parseRevealAssign(table, path, ownEntry(policy, 'assign'), what)
1694
+ reveals[reveals.length] = freeze({ relation, table: table.name, key, path, assign, dimension: to, column, actions: listed, when })
1695
+ }
1696
+ return freeze(reveals)
1697
+ }
1698
+
1699
+ /** A reveal's `to`, a dimension of the table's chain with the column that holds it, its listed actions, and its `when`. */
1700
+ function parseRevealed(
1701
+ table: LinkedTable,
1702
+ policy: Readonly<Record<string, unknown>>,
1703
+ what: string,
1704
+ vocabulary: VocabularyModel,
1705
+ tables: (name: string) => ConditionTable | undefined,
1706
+ hops: HopRule,
1707
+ ): { readonly to: string; readonly column: string; readonly actions: readonly string[]; readonly when: ConditionModel | undefined } {
1708
+ const to = ownEntry(policy, 'to')
1709
+ let column: string | undefined
1710
+ for (let position = 0; position < table.chain.length; position++) {
1711
+ const link = table.chain[position]
1712
+ if (link !== undefined && link.dimension === to) column = link.column
1713
+ }
1714
+ if (typeof to !== 'string' || column === undefined) {
1715
+ const above: string[] = []
1716
+ for (let position = 0; position < table.chain.length; position++) {
1717
+ above[above.length] = table.chain[position]?.dimension ?? ''
1718
+ }
1719
+ throw new PolicyError(
1720
+ `${what}.to names ${String(to)}, which is not a dimension of ${table.name}'s chain (${above.join(', ') || 'none'})`,
1721
+ )
1722
+ }
1723
+ const actions = parseList(ownEntry(policy, 'actions'), (action) => {
1724
+ if (typeof action !== 'string' || !inSet(vocabulary.actions, action)) {
1725
+ throw new PolicyError(`${what}.actions names ${String(action)}, which is not an action of the vocabulary`)
1726
+ }
1727
+ return action
1728
+ })
1729
+ if (actions === undefined) {
1730
+ throw new PolicyError(`${what}.actions takes a plain array of the vocabulary's actions`)
1731
+ }
1732
+ const listed: string[] = []
1733
+ for (let position = 0; position < actions.length; position++) {
1734
+ const action = actions[position] ?? ''
1735
+ if (!includes(listed, action)) listed[listed.length] = action
1736
+ }
1737
+ if (listed.length === 0) {
1738
+ throw new PolicyError(`${what}.actions names no action; a reveal holds the actions it lists, and no other`)
1739
+ }
1740
+ const whenInput = ownEntry(policy, 'when')
1741
+ const when = whenInput === undefined ? undefined : parseCondition(whenInput, table, tables, `${what}.when`, hops)
1742
+ return { to, column, actions: freeze(listed), when }
1743
+ }
1744
+
1745
+ /**
1746
+ * `memberReveals`: the table's own dimension → the ancestor its rows reveal to a grant at their node. Only a dimension
1747
+ * table reveals so: its key is the node an IAM grant names, and the layer generates it, so no writer picks a node
1748
+ * someone already holds a grant at. A queue table's rows move on every claim.
1749
+ */
1750
+ function parseMemberReveals(
1751
+ table: LinkedTable,
1752
+ input: unknown,
1753
+ vocabulary: VocabularyModel,
1754
+ tables: (name: string) => ConditionTable | undefined,
1755
+ hops: HopRule,
1756
+ ): readonly MemberRevealModel[] {
1757
+ if (input === undefined) {
1758
+ return freeze([])
1759
+ }
1760
+ if (table.scope.mode !== 'dimension') {
1761
+ throw new PolicyError(
1762
+ `${table.name}: a ${table.scope.mode} table reveals nothing to members; only a dimension table's rows are nodes a grant names`,
1763
+ )
1764
+ }
1765
+ if (table.queue !== undefined) {
1766
+ throw new PolicyError(`${table.name}: a queue table reveals nothing; the layer rewrites its rows on every claim`)
1767
+ }
1768
+ const own = table.scope.dimension
1769
+ const key = table.scope.key
1770
+ const declared = plainRecord(input, `${table.name}: memberReveals`)
1771
+ const names = ownKeys(declared)
1772
+ const reveals: MemberRevealModel[] = []
1773
+ for (let index = 0; index < names.length; index++) {
1774
+ const source = names[index] ?? ''
1775
+ const what = `${table.name}: memberReveals.${source}`
1776
+ if (source !== own) {
1777
+ throw new PolicyError(`${what}: ${source} is not ${table.name}'s own dimension (${own}); a row reveals to a grant at its own node only`)
1778
+ }
1779
+ const policy = plainRecord(ownEntry(declared, source), what)
1780
+ onlyFields(policy, MEMBER_REVEALS_FIELDS, what)
1781
+ const { to, column, actions, when } = parseRevealed(table, policy, what, vocabulary, tables, hops)
1782
+ reveals[reveals.length] = freeze({ source, table: table.name, key, dimension: to, column, actions, when })
1783
+ }
1784
+ return freeze(reveals)
1785
+ }
1786
+
1787
+ /**
1788
+ * A reveal matched through a secondary path delegates on insert, since the row's writer picks the node: a table with an
1789
+ * insert action states the bound, as a relation source does. A reveal by the row's own key delegates nothing.
1790
+ */
1791
+ function parseRevealAssign(table: LinkedTable, path: SecondaryPath | undefined, input: unknown, what: string): RevealModel['assign'] {
1792
+ if (path === undefined || table.actions.insert.length === 0) {
1793
+ if (input !== undefined) {
1794
+ throw new PolicyError(
1795
+ path === undefined
1796
+ ? `${what}.assign: the reveal matches the row's own key, so no writer picks its node`
1797
+ : `${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`,
1798
+ )
1799
+ }
1800
+ return undefined
1801
+ }
1802
+ if (input === undefined) {
1803
+ throw new PolicyError(
1804
+ `${what}: inserting a row of ${table.name} (${
1805
+ table.actions.insert.join(', ')
1806
+ }) picks the ${path.dimension} node the reveal holds at; state assign: { self? }`,
1807
+ )
1808
+ }
1809
+ const assign = plainRecord(input, `${what}.assign`)
1810
+ onlyFields(assign, REVEAL_ASSIGN_FIELDS, `${what}.assign`)
1811
+ const self = ownEntry(assign, 'self')
1812
+ if (self !== undefined && self !== true) {
1813
+ throw new PolicyError(`${what}.assign.self takes true`)
1814
+ }
1815
+ return freeze({ self: self === true })
1816
+ }
1817
+
1818
+ /**
1819
+ * A row of the table hands out access that its writer places: it confers a relation, reveals through a path, or reveals
1820
+ * its ancestor to the grants at its node. Such a row is written only through the handles, and never moves.
1821
+ */
1822
+ export function delegates(model: TableModel): boolean {
1823
+ for (let index = 0; index < model.reveals.length; index++) {
1824
+ if (model.reveals[index]?.path !== undefined) return true
1825
+ }
1826
+ return model.confers.length > 0 || model.memberReveals.length > 0
1827
+ }
1828
+
1829
+ /**
1830
+ * The tables whose rows hand out access, which no raw statement writes, lowercased as the tag compares names: a relation
1831
+ * source or a path reveal, whose writer the layer bounds; a member-revealing table, whose key the layer generates so no
1832
+ * write revives a node a stale grant still names; and the tables a principal path or a relation's condition reads, whose
1833
+ * columns decide whom a source row names and what it confers.
1834
+ */
1835
+ export function accessTablesOf(models: TableModels): readonly string[] {
1836
+ const tables: string[] = []
1837
+ const names = ownKeys(models)
1838
+ for (let index = 0; index < names.length; index++) {
1839
+ const model = modelOf(models, names[index] ?? '')
1840
+ if (model !== undefined && delegates(model)) {
1841
+ tables[tables.length] = model.name.toLowerCase()
1842
+ }
1843
+ for (let position = 0; model !== undefined && position < model.confers.length; position++) {
1844
+ const source = model.confers[position]
1845
+ const path = source?.principalPath
1846
+ if (path !== undefined) tables[tables.length] = path.table.toLowerCase()
1847
+ if (source?.when !== undefined) {
1848
+ conditionReach(source.when, (table) => {
1849
+ tables[tables.length] = table.toLowerCase()
1850
+ })
1851
+ }
1852
+ }
1853
+ }
1854
+ return tables
1855
+ }
1856
+
1857
+ function containsLink(chain: readonly Container[], dimension: string): boolean {
1858
+ for (let index = 0; index < chain.length; index++) {
1859
+ if (chain[index]?.dimension === dimension) return true
1860
+ }
1861
+ return false
1862
+ }
1863
+
1864
+ /** The column of `table` that places a row at a node of `dimension`: its key for its own dimension, else a chain link. */
1865
+ export function nodeColumnOf(table: Pick<TableModel, 'scope' | 'chain'>, dimension: string): string | undefined {
1866
+ if (table.scope.mode === 'dimension' && table.scope.dimension === dimension) {
1867
+ return table.scope.key
1868
+ }
1869
+ for (let index = 0; index < table.chain.length; index++) {
1870
+ const link = table.chain[index]
1871
+ if (link?.dimension === dimension) {
1872
+ return link.column
1873
+ }
1874
+ }
1875
+ return undefined
1876
+ }
1877
+
1878
+ /**
1879
+ * `confers`: relation → its columns on this table. The node is the table's own column for the relation's dimension,
1880
+ * which the layer stamps from the inserting Ref, so a row names only a node its writer acts on. The principal, the
1881
+ * node, the expiry and the condition's columns are never updated: a row that confers more is a new row, which its
1882
+ * insert action bounds (`assign`).
1883
+ */
1884
+ function parseConfers(
1885
+ table: LinkedTable,
1886
+ input: unknown,
1887
+ relations: Readonly<Record<string, string>>,
1888
+ tables: (name: string) => ConditionTable | undefined,
1889
+ linked: (name: string) => LinkedTable | undefined,
1890
+ hops: HopRule,
1891
+ ): readonly RelationSource[] {
1892
+ if (input === undefined) {
1893
+ return freeze([])
1894
+ }
1895
+ if (table.scope.mode !== 'dimension' && table.scope.mode !== 'child') {
1896
+ throw new PolicyError(`${table.name}: a ${table.scope.mode} table confers no relation; its rows lie at no node`)
1897
+ }
1898
+ if (table.view) {
1899
+ throw new PolicyError(
1900
+ `${table.name}: a view confers no relation; its rows change with every write to the tables it reads, which no delegation bound sees`,
1901
+ )
1902
+ }
1903
+ if (table.queue !== undefined) {
1904
+ // A claim, a requeue and `done: true` rewrite `due` and `version` past every update-column check.
1905
+ throw new PolicyError(`${table.name}: a queue table confers no relation; the layer rewrites its rows on every claim`)
1906
+ }
1907
+ const declared = plainRecord(input, `${table.name}: confers`)
1908
+ const names = ownKeys(declared)
1909
+ const sources: RelationSource[] = []
1910
+ for (let index = 0; index < names.length; index++) {
1911
+ const relation = names[index] ?? ''
1912
+ const what = `${table.name}: confers.${relation}`
1913
+ const dimension = ownEntry(relations, relation)
1914
+ if (dimension === undefined) {
1915
+ throw new PolicyError(`${what}: ${relation} is not a relation of the vocabulary (relations: ${ownKeys(relations).join(', ') || 'none'})`)
1916
+ }
1917
+ const policy = plainRecord(ownEntry(declared, relation), what)
1918
+ onlyFields(policy, CONFERS_FIELDS, what)
1919
+ const column = (value: unknown, field: string): string => {
1920
+ if (!inSet(table.columns, value)) {
1921
+ throw new PolicyError(`${what}.${field} names ${String(value)}, which is not a column of ${table.name}`)
1922
+ }
1923
+ return value
1924
+ }
1925
+ const { column: principal, path: principalPath } = parsePrincipal(table, ownEntry(policy, 'principal'), linked, what)
1926
+ const placed = nodeColumnOf(table, dimension)
1927
+ if (placed === undefined) {
1928
+ throw new PolicyError(`${what}: ${table.name} does not lie in ${dimension}, the relation's dimension, so its rows name no node of it`)
1929
+ }
1930
+ const own = table.scope.mode === 'dimension' && table.scope.dimension === dimension
1931
+ if (!own && table.chain[0]?.column !== placed) {
1932
+ // An inherited column follows a move of an ancestor (ON UPDATE CASCADE), which no delegation bound sees.
1933
+ throw new PolicyError(
1934
+ `${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`,
1935
+ )
1936
+ }
1937
+ const nodeInput = ownEntry(policy, 'node')
1938
+ const node = nodeInput === undefined ? placed : column(nodeInput, 'node')
1939
+ if (node !== placed) {
1940
+ throw new PolicyError(`${what}.node is ${node}, but a row's ${dimension} is ${placed}: the node is the column the inserting Ref stamps`)
1941
+ }
1942
+ const expiresInput = ownEntry(policy, 'expires')
1943
+ const expires = expiresInput === undefined ? undefined : column(expiresInput, 'expires')
1944
+ if (expires !== undefined && !inSet(table.timestamps, expires)) {
1945
+ throw new PolicyError(`${what}.expires names ${expires}, which is not a timestamp column`)
1946
+ }
1947
+ const whenInput = ownEntry(policy, 'when')
1948
+ const when = whenInput === undefined ? undefined : parseSourceWhen(table, whenInput, tables, linked, hops, `${what}.when`)
1949
+ const fixed: string[] = [principal]
1950
+ if (expires !== undefined) fixed[fixed.length] = expires
1951
+ const read = when === undefined ? [] : conditionColumns(when)
1952
+ for (let position = 0; position < read.length; position++) {
1953
+ fixed[fixed.length] = read[position] ?? ''
1954
+ }
1955
+ for (let position = 0; position < fixed.length; position++) {
1956
+ const name = fixed[position] ?? ''
1957
+ if (name === table.version) {
1958
+ throw new PolicyError(`${what}: ${name} is the version column, which every update rewrites; it decides nothing a row confers`)
1959
+ }
1960
+ if (inSet(table.update, name) || hasOwn(table.columnWrites, name)) {
1961
+ throw new PolicyError(`${what}: ${name} decides what a row confers, so no update writes it; replace the row instead`)
1962
+ }
1963
+ }
1964
+ if (principal === node || principal === table.version || hasOwn(table.files, principal)) {
1965
+ throw new PolicyError(`${what}.principal ${principal} is a column the layer stamps; it holds the principal the row names`)
1966
+ }
1967
+ if (principalPath === undefined) refuseReferencing(table, principal, `${what}.principal`, 'holds the principal', undefined)
1968
+ const assign = parseAssign(table, policy, expires, what)
1969
+ if (principal === table.createdBy && principalPath !== undefined) {
1970
+ throw new PolicyError(`${what}.principal ${principal} is the createdBy column, which holds a principal; a principal path starts at a foreign key`)
1971
+ }
1972
+ // The layer stamps createdBy with the writer, so every row such a source confers names its writer.
1973
+ if (principal === table.createdBy && assign !== undefined && !assign.self) {
1974
+ throw new PolicyError(
1975
+ `${what}.principal ${principal} is the createdBy column, so every inserted row names its writer: state assign: { self: true }`,
1976
+ )
1977
+ }
1978
+ sources[sources.length] = freeze({ relation, dimension, table: table.name, principal, principalPath, node, expires, when, assign })
1979
+ }
1980
+ return freeze(sources)
1981
+ }
1982
+
1983
+ /**
1984
+ * `confers.<relation>.when`: a condition on the source row, which may follow one foreign key to the row it names (the far
1985
+ * side of a many-to-many source). What it reads decides whom the relation reaches, so it is held as the principal is:
1986
+ * no update writes it, on the source or on the far row, and nothing a write elsewhere cascades rewrites it.
1987
+ */
1988
+ function parseSourceWhen(
1989
+ table: LinkedTable,
1990
+ input: unknown,
1991
+ tables: (name: string) => ConditionTable | undefined,
1992
+ linked: (name: string) => LinkedTable | undefined,
1993
+ hops: HopRule,
1994
+ what: string,
1995
+ ): ConditionModel {
1996
+ const condition = parseCondition(input, table, tables, what, hops)
1997
+ const visit = (node: ConditionModel): void => {
1998
+ if (node.kind === 'not') {
1999
+ visit(node.term)
2000
+ } else if (node.kind === 'some') {
2001
+ // Every writer of the naming table adds and removes such rows; no rule holds a set of rows still.
2002
+ throw new PolicyError(
2003
+ `${what}: a relation's condition takes no some or none: the rows naming a source row are written outside its delegation bound`,
2004
+ )
2005
+ } else if (node.kind === 'test') {
2006
+ const hop = node.hops[0]
2007
+ if (node.hops.length > 1) {
2008
+ // The far row is read inside every relation term, beside a principal path, four subqueries deep under a reveal.
2009
+ throw new PolicyError(`${what}: a relation's condition follows at most one foreign key, to the row the source row names`)
2010
+ }
2011
+ if (hop !== undefined) farColumn(table, hop, node.column, linked, what)
2012
+ } else {
2013
+ for (let index = 0; index < node.terms.length; index++) {
2014
+ const term = node.terms[index]
2015
+ if (term !== undefined) visit(term)
2016
+ }
2017
+ }
2018
+ }
2019
+ visit(condition)
2020
+ return condition
2021
+ }
2022
+
2023
+ /** The column a relation's condition tests on the row one foreign key of the source names: fixed like a principal. */
2024
+ function farColumn(
2025
+ table: LinkedTable,
2026
+ hop: ConditionHop,
2027
+ held: string,
2028
+ linked: (name: string) => LinkedTable | undefined,
2029
+ what: string,
2030
+ ): void {
2031
+ refuseReferencing(table, hop.column, what, "starts the condition's path", hop)
2032
+ const target = linked(hop.table)
2033
+ if (target === undefined) {
2034
+ throw new PolicyError(`${what}: ${table.name}.${hop.column} references ${hop.table}, which has no policy`)
2035
+ }
2036
+ if (target.view) {
2037
+ throw new PolicyError(`${what}: ${hop.table} is a view, whose rows change with every write to the tables it reads`)
2038
+ }
2039
+ if (target.queue !== undefined) {
2040
+ throw new PolicyError(`${what}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2041
+ }
2042
+ const scope = target.scope
2043
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2044
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2045
+ throw new PolicyError(
2046
+ `${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`,
2047
+ )
2048
+ }
2049
+ if (scope.mode !== 'reference') {
2050
+ refuseReferencing(target, scope.key, what, "is the key the condition's path follows", undefined)
2051
+ }
2052
+ if (held === target.version) {
2053
+ throw new PolicyError(`${what}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2054
+ }
2055
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2056
+ throw new PolicyError(`${what}: ${hop.table}.${held} decides what a row confers, so no update of ${hop.table} writes it; replace the row instead`)
2057
+ }
2058
+ if (chainColumn(target, held)) {
2059
+ throw new PolicyError(`${what}: ${hop.table}.${held} is a containment column, which a move rewrites; it decides nothing a row confers`)
2060
+ }
2061
+ refuseReferencing(target, held, what, 'decides what a row confers', undefined)
2062
+ }
2063
+
2064
+ /**
2065
+ * `confers.<relation>.principal`: a column of the source, or `<column>.<principal column>`, one single-column foreign key
2066
+ * of the source into the key of a table P whose column holds the principal. Every column that decides the principal is
2067
+ * one no update writes, on P as on the source, so a row names someone else only as a new row its insert bounds.
2068
+ */
2069
+ function parsePrincipal(
2070
+ table: LinkedTable,
2071
+ input: unknown,
2072
+ linked: (name: string) => LinkedTable | undefined,
2073
+ what: string,
2074
+ ): { readonly column: string; readonly path: PrincipalPath | undefined } {
2075
+ const field = `${what}.principal`
2076
+ if (typeof input !== 'string') {
2077
+ throw new PolicyError(`${field} names ${String(input)}, which is not a column of ${table.name}`)
2078
+ }
2079
+ const segments = splitPath(input)
2080
+ if (segments.length === 1) {
2081
+ if (!inSet(table.columns, input)) {
2082
+ throw new PolicyError(`${field} names ${input}, which is not a column of ${table.name}`)
2083
+ }
2084
+ return { column: input, path: undefined }
2085
+ }
2086
+ if (segments.length !== 2) {
2087
+ throw new PolicyError(`${field} ${input} follows more than one foreign key; a principal path is <column>.<principal column>`)
2088
+ }
2089
+ const column = segments[0] ?? ''
2090
+ const held = segments[1] ?? ''
2091
+ // A move rewrites a chain column (ON UPDATE CASCADE), and the layer stamps the key and the version: none is fixed.
2092
+ const own = table.scope.mode === 'reference' ? undefined : table.scope.key
2093
+ if (column === own || column === table.version || hasOwn(table.files, column) || chainColumn(table, column)) {
2094
+ throw new PolicyError(
2095
+ `${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`,
2096
+ )
2097
+ }
2098
+ const hop = singleForeignKey(table, column, field)
2099
+ const target = linked(hop.table)
2100
+ if (target === undefined) {
2101
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}, which has no policy`)
2102
+ }
2103
+ if (target.view) {
2104
+ 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`)
2105
+ }
2106
+ if (target.queue !== undefined) {
2107
+ throw new PolicyError(`${field}: ${hop.table} is a queue table, whose rows the layer rewrites on every claim`)
2108
+ }
2109
+ const scope = target.scope
2110
+ if (scope.mode !== 'dimension' && scope.mode !== 'child' && scope.mode !== 'app') {
2111
+ throw new PolicyError(`${field}: ${hop.table} is a ${scope.mode} table; the principal is held by a table whose key ${column} references`)
2112
+ }
2113
+ if (scope.mode === 'dimension' && scope.container === undefined) {
2114
+ // Its key is the inserting Ref's, so a deferred foreign key lets a delete and an insert re-point the source rows.
2115
+ throw new PolicyError(
2116
+ `${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`,
2117
+ )
2118
+ }
2119
+ if (scope.key !== hop.key) {
2120
+ throw new PolicyError(`${field}: ${table.name}.${column} references ${hop.table}.${hop.key}, not its key ${scope.key}`)
2121
+ }
2122
+ // Only the hop's own key, or a tenant-holding one that maps the column to the same key, may hold the start column.
2123
+ refuseReferencing(table, column, field, 'starts the principal path', hop)
2124
+ refuseReferencing(target, scope.key, field, 'is the key the principal path follows', undefined)
2125
+ if (!inSet(target.columns, held)) {
2126
+ throw new PolicyError(`${field}: ${held} is not a column of ${hop.table}`)
2127
+ }
2128
+ if (held === target.version) {
2129
+ throw new PolicyError(`${field}: ${hop.table}.${held} is the version column, which every update rewrites; it decides nothing a row confers`)
2130
+ }
2131
+ if (inSet(target.update, held) || hasOwn(target.columnWrites, held)) {
2132
+ throw new PolicyError(`${field}: ${hop.table}.${held} decides whom a row names, so no update of ${hop.table} writes it; replace the row instead`)
2133
+ }
2134
+ if (held === scope.key || hasOwn(target.files, held) || inSet(target.json, held) || chainColumn(target, held)) {
2135
+ throw new PolicyError(`${field}: ${hop.table}.${held} is a key, a containment, a file or a JSON column; it holds no principal`)
2136
+ }
2137
+ refuseReferencing(target, held, field, 'holds the principal', undefined)
2138
+ return { column, path: freeze({ table: hop.table, key: hop.key, column: held }) }
2139
+ }
2140
+
2141
+ function chainColumn(table: Pick<TableModel, 'chain'>, column: string): boolean {
2142
+ for (let index = 0; index < table.chain.length; index++) {
2143
+ if (table.chain[index]?.column === column) return true
2144
+ }
2145
+ return false
2146
+ }
2147
+
2148
+ /**
2149
+ * A column that decides whom a row names references nothing but `hop` (a key into `hop.table` that maps it to
2150
+ * `hop.key`): the column list carries no foreign key's actions, and one that cascades on update would let a write to
2151
+ * the referenced table change whom every row names.
2152
+ */
2153
+ function refuseReferencing(
2154
+ table: Pick<TableModel, 'name' | 'foreignKeys'>,
2155
+ column: string,
2156
+ field: string,
2157
+ role: string,
2158
+ hop: { readonly table: string; readonly key: string } | undefined,
2159
+ ): void {
2160
+ for (let index = 0; index < table.foreignKeys.length; index++) {
2161
+ const key = table.foreignKeys[index]
2162
+ if (key === undefined) continue
2163
+ for (let position = 0; position < key.columns.length; position++) {
2164
+ if (key.columns[position] !== column) continue
2165
+ if (hop !== undefined && key.table === hop.table && key.references[position] === hop.key) continue
2166
+ throw new PolicyError(
2167
+ `${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`,
2168
+ )
2169
+ }
2170
+ }
2171
+ }
2172
+
2173
+ function parseAssign(
2174
+ table: LinkedTable,
2175
+ policy: Readonly<Record<string, unknown>>,
2176
+ expires: string | undefined,
2177
+ what: string,
2178
+ ): RelationSource['assign'] {
2179
+ const input = ownEntry(policy, 'assign')
2180
+ if (table.actions.insert.length === 0) {
2181
+ if (input !== undefined) {
2182
+ throw new PolicyError(`${what}.assign: ${table.name} has no insert action, so no handler writes a row to delegate with`)
2183
+ }
2184
+ return undefined
2185
+ }
2186
+ if (input === undefined) {
2187
+ throw new PolicyError(
2188
+ `${what}: inserting a row of ${table.name} (${table.actions.insert.join(', ')}) delegates the relation; state assign: { maxDays?, self? }`,
2189
+ )
2190
+ }
2191
+ const assign = plainRecord(input, `${what}.assign`)
2192
+ onlyFields(assign, ASSIGN_FIELDS, `${what}.assign`)
2193
+ const maxDays = ownEntry(assign, 'maxDays')
2194
+ if (maxDays !== undefined && (typeof maxDays !== 'number' || !isSafeInteger(maxDays) || maxDays < 1 || maxDays > MAX_ASSIGN_DAYS)) {
2195
+ throw new PolicyError(`${what}.assign.maxDays takes a whole number of days from 1 to ${MAX_ASSIGN_DAYS}`)
2196
+ }
2197
+ if (maxDays !== undefined && expires === undefined) {
2198
+ throw new PolicyError(`${what}.assign.maxDays bounds a row's expires, which the relation does not declare`)
2199
+ }
2200
+ const self = ownEntry(assign, 'self')
2201
+ if (self !== undefined && self !== true) {
2202
+ throw new PolicyError(`${what}.assign.self takes true`)
2203
+ }
2204
+ return freeze({ maxDays: typeof maxDays === 'number' ? maxDays : undefined, self: self === true })
2205
+ }
2206
+
2207
+ /** The own columns a condition reads. */
2208
+ function conditionColumns(condition: ConditionModel): readonly string[] {
2209
+ if (condition.kind === 'test') {
2210
+ return condition.hops.length === 0 ? [condition.column] : [condition.hops[0]?.column ?? '']
2211
+ }
2212
+ if (condition.kind === 'not') {
2213
+ return conditionColumns(condition.term)
2214
+ }
2215
+ if (condition.kind === 'some') {
2216
+ return [condition.hops[0]?.column ?? condition.key]
2217
+ }
2218
+ const columns: string[] = []
2219
+ for (let index = 0; index < condition.terms.length; index++) {
2220
+ const term = condition.terms[index]
2221
+ const inner = term === undefined ? [] : conditionColumns(term)
2222
+ for (let position = 0; position < inner.length; position++) {
2223
+ columns[columns.length] = inner[position] ?? ''
2224
+ }
2225
+ }
2226
+ return columns
2227
+ }
2228
+
1091
2229
  /** A table's scope with nothing left to derive, and its containment chain. */
1092
2230
  interface Resolved {
1093
2231
  readonly scope: ScopeModel
@@ -1138,6 +2276,20 @@ function resolveChain(
1138
2276
  for (let index = 0; index < parentChain.length; index++) {
1139
2277
  expected[index] = parentChain[index]?.column ?? ''
1140
2278
  }
2279
+ const dimension = parent.scope.dimension
2280
+ const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
2281
+ // A view has no foreign key: its rows are read through the parent row its parent column names (ADR-0072).
2282
+ if (table.view) {
2283
+ const inherit = scope.inherit ?? freeze(carried(table, expected))
2284
+ for (let index = 0; index < inherit.length; index++) {
2285
+ if (!includes(expected, inherit[index])) {
2286
+ throw new PolicyError(
2287
+ `${table.name}: inherits ${inherit[index]}, which is not a containment column of ${scope.parent} (${expected.join(', ') || 'none'})`,
2288
+ )
2289
+ }
2290
+ }
2291
+ return { scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }), chain: freeze([link]) }
2292
+ }
1141
2293
  const inherit = scope.inherit ?? freeze(expected)
1142
2294
  const inherited = nameSet(inherit)
1143
2295
  let matches = inherit.length === expected.length && namesOf(inherited).length === expected.length
@@ -1151,8 +2303,6 @@ function resolveChain(
1151
2303
  }), so a composite foreign key keeps it in scope`,
1152
2304
  )
1153
2305
  }
1154
- const dimension = parent.scope.dimension
1155
- const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
1156
2306
  requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1157
2307
  requireCoveringKey(table, link, parent, parentChain)
1158
2308
  return {
@@ -1161,6 +2311,16 @@ function resolveChain(
1161
2311
  }
1162
2312
  }
1163
2313
 
2314
+ /** The columns of `names` that `table` has: the parent's containment columns a view carries, which a join of it compares. */
2315
+ function carried(table: ParsedTable, names: readonly string[]): readonly string[] {
2316
+ const found: string[] = []
2317
+ for (let index = 0; index < names.length; index++) {
2318
+ const name = names[index] ?? ''
2319
+ if (inSet(table.columns, name)) found[found.length] = name
2320
+ }
2321
+ return found
2322
+ }
2323
+
1164
2324
  /** Whether a foreign key of `table` takes `column` to `key` of `target`, alone or as part of a composite key. */
1165
2325
  function references(table: ParsedTable, column: string, target: string, key: string): boolean {
1166
2326
  for (let index = 0; index < table.foreignKeys.length; index++) {
@@ -1240,6 +2400,53 @@ function requireCoveringKey(table: ParsedTable, link: Container, owner: ParsedTa
1240
2400
  )
1241
2401
  }
1242
2402
 
2403
+ /**
2404
+ * The column pairs a foreign key from `column` of `table` to a row keyed by `key` with chain `chain` holds to keep that
2405
+ * row in `table`'s own tenant: the column and the key, then each ancestor of `chain` that `table` also lies in.
2406
+ */
2407
+ function tenantPairs(table: Resolved, column: string, key: string, chain: readonly Container[]): [string, string][] {
2408
+ const pairs: [string, string][] = [[column, key]]
2409
+ for (let index = 0; index < chain.length; index++) {
2410
+ const link = chain[index]
2411
+ const shared = link === undefined ? undefined : nodeColumnOf(table, link.dimension)
2412
+ if (link !== undefined && shared !== undefined) pairs[pairs.length] = [shared, link.column]
2413
+ }
2414
+ return pairs
2415
+ }
2416
+
2417
+ /**
2418
+ * The ancestor columns of a tenant key (every pair but the first) must be NOT NULL: under MATCH SIMPLE a null one skips
2419
+ * the key, and a row written raw with it null would reach another tenant's row.
2420
+ */
2421
+ function requireNotNullAncestors(
2422
+ what: string,
2423
+ table: { readonly name: string; readonly notNull: NameSet },
2424
+ pairs: readonly (readonly [string, string])[],
2425
+ ): void {
2426
+ const nullable: string[] = []
2427
+ for (let index = 1; index < pairs.length; index++) {
2428
+ const column = pairs[index]?.[0] ?? ''
2429
+ if (!inSet(table.notNull, column)) nullable[nullable.length] = column
2430
+ }
2431
+ if (nullable.length > 0) {
2432
+ throw new PolicyError(
2433
+ `${what}: ${nullable.join(', ')} of ${table.name} may be null, and a null skips the foreign key that holds the row's tenant; declare ${
2434
+ nullable.join(', ')
2435
+ } not null and run fabrika db codegen`,
2436
+ )
2437
+ }
2438
+ }
2439
+
2440
+ /** One foreign key to `table` of exactly `pairs`: a further nullable column would let the database skip the whole key. */
2441
+ function holdsExactly(foreignKeys: readonly ForeignKey[], table: string, pairs: readonly (readonly [string, string])[]): boolean {
2442
+ for (let index = 0; index < foreignKeys.length; index++) {
2443
+ const foreignKey = foreignKeys[index]
2444
+ if (foreignKey !== undefined && foreignKey.table === table && foreignKey.columns.length === pairs.length && coversPairs(foreignKey, pairs)) {
2445
+ return true
2446
+ }
2447
+ }
2448
+ return false
2449
+ }
1243
2450
  /** Whether every `[column, referenced]` pair is a column of `foreignKey` with that referenced column. */
1244
2451
  function coversPairs(foreignKey: ForeignKey, pairs: readonly (readonly [string, string])[]): boolean {
1245
2452
  for (let index = 0; index < pairs.length; index++) {