@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/framework.ts CHANGED
@@ -24,7 +24,7 @@ export type { DeliveryClaim, NewWebhookBinding, WebhookBinding, WebhookTables }
24
24
  export type { JobLeases, JobLeaseState, JobOutcome, LeaseChange, LeaseProjection, OverdueClaim } from './job-leases'
25
25
  export type { FinishWakes, JobWakes, NewWake, Wake, WakeReason } from './job-wakes'
26
26
  export type { DataAccess, DataHandles, DataSite } from './orm'
27
- export type { FrameworkTables, Locator, ProvisionalBinding } from './registry'
27
+ export type { FrameworkTables, Locator, ProvisionalBinding, RelationCheck, RevealCheck } from './registry'
28
28
  export type { SqlMode, SqlSite, SqlTag, SqlValue } from './sql'
29
29
  export type { FileColumnRef, QuarantinedStoredFile, ServedFile, StagedFile, StoredFileMeta, StoredFiles, StoredFileStatus } from './stored-files'
30
30
 
package/src/guard.ts CHANGED
@@ -26,8 +26,39 @@ export interface GuardContext {
26
26
  readonly lock?: 'share' | 'update' | 'claim'
27
27
  /** An insert that does nothing on a conflict of its listed columns: `on conflict (columns) do nothing`, and no other. */
28
28
  readonly onConflict?: 'nothing'
29
+ /**
30
+ * The tables a scope predicate's subqueries may read, each with the columns one may select: a relation's source by
31
+ * its node column, a condition path's target by its key. Without it, a scope holds no subquery.
32
+ */
33
+ readonly subqueries?: Readonly<Record<string, readonly string[]>>
34
+ /**
35
+ * A child view's parent: its scope may read the view's rows through `<column> in (select P.<key> from P where <P's
36
+ * reach>)`. Without it, a scope holds no such subquery.
37
+ */
38
+ readonly through?: ViewParentLink | undefined
29
39
  }
30
40
 
41
+ /** The parent a child view's scope reads its rows through: the view's parent column, the parent table and its key. */
42
+ export interface ViewParentLink {
43
+ readonly column: string
44
+ readonly table: string
45
+ readonly key: string
46
+ }
47
+
48
+ /** A subquery of the scope predicate the shape check admitted, and the one table it reads. */
49
+ interface Admitted {
50
+ readonly node: unknown
51
+ readonly table: string
52
+ }
53
+
54
+ /**
55
+ * How deep subqueries of a scope nest, the deepest the layer builds: a reveal's row (1) under a condition path of three
56
+ * hops, and a reveal matched through a secondary path above the relation's dimension (the reveal's row, the path's
57
+ * table, the source, and the table a principal path reads). A child view's parent subquery stands once above them, at
58
+ * the top of its scope, and counts apart, so a view's scope nests at most one deeper.
59
+ */
60
+ const MAX_SCOPE_NESTING = 4
61
+
31
62
  function lookup(...names: string[]): NameSet {
32
63
  return nameSet(names)
33
64
  }
@@ -81,6 +112,8 @@ const NODE_KINDS = lookup(
81
112
  // Only as a selected own column's text, the exact position a keyset page continues from; checked below.
82
113
  'CastNode',
83
114
  'DataTypeNode',
115
+ // Only as `not` of a scope predicate's branch, which the shape check admitted.
116
+ 'UnaryOperationNode',
84
117
  )
85
118
 
86
119
  const COMPARISON_OPERATORS = lookup('=', '<>', '<', '<=', '>', '>=', 'like', 'ilike', 'not like', 'not ilike', 'in', 'not in', 'is', 'is not')
@@ -108,11 +141,12 @@ export function assertAllowedTree(root: OperationNode, context: GuardContext): v
108
141
  throw new QueryRefusedError('statement_shape', `${context.root}.${key} is not allowed`)
109
142
  }
110
143
  }
111
- checkRoot(root, context)
112
- walk(root, undefined, context)
144
+ const admitted: Admitted[] = []
145
+ checkRoot(root, context, admitted)
146
+ walk(root, undefined, context, admitted, undefined)
113
147
  }
114
148
 
115
- function checkRoot(root: OperationNode, context: GuardContext): void {
149
+ function checkRoot(root: OperationNode, context: GuardContext, admitted: Admitted[]): void {
116
150
  const target = context.root === 'InsertQueryNode'
117
151
  ? read(root, 'into')
118
152
  : context.root === 'UpdateQueryNode'
@@ -134,20 +168,242 @@ function checkRoot(root: OperationNode, context: GuardContext): void {
134
168
  if (!scoped) {
135
169
  throw new QueryRefusedError('scope_predicate', 'the scope predicate must be the top-level conjunct of WHERE')
136
170
  }
171
+ const through = context.through
172
+ // A child view's rows are placed by its parent row only: no column of the view stands in for that reach.
173
+ const reach = (node: unknown) =>
174
+ through === undefined
175
+ ? isReach(node, context.table, context.subqueries, admitted)
176
+ : isEverything(node) || isThroughParent(node, context.table, through, context.subqueries, admitted)
137
177
  const scope = context.scope
138
- const membership = (leaf: unknown) => isScopeMembership(leaf, context.table)
139
- const shaped = isEverything(scope)
140
- || isTreeOf(scope, 'AndNode', (leaf) => isScopeEquality(leaf, context.table))
141
- || membership(scope)
142
- || (kindOf(scope) === 'ParensNode' && kindOf(read(scope, 'node')) === 'OrNode' && isTreeOf(read(scope, 'node'), 'OrNode', membership))
178
+ const shaped = reach(scope)
179
+ || (kindOf(scope) === 'AndNode' && hasOnly(scope, CONNECTIVE_KEYS) && reach(read(scope, 'left'))
180
+ && kindOf(read(scope, 'right')) === 'ParensNode'
181
+ && isScopeTree(read(scope, 'right'), context.table, context.subqueries, admitted, 0))
143
182
  if (!shaped) {
144
183
  throw new QueryRefusedError(
145
184
  'scope_predicate',
146
- 'the scope predicate must be true, an AND of column = value, or a parenthesized OR of column in (values), over the statement table',
185
+ 'the scope predicate must be true, an AND of column = value, a parenthesized OR of column in (values) or relation rows, or one of these AND a parenthesized condition, over the statement table',
147
186
  )
148
187
  }
149
188
  }
150
189
 
190
+ /**
191
+ * What a capability reaches before its action's condition narrows it: everything (a global grant), a Ref's chain of
192
+ * equalities, and its relation rows after them, or a Within's memberships of values and relation rows.
193
+ */
194
+ function isReach(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth = 0): boolean {
195
+ const equality = (leaf: unknown) => isScopeEquality(leaf, table)
196
+ const related = (leaf: unknown) => isRelationMembership(leaf, table, subqueries, admitted, depth)
197
+ const member = (leaf: unknown) => isScopeMembership(leaf, table) || related(leaf)
198
+ return isEverything(node)
199
+ || isTreeOf(node, 'AndNode', equality)
200
+ || isUnionOf(node, member)
201
+ || (kindOf(node) === 'AndNode' && isTreeOf(read(node, 'left'), 'AndNode', equality) && isUnionOf(read(node, 'right'), related))
202
+ }
203
+
204
+ /**
205
+ * A child view's rows read through its parent: `V.<column> in (select P.<key> from P where <P's reach>)`, after an AND
206
+ * of equalities when one row is addressed. P's reach is one the guard admits for a statement on P, never `true`; a
207
+ * subquery without WHERE reads every parent row.
208
+ */
209
+ function isThroughParent(
210
+ node: unknown,
211
+ table: string,
212
+ parent: ViewParentLink,
213
+ subqueries: GuardContext['subqueries'],
214
+ admitted: Admitted[],
215
+ ): boolean {
216
+ const member = (leaf: unknown) => isParentMembership(leaf, table, parent, subqueries, admitted)
217
+ return member(node)
218
+ || (kindOf(node) === 'AndNode' && hasOnly(node, CONNECTIVE_KEYS) && isTreeOf(read(node, 'left'), 'AndNode', (leaf) => isScopeEquality(leaf, table))
219
+ && member(read(node, 'right')))
220
+ }
221
+
222
+ function isParentMembership(
223
+ node: unknown,
224
+ table: string,
225
+ parent: ViewParentLink,
226
+ subqueries: GuardContext['subqueries'],
227
+ admitted: Admitted[],
228
+ ): boolean {
229
+ if (
230
+ kindOf(node) !== 'BinaryOperationNode' || !hasOnly(node, BINARY_KEYS) || read(read(node, 'operator'), 'operator') !== 'in'
231
+ || !isReference(read(node, 'leftOperand'), table, parent.column)
232
+ ) {
233
+ return false
234
+ }
235
+ const select = read(node, 'rightOperand')
236
+ const from = read(select, 'from')
237
+ const froms = read(from, 'froms')
238
+ const selections = read(select, 'selections')
239
+ const where = read(select, 'where')
240
+ if (
241
+ kindOf(select) !== 'SelectQueryNode' || !hasOnly(select, SUBQUERY_KEYS) || !hasOnly(from, FROM_KEYS) || !isArray(froms) || froms.length !== 1
242
+ || tableName(froms[0]) !== parent.table || !isArray(selections) || selections.length !== 1 || !hasOnly(selections[0], SELECTION_KEYS)
243
+ || !isReference(read(selections[0], 'selection'), parent.table, parent.key) || (where !== undefined && !hasOnly(where, WHERE_KEYS))
244
+ ) {
245
+ return false
246
+ }
247
+ // No WHERE: every parent row, a `Within` of `all`; strictly narrower than the `true` a view's statement admits.
248
+ if (where === undefined) {
249
+ admitted[admitted.length] = { node: select, table: parent.table }
250
+ return true
251
+ }
252
+ const reach = read(where, 'where')
253
+ // The parent's reach nests as deep as on a statement of the parent's own: the parent's subquery counts apart.
254
+ if (isEverything(reach) || !isReach(reach, parent.table, subqueries, admitted, 0)) {
255
+ return false
256
+ }
257
+ admitted[admitted.length] = { node: select, table: parent.table }
258
+ return true
259
+ }
260
+
261
+ /** One leaf, or a parenthesized OR tree of them. */
262
+ function isUnionOf(node: unknown, leaf: (node: unknown) => boolean): boolean {
263
+ return leaf(node) || (kindOf(node) === 'ParensNode' && kindOf(read(node, 'node')) === 'OrNode' && isTreeOf(read(node, 'node'), 'OrNode', leaf))
264
+ }
265
+
266
+ /** `table.<node> in (select S.<node> from S where S.<principal> = $me and …)`: the rows a relation reaches. */
267
+ function isRelationMembership(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth = 0): boolean {
268
+ return kindOf(node) === 'BinaryOperationNode' && hasOnly(node, BINARY_KEYS) && read(read(node, 'operator'), 'operator') === 'in'
269
+ && isOwnColumn(read(node, 'leftOperand'), table)
270
+ && isScopeSubquery(read(node, 'rightOperand'), subqueries, admitted, depth + 1, true)
271
+ }
272
+
273
+ /**
274
+ * A scope with relations or conditions: AND, OR, parentheses and `not` over tests of the table's own columns against a
275
+ * bound value, a bound list, null, or a subquery that reads one admitted table, selects one admitted column of it and
276
+ * is scoped the same way over that table. Never `true` inside: that would make a branch vacuous.
277
+ */
278
+ function isScopeTree(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
279
+ switch (kindOf(node)) {
280
+ case 'AndNode':
281
+ case 'OrNode':
282
+ return hasOnly(node, CONNECTIVE_KEYS) && isScopeTree(read(node, 'left'), table, subqueries, admitted, depth)
283
+ && isScopeTree(read(node, 'right'), table, subqueries, admitted, depth)
284
+ case 'ParensNode':
285
+ return hasOnly(node, PARENS_KEYS) && isScopeTree(read(node, 'node'), table, subqueries, admitted, depth)
286
+ case 'UnaryOperationNode':
287
+ return hasOnly(node, UNARY_KEYS) && read(read(node, 'operator'), 'operator') === 'not'
288
+ && isScopeTree(read(node, 'operand'), table, subqueries, admitted, depth)
289
+ case 'BinaryOperationNode':
290
+ return isScopeTest(node, table, subqueries, admitted, depth)
291
+ default:
292
+ return false
293
+ }
294
+ }
295
+
296
+ function isScopeTest(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
297
+ const operator = read(read(node, 'operator'), 'operator')
298
+ if (!hasOnly(node, BINARY_KEYS) || !isOwnColumn(read(node, 'leftOperand'), table) || !inSet(SCOPE_OPERATORS, operator)) {
299
+ return false
300
+ }
301
+ const right = read(node, 'rightOperand')
302
+ if (operator === 'is' || operator === 'is not') {
303
+ return kindOf(right) === 'ValueNode' && read(right, 'immediate') === true && read(right, 'value') === null
304
+ }
305
+ if (operator === 'in' || operator === 'not in') {
306
+ if (kindOf(right) === 'ValueListNode') {
307
+ return isBoundList(right)
308
+ }
309
+ return operator === 'in' && isScopeSubquery(right, subqueries, admitted, depth + 1, false)
310
+ }
311
+ return isBoundValue(right)
312
+ }
313
+
314
+ function isBoundList(list: unknown): boolean {
315
+ const values = read(list, 'values')
316
+ if (!isArray(values) || values.length === 0) {
317
+ return false
318
+ }
319
+ for (let index = 0; index < values.length; index++) {
320
+ if (!isBoundValue(values[index])) {
321
+ return false
322
+ }
323
+ }
324
+ return true
325
+ }
326
+
327
+ /**
328
+ * `(select S.<column> from S where <scope tree over S>)`, S and its column admitted, nothing else on the node. A relation's
329
+ * subquery is `anchored`: its WHERE starts with an equality to a bound value, the principal, so it never reads every row.
330
+ */
331
+ function isScopeSubquery(node: unknown, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number, anchored: boolean): boolean {
332
+ if (subqueries === undefined || depth > MAX_SCOPE_NESTING || kindOf(node) !== 'SelectQueryNode' || !hasOnly(node, SUBQUERY_KEYS)) {
333
+ return false
334
+ }
335
+ const from = read(node, 'from')
336
+ const froms = read(from, 'froms')
337
+ if (!hasOnly(from, FROM_KEYS) || !isArray(froms) || froms.length !== 1) {
338
+ return false
339
+ }
340
+ const table = tableName(froms[0])
341
+ if (table === undefined || !hasOwn(subqueries, table)) {
342
+ return false
343
+ }
344
+ const columns = subqueries[table] ?? []
345
+ const selections = read(node, 'selections')
346
+ if (!isArray(selections) || selections.length !== 1 || !hasOnly(selections[0], SELECTION_KEYS)) {
347
+ return false
348
+ }
349
+ const selected = read(selections[0], 'selection')
350
+ const name = read(read(read(selected, 'column'), 'column'), 'name')
351
+ let known = false
352
+ for (let index = 0; index < columns.length; index++) {
353
+ if (columns[index] === name) {
354
+ known = true
355
+ }
356
+ }
357
+ const where = read(node, 'where')
358
+ if (!known || !isOwnColumn(selected, table) || !hasOnly(where, WHERE_KEYS)) {
359
+ return false
360
+ }
361
+ const condition = read(where, 'where')
362
+ if (anchored ? !isAnchored(condition, table, subqueries, admitted, depth) : !isScopeTree(condition, table, subqueries, admitted, depth)) {
363
+ return false
364
+ }
365
+ admitted[admitted.length] = { node, table }
366
+ return true
367
+ }
368
+
369
+ /**
370
+ * `S.<column> = $n`, `S.<column> in ($1, …)` (a secondary path's container: the nodes inside bound containers), or a
371
+ * relation's membership over `S` (a reveal: `R.<key> in (<anchored subquery>)`), then any scope tree AND-ed after it.
372
+ * Each way the innermost subquery starts with a test against bound values, so it never reads every row.
373
+ */
374
+ function isAnchored(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
375
+ if (kindOf(node) === 'AndNode') {
376
+ return hasOnly(node, CONNECTIVE_KEYS) && isAnchored(read(node, 'left'), table, subqueries, admitted, depth)
377
+ && isScopeTree(read(node, 'right'), table, subqueries, admitted, depth)
378
+ }
379
+ return isScopeEquality(node, table) || isScopeMembership(node, table) || isRelationMembership(node, table, subqueries, admitted, depth)
380
+ }
381
+
382
+ /** True when every own property of `node` is one of `keys`: a scope node carries nothing the shape check did not read. */
383
+ function hasOnly(node: unknown, keys: NameSet): boolean {
384
+ if (typeof node !== 'object' || node === null) {
385
+ return false
386
+ }
387
+ const own = ownKeys(node)
388
+ for (let index = 0; index < own.length; index++) {
389
+ const key = own[index] ?? ''
390
+ if (!inSet(keys, key) && read(node, key) !== undefined) {
391
+ return false
392
+ }
393
+ }
394
+ return true
395
+ }
396
+
397
+ const CONNECTIVE_KEYS = lookup('kind', 'left', 'right')
398
+ const PARENS_KEYS = lookup('kind', 'node')
399
+ const UNARY_KEYS = lookup('kind', 'operator', 'operand')
400
+ const BINARY_KEYS = lookup('kind', 'leftOperand', 'operator', 'rightOperand')
401
+ const SUBQUERY_KEYS = lookup('kind', 'from', 'selections', 'where')
402
+ const FROM_KEYS = lookup('kind', 'froms')
403
+ const SELECTION_KEYS = lookup('kind', 'selection')
404
+ const WHERE_KEYS = lookup('kind', 'where')
405
+ const SCOPE_OPERATORS = lookup('=', '<>', '<', '<=', '>', '>=', 'in', 'not in', 'is', 'is not')
406
+
151
407
  /** A Within that is not limited to scope values. */
152
408
  function isEverything(node: unknown): boolean {
153
409
  return kindOf(node) === 'ValueNode' && read(node, 'immediate') === true && read(node, 'value') === true
@@ -205,8 +461,18 @@ function soleFrom(from: unknown): unknown {
205
461
  return froms[0]
206
462
  }
207
463
 
208
- function walk(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
209
- checkNode(node, parent, context)
464
+ function walk(
465
+ node: OperationNode,
466
+ parent: Visit | undefined,
467
+ context: GuardContext,
468
+ admitted: readonly Admitted[],
469
+ inside: string | undefined,
470
+ ): void {
471
+ const subquery = parent === undefined ? undefined : admittedTable(node, admitted)
472
+ const reading = subquery ?? inside
473
+ if (subquery === undefined) {
474
+ checkNode(node, parent, context, reading)
475
+ }
210
476
  if (node.kind === 'ValueNode') {
211
477
  return
212
478
  }
@@ -218,7 +484,7 @@ function walk(node: OperationNode, parent: Visit | undefined, context: GuardCont
218
484
  for (let position = 0; position < children.length; position++) {
219
485
  const child = children[position]
220
486
  if (isOperationNode(child)) {
221
- walk(child, { node, key, up: parent }, context)
487
+ walk(child, { node, key, up: parent }, context, admitted, reading)
222
488
  } else if (typeof child === 'object' && child !== null) {
223
489
  throw new QueryRefusedError('statement_shape', `unexpected structure under ${node.kind}.${key}`)
224
490
  }
@@ -226,7 +492,18 @@ function walk(node: OperationNode, parent: Visit | undefined, context: GuardCont
226
492
  }
227
493
  }
228
494
 
229
- function checkNode(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
495
+ /** The table an admitted subquery reads, when `node` is one, by identity. */
496
+ function admittedTable(node: unknown, admitted: readonly Admitted[]): string | undefined {
497
+ for (let index = 0; index < admitted.length; index++) {
498
+ const entry = admitted[index]
499
+ if (entry !== undefined && entry.node === node) {
500
+ return entry.table
501
+ }
502
+ }
503
+ return undefined
504
+ }
505
+
506
+ function checkNode(node: OperationNode, parent: Visit | undefined, context: GuardContext, inside: string | undefined): void {
230
507
  if (inSet(ROOT_KINDS, node.kind)) {
231
508
  if (parent !== undefined) {
232
509
  throw new QueryRefusedError('statement_shape', 'subqueries are not allowed')
@@ -261,7 +538,7 @@ function checkNode(node: OperationNode, parent: Visit | undefined, context: Guar
261
538
  }
262
539
  return
263
540
  case 'TableNode':
264
- return checkTable(node, parent, context)
541
+ return checkTable(node, parent, context, inside)
265
542
  case 'OrderByItemNode': {
266
543
  // Kysely prints `nulls` as raw text; the layer only ever states the order Postgres has by default.
267
544
  const nulls = read(node, 'nulls')
@@ -313,6 +590,9 @@ function checkOperator(node: OperationNode, parent: Visit | undefined): void {
313
590
  if (inSet(COMPARISON_OPERATORS, operator)) {
314
591
  return
315
592
  }
593
+ if (operator === 'not' && parent?.node.kind === 'UnaryOperationNode') {
594
+ return
595
+ }
316
596
  // The version bump `version = version + 1` is the one arithmetic the layer writes, as a SET value.
317
597
  if (operator === '+' && parent?.up?.node.kind === 'ColumnUpdateNode') {
318
598
  return
@@ -393,8 +673,15 @@ function checkRaw(node: OperationNode, parent: Visit | undefined): void {
393
673
  }
394
674
  }
395
675
 
396
- function checkTable(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
676
+ function checkTable(node: OperationNode, parent: Visit | undefined, context: GuardContext, inside: string | undefined): void {
397
677
  const name = tableName(node)
678
+ // Inside an admitted subquery its own table is the one it reads, and the outer statement's is not reachable.
679
+ if (inside !== undefined) {
680
+ if (name === inside) {
681
+ return
682
+ }
683
+ throw new QueryRefusedError('statement_shape', `a scope subquery of ${inside} reads ${String(name)}`)
684
+ }
398
685
  if (name === context.table) {
399
686
  return
400
687
  }
package/src/index.ts CHANGED
@@ -112,6 +112,7 @@ export {
112
112
  export { type TablePolicies, tablePolicies } from './tables'
113
113
  export type {
114
114
  ColumnTypes,
115
+ ColumnViews,
115
116
  DefineVocabularyPolicies,
116
117
  NormalizedPolicies,
117
118
  TableVocabulary,
@@ -124,4 +125,5 @@ export type {
124
125
  VocabularyDimensionScope,
125
126
  VocabularyPolicyMap,
126
127
  VocabularyTablePolicy,
128
+ VocabularyViewPolicy,
127
129
  } from './vocabulary-tables'
package/src/nodes.ts CHANGED
@@ -81,11 +81,12 @@ export function anyOf(nodes: readonly OperationNode[]): OperationNode {
81
81
  }
82
82
 
83
83
  export function inList(table: string, name: string, values: readonly string[]): OperationNode {
84
- return BinaryOperationNode.create(
85
- column(table, name),
86
- OperatorNode.create('in'),
87
- ValueListNode.create(valueNodes(values)),
88
- )
84
+ return BinaryOperationNode.create(column(table, name), OperatorNode.create('in'), valueList(values))
85
+ }
86
+
87
+ /** `($1, $2, …)`: bound values, as the right operand of an `in`. */
88
+ export function valueList(values: readonly string[]): OperationNode {
89
+ return ValueListNode.create(valueNodes(values))
89
90
  }
90
91
 
91
92
  function valueNodes(values: readonly string[]): ValueNode[] {
@@ -181,7 +182,9 @@ function joinNode(parent: string, join: JoinState): JoinNode {
181
182
  BinaryOperationNode.create(column(child, pair.childColumn), OperatorNode.create('='), column(parent, pair.parentColumn))
182
183
  ),
183
184
  )
184
- const conditions = conditionsNode(child, join.select.conditions)
185
+ const requested = conditionsNode(child, join.select.conditions)
186
+ const held = join.condition
187
+ const conditions = held === undefined ? requested : requested === undefined ? held : AndNode.create(requested, ParensNode.create(held))
185
188
  const on = conditions === undefined ? foreignKey : AndNode.create(foreignKey, ParensNode.create(conditions))
186
189
  return JoinNode.createWithOn('InnerJoin', TableNode.create(child), on)
187
190
  }
package/src/orm-types.ts CHANGED
@@ -103,6 +103,8 @@ export interface IndexedTable {
103
103
  readonly versioned: boolean
104
104
  /** A queue table: its rows are claimed and finished through `row.ref`. */
105
105
  readonly queued: boolean
106
+ /** A view: read like its scope's tables, written by no site (ADR-0072). */
107
+ readonly view: boolean
106
108
  }
107
109
 
108
110
  type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> = {
@@ -128,6 +130,7 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
128
130
  readonly reach: ReachOf<P, T, V>
129
131
  readonly versioned: PolicyOf<P, T> extends { readonly version: string } ? true : false
130
132
  readonly queued: PolicyOf<P, T> extends { readonly queue: object } ? true : false
133
+ readonly view: PolicyOf<P, T> extends { readonly view: true } ? true : false
131
134
  }
132
135
 
133
136
  type OwnerTable<P, D> = { [K in keyof P]: P[K] extends { readonly scope: { readonly dimension: D } } ? K : never }[keyof P]
@@ -159,6 +162,14 @@ type ChainDimensions<P, T, V> = PolicyOf<P, T> extends { readonly scope: infer S
159
162
  /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a top-level table's own. */
160
163
  type ReachOf<P, T, V> = [ContainerOf<P, T>] extends [never] ? DimensionOf<P, T> | ChainDimensions<P, T, V> : ChainDimensions<P, T, V>
161
164
 
165
+ /**
166
+ * The dimensions outside its chain whose `Within` reads table `T` through a foreign key (`readThrough`); a child view's
167
+ * are its parent's, as it is read through its parent row.
168
+ */
169
+ type ReadThroughOf<P, T> = PolicyOf<P, T> extends { readonly readThrough: infer R } ? keyof R & string
170
+ : PolicyOf<P, T> extends { readonly view: true; readonly scope: { readonly child: infer Parent extends string } } ? ReadThroughOf<P, Parent>
171
+ : never
172
+
162
173
  /**
163
174
  * A row as reads return it: the generated interface itself where no column has a separate write type, so a
164
175
  * diagnostic names it (`DealsTable`), and Kysely's `Selectable` of it otherwise.
@@ -187,8 +198,11 @@ export type DbIndex<DB, P, V = unknown> = {
187
198
  readonly children: { readonly [T in ChildTableName<P> as ParentOf<P, T>]: T }
188
199
  /** Dimension → the dimension tables listed in it: those it contains, and a top-level table its own. */
189
200
  readonly listed: { readonly [T in DimensionTableName<P> as ListDimensionOf<P, T>]: T }
190
- /** Dimension → the tables an `over` of it lists: each whose containment chain holds it, and a top-level table its own. */
191
- readonly within: { readonly [T in DimensionTableName<P> | ChildTableName<P> as ReachOf<P, T, V>]: T }
201
+ /**
202
+ * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a top-level table its own, and
203
+ * each that reads through it (`readThrough`).
204
+ */
205
+ readonly within: { readonly [T in DimensionTableName<P> | ChildTableName<P> as ReachOf<P, T, V> | ReadThroughOf<P, T>]: T }
192
206
  readonly references: ReferenceTableName<P>
193
207
  /** The application tables: an `app` endpoint reads and writes them. */
194
208
  readonly applications: ApplicationTableName<P>
@@ -386,19 +400,21 @@ export interface UnownedTarget<D extends string> {
386
400
  readonly remove: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>
387
401
  }
388
402
 
389
- /** A child table of the target: its rows are addressed by their own key under the target. */
403
+ /** A child table of the target: its rows are addressed by their own key under the target; a view's are only read. */
390
404
  export interface ChildRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
391
405
  readonly list: Read<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>
392
406
  readonly get: Read<T, E, A, (key: string) => Promise<RowFor<E, A>>>
393
- readonly insert: Write<T, E, 'insert', A, K, InsertMethod<E>>
394
- readonly update: Update<
407
+ readonly insert: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`>
408
+ : Write<T, E, 'insert', A, K, InsertMethod<E>>
409
+ readonly update: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Update<
395
410
  T,
396
411
  E,
397
412
  A,
398
413
  K,
399
414
  (key: string, values: { [C in keyof UpdateValuesOf<E, A>]: UpdateValuesOf<E, A>[C] }, ...version: VersionArguments<E>) => Promise<Saved<E>>
400
415
  >
401
- readonly remove: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>
416
+ readonly remove: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`>
417
+ : Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>
402
418
  }
403
419
 
404
420
  /** A dimension table the target contains: listed in it, and inserted into it by a mutation of its insert action. */
@@ -603,19 +619,22 @@ export type UnscopedMode = 'read' | 'write'
603
619
  export type UnscopedDeclaration<Table extends string, Mode extends UnscopedMode> = { readonly [T in Table]?: Mode }
604
620
 
605
621
  /**
606
- * The tables of `U` whose mode may be `'write'` that no site writes: a reference table. A union or optional mode that
607
- * admits `'write'` counts, because the declaration it types may hold it.
622
+ * The tables of `U` whose mode may be `'write'` that no site writes: a reference table or a view. A union or optional
623
+ * mode that admits `'write'` counts, because the declaration it types may hold it.
608
624
  */
609
625
  type ReadOnlyWritten<Ix extends AnyDbIndex, U> = {
610
- [T in keyof U & TableName<Ix>]: 'write' extends U[T] ? Ix['tables'][T]['mode'] extends 'reference' ? T : never : never
626
+ [T in keyof U & TableName<Ix>]: 'write' extends U[T]
627
+ ? Ix['tables'][T]['mode'] extends 'reference' ? T : Ix['tables'][T]['view'] extends true ? T : never
628
+ : never
611
629
  }[keyof U & TableName<Ix>]
612
630
 
613
- type ReadOnlyMessage<T extends string> =
614
- `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`
631
+ type ReadOnlyMessage<T extends string, E extends IndexedTable> = E['view'] extends true
632
+ ? `${T} is a view, which no site writes: its rows come from the tables it reads, so declare unscoped: { ${T}: 'read' }`
633
+ : `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`
615
634
 
616
635
  /** An `unscoped` declaration's `'write'` of a reference table, refused at its own line. */
617
636
  export type ReadOnlyUnscoped<Ix extends AnyDbIndex, U> = [ReadOnlyWritten<Ix, U>] extends [never] ? unknown
618
- : { readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T>> }
637
+ : { readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T, Ix['tables'][T]>> }
619
638
 
620
639
  type KeylessMessage<T extends string> = `${T} is a reference table, which has no key: read it with list`
621
640