@fabrika/db 0.9.0-dev.12 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.12",
3
+ "version": "0.9.0-dev.13",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -92,9 +92,9 @@
92
92
  "test": "bun test"
93
93
  },
94
94
  "dependencies": {
95
- "@fabrika/auth-core": "0.9.0-dev.12",
96
- "@fabrika/platform": "0.9.0-dev.12",
97
- "@fabrika/platform-node": "0.9.0-dev.12",
95
+ "@fabrika/auth-core": "0.9.0-dev.13",
96
+ "@fabrika/platform": "0.9.0-dev.13",
97
+ "@fabrika/platform-node": "0.9.0-dev.13",
98
98
  "kysely": "0.29.6",
99
99
  "kysely-postgres-js": "5.0.1",
100
100
  "zod": "^3.25.76"
@@ -0,0 +1,254 @@
1
+ // What a capability admits of a table's rows beyond its containment: the relations it is held through and the
2
+ // condition its action holds a row under. Every predicate a capability scopes is built through `refScope`,
3
+ // `viewScope` or `conditioned`, so neither is left out of a statement by a builder that forgot it.
4
+
5
+ import { AndNode, BinaryOperationNode, type OperationNode, OperatorNode, ParensNode, ValueNode } from 'kysely'
6
+ import { ownEntry } from './builtins'
7
+ import type { RefGrant, WithinGrant } from './capability'
8
+ import { conditionNode, subquery } from './condition-nodes'
9
+ import { CapabilityError } from './errors'
10
+ import type { ViewParentLink } from './guard'
11
+ import { linksPredicate, linkValues } from './links'
12
+ import { allOf, anyOf, column, equals, valueList } from './nodes'
13
+ import {
14
+ type Container,
15
+ includes,
16
+ type MemberRevealModel,
17
+ nodeColumnOf,
18
+ type RelationSource,
19
+ type RevealModel,
20
+ type SecondaryPath,
21
+ type TableModel,
22
+ } from './policy'
23
+
24
+ /** A relation of the layer: its source table, and the tables whose rows it reaches reveal an ancestor node. */
25
+ export interface LayerRelation extends RelationSource {
26
+ readonly reveals: readonly RevealModel[]
27
+ }
28
+
29
+ /** Every relation of the layer, by name, with its source table. */
30
+ export type RelationSources = Readonly<Record<string, LayerRelation>>
31
+
32
+ /** Every member reveal of the layer, by the dimension whose grants it reveals to. */
33
+ export type MemberReveals = Readonly<Record<string, readonly MemberRevealModel[]>>
34
+
35
+ export function relationSource(relations: RelationSources, relation: string): LayerRelation {
36
+ const source = ownEntry(relations, relation)
37
+ if (source === undefined) {
38
+ throw new CapabilityError('unenforceable', `the capability is held through the relation ${relation}, which no table of the layer confers`)
39
+ }
40
+ return source
41
+ }
42
+
43
+ /** A source row that confers its relation now: unexpired, and admitted by the relation's own condition. */
44
+ export function activeRow(source: RelationSource, now: Date): readonly OperationNode[] {
45
+ const terms: OperationNode[] = []
46
+ if (source.expires !== undefined) {
47
+ const open = BinaryOperationNode.create(column(source.table, source.expires), OperatorNode.create('is'), ValueNode.createImmediate(null))
48
+ const ahead = BinaryOperationNode.create(column(source.table, source.expires), OperatorNode.create('>'), ValueNode.create(now))
49
+ terms[terms.length] = anyOf([open, ahead])
50
+ }
51
+ if (source.when !== undefined) {
52
+ terms[terms.length] = conditionNode(source.table, source.when, now)
53
+ }
54
+ return terms
55
+ }
56
+
57
+ /**
58
+ * A source row naming `principal`: `S.<principal> = $me`, or through its path `S.<column> in (select P.<key> from P where
59
+ * P.<column> = $me)`. Every check of a source row's principal is built here.
60
+ */
61
+ export function namesPrincipal(source: RelationSource, principal: string): OperationNode {
62
+ const path = source.principalPath
63
+ if (path === undefined) {
64
+ return equals(source.table, source.principal, principal)
65
+ }
66
+ return isIn(source.table, source.principal, subquery(path.table, path.key, equals(path.table, path.column, principal)))
67
+ }
68
+
69
+ /** `select S.<node> from S where <names principal> and <active>`: the nodes a relation holds `principal` at now. */
70
+ function relationNodes(source: RelationSource, principal: string, now: Date): OperationNode {
71
+ return subquery(source.table, source.node, allOf([namesPrincipal(source, principal), ...activeRow(source, now)]))
72
+ }
73
+
74
+ function isIn(table: string, name: string, nodes: OperationNode): OperationNode {
75
+ return BinaryOperationNode.create(column(table, name), OperatorNode.create('in'), nodes)
76
+ }
77
+
78
+ /**
79
+ * The rows of `table` whose `path` column names one of `nodes` of `dimension`: `T.<column> in (nodes)` at the path's own
80
+ * dimension, `T.<column> in (select D.<key> from D where D.<link> in (nodes))` at one above it; `undefined` elsewhere. A
81
+ * path through the nearest container reads the container's: `T.<link> in (select C.<key> from C where <C's term>)`.
82
+ */
83
+ export function throughPath(table: string, path: SecondaryPath, dimension: string, nodes: OperationNode): OperationNode | undefined {
84
+ const via = path.via
85
+ const term = pathTerm(via === undefined ? table : via.table, path, dimension, nodes)
86
+ return via === undefined || term === undefined ? term : isIn(table, via.column, subquery(via.table, via.key, term))
87
+ }
88
+
89
+ function pathTerm(table: string, path: SecondaryPath, dimension: string, nodes: OperationNode): OperationNode | undefined {
90
+ if (path.dimension === dimension) {
91
+ return isIn(table, path.column, nodes)
92
+ }
93
+ for (let index = 0; index < path.chain.length; index++) {
94
+ const link = path.chain[index]
95
+ if (link !== undefined && link.dimension === dimension) {
96
+ return isIn(table, path.column, subquery(path.table, path.key, isIn(path.table, link.column, nodes)))
97
+ }
98
+ }
99
+ return undefined
100
+ }
101
+
102
+ /** `select R.<ancestor> from R where R.<key> in (<the relation's nodes>) and <when>`: the nodes a reveal holds `principal` at. */
103
+ export function revealedNodes(source: RelationSource, reveal: RevealModel, principal: string, now: Date): OperationNode {
104
+ const nodes = relationNodes(source, principal, now)
105
+ const through = reveal.path === undefined ? undefined : throughPath(reveal.table, reveal.path, source.dimension, nodes)
106
+ const reached = through ?? isIn(reveal.table, reveal.key, nodes)
107
+ const where = reveal.when === undefined ? reached : AndNode.create(reached, ParensNode.create(conditionNode(reveal.table, reveal.when, now)))
108
+ return subquery(reveal.table, reveal.column, where)
109
+ }
110
+
111
+ /**
112
+ * The rows of `model` a relation reaches for `principal` under `action`: `T.<node> in (select S.<node> from S where
113
+ * S.<principal> = $me and <active>)` where `model` lies at a node of the relation's dimension, and one
114
+ * `T.<ancestor> in (<revealed nodes>)` per reveal of `action` to an ancestor `model` lies at. Empty where neither holds.
115
+ * A `Within`'s read (`reads`) also follows the secondary paths: the column `model` reaches the relation's dimension
116
+ * through, and the reveals matched through one. Every other statement follows containment only.
117
+ */
118
+ export function relationTerms(
119
+ relations: RelationSources,
120
+ model: TableModel,
121
+ relation: string,
122
+ principal: string,
123
+ action: string,
124
+ now: Date,
125
+ reads: boolean,
126
+ ): readonly OperationNode[] {
127
+ const source = relationSource(relations, relation)
128
+ const at = nodeColumnOf(model, source.dimension)
129
+ const terms: OperationNode[] = at === undefined ? [] : [isIn(model.name, at, relationNodes(source, principal, now))]
130
+ for (let index = 0; reads && index < model.readThrough.length; index++) {
131
+ const path = model.readThrough[index]
132
+ const through = path === undefined ? undefined : throughPath(model.name, path, source.dimension, relationNodes(source, principal, now))
133
+ if (through !== undefined) terms[terms.length] = through
134
+ }
135
+ for (let index = 0; index < source.reveals.length; index++) {
136
+ const reveal = source.reveals[index]
137
+ const held = reveal !== undefined && includes(reveal.actions, action) && (reads || reveal.path === undefined)
138
+ const placed = reveal === undefined || !held ? undefined : nodeColumnOf(model, reveal.dimension)
139
+ if (reveal !== undefined && placed !== undefined) {
140
+ terms[terms.length] = isIn(model.name, placed, revealedNodes(source, reveal, principal, now))
141
+ }
142
+ }
143
+ return terms
144
+ }
145
+
146
+ /**
147
+ * The rows of `model` a `Within`'s read reaches through member reveals: per grant it carries at a revealing dimension,
148
+ * `T.<ancestor> in (select R.<ancestor> from R where R.<key> in (values) and <when>)` for each reveal of `action` to an
149
+ * ancestor `model` lies at. A grant at a dimension that reveals no node for `action` is refused: the framework passes
150
+ * none.
151
+ */
152
+ export function memberTerms(members: MemberReveals, model: TableModel, grant: WithinGrant, now: Date): readonly OperationNode[] {
153
+ const terms: OperationNode[] = []
154
+ for (let index = 0; index < grant.revealing.length; index++) {
155
+ const revealing = grant.revealing[index]
156
+ if (revealing === undefined) continue
157
+ const reveals = ownEntry(members, revealing.dimension) ?? []
158
+ let named = false
159
+ for (let position = 0; position < reveals.length; position++) {
160
+ const reveal = reveals[position]
161
+ if (reveal === undefined || !includes(reveal.actions, grant.action)) continue
162
+ named = true
163
+ const placed = nodeColumnOf(model, reveal.dimension)
164
+ if (placed === undefined || revealing.values.length === 0) continue
165
+ const reached = isIn(reveal.table, reveal.key, valueList(revealing.values))
166
+ const where = reveal.when === undefined ? reached : AndNode.create(reached, ParensNode.create(conditionNode(reveal.table, reveal.when, now)))
167
+ terms[terms.length] = isIn(model.name, placed, subquery(reveal.table, reveal.column, where))
168
+ }
169
+ if (!named) {
170
+ throw new CapabilityError(
171
+ 'unenforceable',
172
+ `the Within of ${grant.dimension} carries a grant on ${revealing.dimension}, whose rows reveal no node for ${grant.action}`,
173
+ )
174
+ }
175
+ }
176
+ return terms
177
+ }
178
+
179
+ /** The condition `action` holds a row of `model` under, or `undefined` when the action is not narrowed there. */
180
+ export function actionCondition(model: TableModel, action: string, now: Date): OperationNode | undefined {
181
+ const condition = ownEntry(model.when, action)
182
+ return condition === undefined ? undefined : conditionNode(model.name, condition, now)
183
+ }
184
+
185
+ /**
186
+ * `branch`, narrowed by the condition of `action`: `<reach> and (<when>)`, for a global grant `true and (<when>)`, the
187
+ * one shape the guard admits a condition in, so a condition never stands in for the reach.
188
+ */
189
+ export function conditioned(model: TableModel, action: string, branch: OperationNode | 'all', now: Date): OperationNode {
190
+ const reach = branch === 'all' ? ValueNode.createImmediate(true) : branch
191
+ const condition = actionCondition(model, action, now)
192
+ return condition === undefined ? reach : AndNode.create(reach, ParensNode.create(condition))
193
+ }
194
+
195
+ /**
196
+ * A Ref's predicate over `links` of `model`: one equality per link of its chain (after `row`, the equality that
197
+ * addresses one row by its key), then, when the Ref is held through relations, a row of one of them at the node, and
198
+ * its action's condition. A relation that does not reach `model` leaves the Ref unenforceable there, never
199
+ * unconditioned.
200
+ */
201
+ export function refScope(
202
+ relations: RelationSources,
203
+ model: TableModel,
204
+ links: readonly Container[],
205
+ grant: RefGrant,
206
+ now: Date,
207
+ row?: OperationNode,
208
+ ): OperationNode {
209
+ const linked = linksPredicate(model.name, linkValues(model.name, links, grant))
210
+ const chain = row === undefined ? linked : allOf([row, linked])
211
+ const gate = relationGate(relations, model, grant, now)
212
+ return conditioned(model, grant.action, gate === undefined ? chain : allOf([chain, gate]), now)
213
+ }
214
+
215
+ /**
216
+ * The rows of a child view whose parent row `reached` admits: `V.<column> in (select P.<key> from P where <reached>)`,
217
+ * after `row` when it addresses one row, then the view's own condition of `action`. For `all`, every parent row, so a
218
+ * row whose parent column names none is still read by no capability. No column of the view places a row: its
219
+ * containment rests on the parent's foreign keys (ADR-0072).
220
+ */
221
+ export function viewScope(
222
+ model: TableModel,
223
+ parent: ViewParentLink,
224
+ action: string,
225
+ reached: OperationNode | 'all',
226
+ now: Date,
227
+ row?: OperationNode,
228
+ ): OperationNode {
229
+ const member = isIn(model.name, parent.column, subquery(parent.table, parent.key, reached === 'all' ? undefined : reached))
230
+ return conditioned(model, action, row === undefined ? member : allOf([row, member]), now)
231
+ }
232
+
233
+ /** The relation rows a Ref held through relations needs at `model`, or `undefined` for a Ref an IAM grant holds. */
234
+ export function relationGate(relations: RelationSources, model: TableModel, grant: RefGrant, now: Date): OperationNode | undefined {
235
+ if (grant.relations.length === 0) {
236
+ return undefined
237
+ }
238
+ const terms: OperationNode[] = []
239
+ for (let index = 0; index < grant.relations.length; index++) {
240
+ const relation = grant.relations[index] ?? ''
241
+ const reached = relationTerms(relations, model, relation, grant.principal, grant.action, now, false)
242
+ if (reached.length === 0) {
243
+ throw new CapabilityError(
244
+ 'unenforceable',
245
+ `the Ref of ${grant.dimension} is held through ${relation}, whose dimension ${model.name} carries no column for, and which reveals none of its nodes for ${grant.action}`,
246
+ )
247
+ }
248
+ for (let position = 0; position < reached.length; position++) {
249
+ const term = reached[position]
250
+ if (term !== undefined) terms[terms.length] = term
251
+ }
252
+ }
253
+ return anyOf(terms)
254
+ }
package/src/builtins.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { PolicyError } from './errors'
2
+
1
3
  // Captured when the module loads, before application code: a later patch to Object, Array, Map or their prototypes
2
4
  // does not change what these references do. Every policy and allowlist check goes through them and index loops,
3
5
  // never through an iterator, a spread or a method the checked value (or a mutable prototype) supplies.
@@ -92,3 +94,22 @@ export function defineValue(target: object, key: string, value: unknown): void {
92
94
  export function ownEntry<V>(record: Readonly<Record<string, V>>, key: string): V | undefined {
93
95
  return hasOwn(record, key) ? record[key] : undefined
94
96
  }
97
+
98
+ /** A copy of a plain object's own data properties; anything else (an instance, a symbol key, an accessor) is refused. */
99
+ export function plainRecord(value: unknown, what: string): Readonly<Record<string, unknown>> {
100
+ const prototype: unknown = typeof value === 'object' && value !== null && !isArray(value) ? prototypeOf(value) : undefined
101
+ if ((prototype !== OBJECT_PROTOTYPE && prototype !== null) || typeof value !== 'object' || value === null || ownSymbols(value).length > 0) {
102
+ throw new PolicyError(`${what} must be a plain object`)
103
+ }
104
+ const copy: Record<string, unknown> = {}
105
+ const keys = ownNames(value)
106
+ for (let index = 0; index < keys.length; index++) {
107
+ const key = keys[index] ?? ''
108
+ const descriptor = ownDescriptor(value, key)
109
+ if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
110
+ throw new PolicyError(`${what}: ${key} is an accessor; a policy holds plain values`)
111
+ }
112
+ setOwn(copy, key, descriptor.value)
113
+ }
114
+ return freeze(copy)
115
+ }
package/src/capability.ts CHANGED
@@ -36,6 +36,11 @@ export interface RefGrant {
36
36
  readonly id: string
37
37
  /** The values of the containers this object lies in, by dimension (`workspace → w1` for a note). */
38
38
  readonly chain: ReadonlyMap<string, string>
39
+ /**
40
+ * The relations the caller holds the action through on this object or a container, when no grant holds it: every
41
+ * statement of the Ref then also requires a row of one of them. Empty for a Ref an IAM grant holds.
42
+ */
43
+ readonly relations: readonly string[]
39
44
  }
40
45
 
41
46
  /** The values of one container dimension in which the caller holds the action: `organization → [o1]`. */
@@ -67,6 +72,16 @@ export interface WithinGrant {
67
72
  * the action: a row that lies in one of their values is listed, as a single-object read of it is allowed.
68
73
  */
69
74
  readonly contained: readonly ContainerGrant[]
75
+ /**
76
+ * The relations through which the caller also holds the action (`~rel` entries of its token): a row lies in the
77
+ * `Within` too where a row of one of them names the caller at the row's node, read by the statement itself.
78
+ */
79
+ readonly relations: readonly string[]
80
+ /**
81
+ * The caller's grants of the action at nodes whose rows reveal the `Within`'s dimension or a container of it to their
82
+ * members (`memberReveals`): a row under a node such a row reveals is read too, the statement judging the revealing row.
83
+ */
84
+ readonly revealing: readonly ContainerGrant[]
70
85
  }
71
86
 
72
87
  /** An `app` endpoint's grant: the action everywhere in the application, which the proxy checked was held globally. */
package/src/codegen.ts CHANGED
@@ -8,6 +8,8 @@ export const SCHEMA_FILE = 'src/db/schema.generated.ts'
8
8
 
9
9
  /** Framework tables (the migration ledger, and later files, job leases, webhook deliveries) are not application tables. */
10
10
  const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
11
+ /** The formatter's line width (`dprint.json`), a tab counted as one column: a longer line it would break. */
12
+ const LINE_WIDTH = 150
11
13
 
12
14
  const HEADER = '// @generated by fabrika db codegen from the migrated database. Do not edit: write a migration, then run fabrika db codegen.'
13
15
 
@@ -449,8 +451,16 @@ export function renderTables<C extends RelationColumn>(
449
451
  const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
450
452
  return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
451
453
  }
454
+ // The NOT NULL columns, which a foreign key that holds a row's tenant needs its ancestor columns among. A list past
455
+ // the formatter's line width goes one column per line, as `columns` does, so the module stays formatter-stable.
456
+ const notNullOf = (table: string): string => {
457
+ const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.nullable === false).map((column) => quote(column.column_name))
458
+ if (listed.length === 0) return ''
459
+ const line = `\t\tnotNull: [${listed.join(', ')}],`
460
+ return line.length <= LINE_WIDTH ? `${line}\n` : `\t\tnotNull: [\n${listed.map((name) => `\t\t\t${name},\n`).join('')}\t\t],\n`
461
+ }
452
462
  const datesOf = (table: string): string =>
453
- `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}`
463
+ `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}${notNullOf(table)}`
454
464
  const columns = rendered
455
465
  .map((table) =>
456
466
  `\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
@@ -0,0 +1,119 @@
1
+ // The predicate of a structured row condition, and the one subquery shape a scope predicate holds. Apart from the
2
+ // parse in `conditions.ts`, which `@fabrika/db/tables` loads in a browser without Kysely.
3
+
4
+ import {
5
+ BinaryOperationNode,
6
+ ColumnNode,
7
+ type OperationNode,
8
+ OperatorNode,
9
+ ParensNode,
10
+ QueryNode,
11
+ ReferenceNode,
12
+ SelectionNode,
13
+ SelectQueryNode,
14
+ TableNode,
15
+ UnaryOperationNode,
16
+ ValueListNode,
17
+ ValueNode,
18
+ } from 'kysely'
19
+ import { isArray } from './builtins'
20
+ import { type ConditionHop, type ConditionLiteral, type ConditionModel, NOW, type NowOperand, scalar } from './conditions'
21
+ import { allOf, anyOf, column } from './nodes'
22
+
23
+ function comparison(operator: 'eq' | 'notEq' | 'lt' | 'lte' | 'gt' | 'gte'): OperatorNode {
24
+ switch (operator) {
25
+ case 'eq':
26
+ return OperatorNode.create('=')
27
+ case 'notEq':
28
+ return OperatorNode.create('<>')
29
+ case 'lt':
30
+ return OperatorNode.create('<')
31
+ case 'lte':
32
+ return OperatorNode.create('<=')
33
+ case 'gt':
34
+ return OperatorNode.create('>')
35
+ case 'gte':
36
+ return OperatorNode.create('>=')
37
+ }
38
+ }
39
+
40
+ /** The predicate of `condition` over `table`'s rows; `now` is the statement's clock, bound as a value. */
41
+ export function conditionNode(table: string, condition: ConditionModel, now: Date): OperationNode {
42
+ switch (condition.kind) {
43
+ case 'all':
44
+ return ParensNode.create(allOf(nodesOf(table, condition.terms, now)))
45
+ case 'any':
46
+ return anyOf(nodesOf(table, condition.terms, now))
47
+ case 'not':
48
+ return UnaryOperationNode.create(OperatorNode.create('not'), ParensNode.create(conditionNode(table, condition.term, now)))
49
+ case 'some':
50
+ return alongPath(table, condition.hops, 0, (target) => {
51
+ // The rows of the other table whose key names this row: a null key names none, so `not in` never turns unknown.
52
+ const named = BinaryOperationNode.create(
53
+ column(condition.table, condition.column),
54
+ OperatorNode.create('is not'),
55
+ ValueNode.createImmediate(null),
56
+ )
57
+ const rows = subquery(condition.table, condition.column, allOf([named, ParensNode.create(conditionNode(condition.table, condition.term, now))]))
58
+ const some = BinaryOperationNode.create(column(target, condition.key), OperatorNode.create('in'), rows)
59
+ return condition.negated ? UnaryOperationNode.create(OperatorNode.create('not'), ParensNode.create(some)) : some
60
+ })
61
+ case 'test':
62
+ return alongPath(table, condition.hops, 0, (target) => testNode(target, condition, now))
63
+ }
64
+ }
65
+
66
+ function nodesOf(table: string, terms: readonly ConditionModel[], now: Date): OperationNode[] {
67
+ const nodes: OperationNode[] = []
68
+ for (let index = 0; index < terms.length; index++) {
69
+ const term = terms[index]
70
+ if (term !== undefined) nodes[nodes.length] = conditionNode(table, term, now)
71
+ }
72
+ return nodes
73
+ }
74
+
75
+ /** `table.fk in (select target.key from target where …)` per hop, then `leaf` over the row the path reaches. */
76
+ function alongPath(table: string, hops: readonly ConditionHop[], position: number, leaf: (table: string) => OperationNode): OperationNode {
77
+ const hop = hops[position]
78
+ if (hop === undefined) {
79
+ return leaf(table)
80
+ }
81
+ const inner = alongPath(hop.table, hops, position + 1, leaf)
82
+ return BinaryOperationNode.create(column(table, hop.column), OperatorNode.create('in'), subquery(hop.table, hop.key, inner))
83
+ }
84
+
85
+ /** A column's own test. */
86
+ function testNode(table: string, test: Extract<ConditionModel, { kind: 'test' }>, now: Date): OperationNode {
87
+ const left = column(table, test.column)
88
+ const value = test.value
89
+ switch (test.operator) {
90
+ case 'isNull':
91
+ return BinaryOperationNode.create(left, OperatorNode.create(value === true ? 'is' : 'is not'), ValueNode.createImmediate(null))
92
+ case 'in':
93
+ case 'notIn':
94
+ return BinaryOperationNode.create(left, OperatorNode.create(test.operator === 'in' ? 'in' : 'not in'), ValueListNode.create(literals(value)))
95
+ default:
96
+ return BinaryOperationNode.create(left, comparison(test.operator), ValueNode.create(value === NOW ? now : scalar(value)))
97
+ }
98
+ }
99
+
100
+ function literals(value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand): ValueNode[] {
101
+ const nodes: ValueNode[] = []
102
+ if (isArray(value)) {
103
+ for (let index = 0; index < value.length; index++) {
104
+ nodes[nodes.length] = ValueNode.create(value[index])
105
+ }
106
+ }
107
+ return nodes
108
+ }
109
+
110
+ /**
111
+ * `select table.key from table where <where>`: the one subquery shape the guard admits in a scope predicate. Without
112
+ * `where`, every row's key: only a child view's parent subquery takes that form.
113
+ */
114
+ export function subquery(table: string, key: string, where?: OperationNode): OperationNode {
115
+ const select = SelectQueryNode.cloneWithSelections(SelectQueryNode.createFrom([TableNode.create(table)]), [
116
+ SelectionNode.create(ReferenceNode.create(ColumnNode.create(key), TableNode.create(table))),
117
+ ])
118
+ return where === undefined ? select : QueryNode.cloneWithWhere(select, where)
119
+ }