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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,683 @@
1
+ // Structured row conditions: the `when` of a table action and of a relation source. One parse over values nobody
2
+ // type-checked, one predicate builder, and the value of a condition on an insert's own row. Index loops and the
3
+ // captured built-ins only, as in the policy parse. No Kysely runtime: `@fabrika/db/tables` reads the parse in a
4
+ // browser; `condition-nodes.ts` builds the predicate.
5
+
6
+ import type { ColumnTestArtifact, ConditionArtifact, RowsTestArtifact } from '@fabrika/auth-core'
7
+ import { freeze, hasOwn, inSet, isArray, type NameSet, ownEntry, ownKeys, parseList, plainRecord } from './builtins'
8
+ import type { Primitive } from './description'
9
+ import { PolicyError } from './errors'
10
+
11
+ /** A literal a condition compares with. `{ now: true }` is the statement's clock, never the text `now`. */
12
+ export type ConditionLiteral = string | number | boolean
13
+ export interface NowOperand {
14
+ readonly now: true
15
+ }
16
+ /** The parsed clock operand, compared by identity: no literal, the text `now` included, is ever it. */
17
+ export const NOW: NowOperand = freeze({ now: true })
18
+
19
+ /** One test of a column: exactly one operator. */
20
+ export interface ColumnTest {
21
+ readonly eq?: ConditionLiteral
22
+ readonly notEq?: ConditionLiteral
23
+ readonly in?: readonly ConditionLiteral[]
24
+ readonly notIn?: readonly ConditionLiteral[]
25
+ readonly isNull?: boolean
26
+ readonly lt?: ConditionLiteral | NowOperand
27
+ readonly lte?: ConditionLiteral | NowOperand
28
+ readonly gt?: ConditionLiteral | NowOperand
29
+ readonly gte?: ConditionLiteral | NowOperand
30
+ }
31
+
32
+ /** `{ some: { table: … } }` or `{ none: { table: … } }` at the end of a path: over the rows naming the row it reaches. */
33
+ export type RowsTest =
34
+ | { readonly some: { readonly [table: string]: ConditionPolicy } }
35
+ | { readonly none: { readonly [table: string]: ConditionPolicy } }
36
+
37
+ /**
38
+ * A condition as a policy writes it: `{ column: test, … }` (all of them), `{ 'fk_column.column': test }` along a
39
+ * foreign key, `{ anyOf: […] }`, `{ allOf: […] }`, `{ not: … }`, or `{ some: { table: … } }` and `{ none: { table: … } }`
40
+ * over the rows of `table` whose foreign key names the row; `{ 'fk_column': { some: { table: … } } }` over the rows
41
+ * naming the row a path reaches.
42
+ */
43
+ export type ConditionPolicy<Col extends string = string> =
44
+ | { readonly anyOf: readonly ConditionPolicy<Col>[] }
45
+ | { readonly allOf: readonly ConditionPolicy<Col>[] }
46
+ | { readonly not: ConditionPolicy<Col> }
47
+ | { readonly some: { readonly [table: string]: ConditionPolicy } }
48
+ | { readonly none: { readonly [table: string]: ConditionPolicy } }
49
+ | { readonly [C in Col | `${Col}.${string}`]?: ColumnTest | RowsTest }
50
+
51
+ export type ConditionOperator = 'eq' | 'notEq' | 'in' | 'notIn' | 'isNull' | 'lt' | 'lte' | 'gt' | 'gte'
52
+
53
+ /** One foreign-key hop of a path: `column` of the table it leaves references `key` of `table`. */
54
+ export interface ConditionHop {
55
+ readonly column: string
56
+ readonly table: string
57
+ readonly key: string
58
+ }
59
+
60
+ export type ConditionModel =
61
+ | { readonly kind: 'all'; readonly terms: readonly ConditionModel[] }
62
+ | { readonly kind: 'any'; readonly terms: readonly ConditionModel[] }
63
+ | { readonly kind: 'not'; readonly term: ConditionModel }
64
+ | {
65
+ /**
66
+ * `key in (select table.column from table where <term>)`, or its negation for `none`, over the row `hops` reach
67
+ * from the condition's own row (none: the row itself).
68
+ */
69
+ readonly kind: 'some'
70
+ readonly hops: readonly ConditionHop[]
71
+ readonly negated: boolean
72
+ readonly key: string
73
+ readonly table: string
74
+ readonly column: string
75
+ readonly term: ConditionModel
76
+ }
77
+ | {
78
+ readonly kind: 'test'
79
+ readonly hops: readonly ConditionHop[]
80
+ readonly column: string
81
+ readonly operator: ConditionOperator
82
+ readonly value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand
83
+ }
84
+
85
+ /** What the parse reads of each table: its columns, its foreign keys and its typed columns. */
86
+ export interface ConditionTable {
87
+ readonly name: string
88
+ readonly columns: NameSet
89
+ readonly foreignKeys: readonly { readonly columns: readonly string[]; readonly table: string; readonly references: readonly string[] }[]
90
+ readonly timestamps: NameSet
91
+ readonly json: NameSet
92
+ /** The columns the column list declares NOT NULL: a path under `not` follows only these. */
93
+ readonly notNull: NameSet
94
+ }
95
+
96
+ /** A path follows at most this many foreign keys: each hop is one more subquery in every statement the condition scopes. */
97
+ export const MAX_CONDITION_HOPS = 3
98
+ const MAX_CONDITION_DEPTH = 8
99
+ const OPERATORS: readonly ConditionOperator[] = freeze(['eq', 'notEq', 'in', 'notIn', 'isNull', 'lt', 'lte', 'gt', 'gte'])
100
+ const CONNECTIVES = freeze(['anyOf', 'allOf', 'not', 'some', 'none'])
101
+
102
+ /**
103
+ * Whether a path may follow `from.column` to the row of `to` whose `key` it holds. A hop reads its target unscoped, so
104
+ * the rule admits only one that stays where the row is (its own container or parent), stays in its tenant (a foreign
105
+ * key that also holds every ancestor the two tables share), or reaches what every site reads (a reference table).
106
+ * `backward` is a `some` reading the rows of `from` that name a row of `to`: those must stay in that row's tenant, so
107
+ * a reference row, which every tenant's rows name, is no shortcut there.
108
+ */
109
+ export type HopRule = (from: string, column: string, to: string, key: string, backward: boolean) => boolean
110
+
111
+ /** Parses `input` as a condition over `table`. `hops` is the rule a path's foreign keys are held to. */
112
+ export function parseCondition(
113
+ input: unknown,
114
+ table: ConditionTable,
115
+ tables: (name: string) => ConditionTable | undefined,
116
+ what: string,
117
+ hops: HopRule,
118
+ ): ConditionModel {
119
+ return parseNode(input, table, tables, what, hops, 0, 0, false)
120
+ }
121
+
122
+ const HOP_LIMIT = `a path follows at most ${MAX_CONDITION_HOPS} foreign keys, a some or none counted as one`
123
+
124
+ /**
125
+ * `level` counts the `some` and `none` subqueries around the node: each takes one of a path's foreign keys. `negated`
126
+ * holds under any `not` around it.
127
+ */
128
+ function parseNode(
129
+ input: unknown,
130
+ table: ConditionTable,
131
+ tables: (name: string) => ConditionTable | undefined,
132
+ what: string,
133
+ hops: HopRule,
134
+ depth: number,
135
+ level: number,
136
+ negated: boolean,
137
+ ): ConditionModel {
138
+ if (depth > MAX_CONDITION_DEPTH) {
139
+ throw new PolicyError(`${what} nests deeper than ${MAX_CONDITION_DEPTH} levels`)
140
+ }
141
+ const record = plainRecord(input, what)
142
+ const keys = ownKeys(record)
143
+ if (keys.length === 0) {
144
+ throw new PolicyError(`${what} is empty: a condition tests at least one column`)
145
+ }
146
+ const first = keys[0] ?? ''
147
+ if (keys.length === 1 && (first === 'anyOf' || first === 'allOf')) {
148
+ const items = parseList(ownEntry(record, first), (item) => parseNode(item, table, tables, `${what}.${first}`, hops, depth + 1, level, negated))
149
+ if (items === undefined || items.length === 0) {
150
+ throw new PolicyError(`${what}.${first} takes a non-empty plain array of conditions`)
151
+ }
152
+ return freeze({ kind: first === 'anyOf' ? 'any' : 'all', terms: freeze(items) })
153
+ }
154
+ if (keys.length === 1 && first === 'not') {
155
+ return freeze({ kind: 'not', term: parseNode(ownEntry(record, 'not'), table, tables, `${what}.not`, hops, depth + 1, level, true) })
156
+ }
157
+ if (keys.length === 1 && (first === 'some' || first === 'none')) {
158
+ return parseSome(first, ownEntry(record, first), [], table, tables, `${what}.${first}`, hops, depth, level, negated)
159
+ }
160
+ const terms: ConditionModel[] = []
161
+ for (let index = 0; index < keys.length; index++) {
162
+ const key = keys[index] ?? ''
163
+ for (let connective = 0; connective < CONNECTIVES.length; connective++) {
164
+ if (key === CONNECTIVES[connective]) {
165
+ throw new PolicyError(`${what}: ${key} stands alone in its object; wrap the column tests beside it in allOf`)
166
+ }
167
+ }
168
+ terms[terms.length] = parseTest(key, ownEntry(record, key), table, tables, `${what}.${key}`, hops, depth, level, negated)
169
+ }
170
+ const only = terms[0]
171
+ return terms.length === 1 && only !== undefined ? only : freeze({ kind: 'all', terms: freeze(terms) })
172
+ }
173
+
174
+ function parseTest(
175
+ path: string,
176
+ input: unknown,
177
+ table: ConditionTable,
178
+ tables: (name: string) => ConditionTable | undefined,
179
+ what: string,
180
+ hops: HopRule,
181
+ depth: number,
182
+ level: number,
183
+ negated: boolean,
184
+ ): ConditionModel {
185
+ const segments = splitPath(path)
186
+ const test = plainRecord(input, what)
187
+ const operators = ownKeys(test)
188
+ const only = operators[0]
189
+ // `{ 'fk_column': { some: … } }`: every segment is a foreign key, and the rows test is one more hop past them.
190
+ const rows = operators.length === 1 && (only === 'some' || only === 'none') ? only : undefined
191
+ const followedCount = rows === undefined ? segments.length - 1 : segments.length
192
+ if (followedCount + (rows === undefined ? 0 : 1) + level > MAX_CONDITION_HOPS) {
193
+ throw new PolicyError(`${what}: ${HOP_LIMIT}`)
194
+ }
195
+ const followed: ConditionHop[] = []
196
+ let current = table
197
+ for (let index = 0; index < followedCount; index++) {
198
+ const name = segments[index] ?? ''
199
+ const hop = singleForeignKey(current, name, what)
200
+ const target = tables(hop.table)
201
+ if (target === undefined) {
202
+ throw new PolicyError(`${what}: ${current.name}.${name} references ${hop.table}, which has no policy`)
203
+ }
204
+ // A hop's subquery reads its target unscoped: on a null key it is false while no row anywhere matches and unknown
205
+ // otherwise, so under `not` the row would turn on rows of every tenant.
206
+ if (negated && !inSet(current.notNull, name)) {
207
+ throw new PolicyError(
208
+ `${what}: ${current.name}.${name} may be null, and under not a path through a null key holds exactly when no row of ${hop.table} in any tenant matches; declare ${current.name}.${name} NOT NULL and run fabrika db codegen, or drop the not`,
209
+ )
210
+ }
211
+ if (!hops(current.name, name, hop.table, hop.key, false)) {
212
+ throw new PolicyError(
213
+ `${what}: ${current.name}.${name} leads to ${hop.table}, outside the row's own containment; a path follows a row's container or parent column, a foreign key that also holds every ancestor the two tables share, or reaches a reference table`,
214
+ )
215
+ }
216
+ followed[followed.length] = hop
217
+ current = target
218
+ }
219
+ if (rows !== undefined) {
220
+ return parseSome(rows, ownEntry(test, rows), freeze(followed), current, tables, `${what}.${rows}`, hops, depth, level + followedCount, negated)
221
+ }
222
+ const columnName = segments[segments.length - 1] ?? ''
223
+ if (!inSet(current.columns, columnName)) {
224
+ throw new PolicyError(`${what}: ${columnName} is not a column of ${current.name}`)
225
+ }
226
+ if (inSet(current.json, columnName)) {
227
+ throw new PolicyError(`${what}: ${current.name}.${columnName} is a JSON column, which no condition compares`)
228
+ }
229
+ if (operators.length !== 1) {
230
+ throw new PolicyError(`${what} takes exactly one operator (${OPERATORS.join(', ')})`)
231
+ }
232
+ const operator = operatorOf(only, what)
233
+ const raw = ownEntry(test, operator)
234
+ return freeze({
235
+ kind: 'test',
236
+ hops: freeze(followed),
237
+ column: columnName,
238
+ operator,
239
+ value: operandOf(operator, raw, inSet(current.timestamps, columnName), what),
240
+ })
241
+ }
242
+
243
+ /**
244
+ * `{ some: { <table>: <condition> } }`: a row of `table` whose foreign key names this row meets the condition; `none`:
245
+ * no such row does. The foreign key is held to the path rule from `table`'s side, so the rows read lie in this row's
246
+ * own tenant: a child's parent column, a contained dimension's container column, or a key that holds the tenant.
247
+ * After a path (`path`), `table` is the row it reaches and `level` counts its hops.
248
+ */
249
+ function parseSome(
250
+ kind: 'some' | 'none',
251
+ input: unknown,
252
+ path: readonly ConditionHop[],
253
+ table: ConditionTable,
254
+ tables: (name: string) => ConditionTable | undefined,
255
+ what: string,
256
+ hops: HopRule,
257
+ depth: number,
258
+ level: number,
259
+ negated: boolean,
260
+ ): ConditionModel {
261
+ if (level + 1 > MAX_CONDITION_HOPS) {
262
+ throw new PolicyError(`${what}: ${HOP_LIMIT}`)
263
+ }
264
+ const record = plainRecord(input, what)
265
+ const names = ownKeys(record)
266
+ const name = names[0] ?? ''
267
+ if (names.length !== 1) {
268
+ throw new PolicyError(`${what} names exactly one table`)
269
+ }
270
+ const child = tables(name)
271
+ if (child === undefined) {
272
+ throw new PolicyError(`${what}: ${name} is not a table with a policy`)
273
+ }
274
+ let found: ConditionHop | undefined
275
+ let count = 0
276
+ for (let index = 0; index < child.foreignKeys.length; index++) {
277
+ const key = child.foreignKeys[index]
278
+ if (key !== undefined && key.columns.length === 1 && key.table === table.name) {
279
+ found = freeze({ column: key.columns[0] ?? '', table: name, key: key.references[0] ?? '' })
280
+ count++
281
+ }
282
+ }
283
+ if (found === undefined || count !== 1) {
284
+ throw new PolicyError(
285
+ found === undefined
286
+ ? `${what}: ${name} has no single-column foreign key to ${table.name}`
287
+ : `${what}: ${name} has ${count} single-column foreign keys to ${table.name}, so the rows it names are not one set`,
288
+ )
289
+ }
290
+ if (!hops(name, found.column, table.name, found.key, true)) {
291
+ throw new PolicyError(
292
+ `${what}: ${name}.${found.column} is outside ${table.name}'s containment; the rows read follow a child's parent column, a contained dimension's container column, or a foreign key that also holds every ancestor the two tables share, never a key into a reference table, whose rows every tenant's rows name`,
293
+ )
294
+ }
295
+ const term = parseNode(ownEntry(record, name), child, tables, `${what}.${name}`, hops, depth + 1, level + 1, negated)
296
+ return freeze({ kind: 'some', hops: path, negated: kind === 'none', key: found.key, table: name, column: found.column, term })
297
+ }
298
+
299
+ export function splitPath(path: string): readonly string[] {
300
+ const segments: string[] = []
301
+ let start = 0
302
+ for (let index = 0; index <= path.length; index++) {
303
+ if (index === path.length || path[index] === '.') {
304
+ segments[segments.length] = path.slice(start, index)
305
+ start = index + 1
306
+ }
307
+ }
308
+ return segments
309
+ }
310
+
311
+ export function singleForeignKey(table: ConditionTable, name: string, what: string): ConditionHop {
312
+ if (!inSet(table.columns, name)) {
313
+ throw new PolicyError(`${what}: ${name} is not a column of ${table.name}`)
314
+ }
315
+ for (let index = 0; index < table.foreignKeys.length; index++) {
316
+ const key = table.foreignKeys[index]
317
+ if (key !== undefined && key.columns.length === 1 && key.columns[0] === name) {
318
+ return freeze({ column: name, table: key.table, key: key.references[0] ?? '' })
319
+ }
320
+ }
321
+ throw new PolicyError(`${what}: ${table.name}.${name} is not a single-column foreign key, so a path cannot follow it`)
322
+ }
323
+
324
+ function operatorOf(name: unknown, what: string): ConditionOperator {
325
+ for (let index = 0; index < OPERATORS.length; index++) {
326
+ const candidate = OPERATORS[index]
327
+ if (candidate !== undefined && candidate === name) {
328
+ return candidate
329
+ }
330
+ }
331
+ throw new PolicyError(`${what}: ${String(name)} is not an operator (${OPERATORS.join(', ')})`)
332
+ }
333
+
334
+ function literalOf(value: unknown, what: string): ConditionLiteral {
335
+ if (typeof value === 'string' || typeof value === 'boolean' || (typeof value === 'number' && Number.isFinite(value))) {
336
+ return value
337
+ }
338
+ throw new PolicyError(`${what} compares with a string, a finite number or a boolean`)
339
+ }
340
+
341
+ function operandOf(
342
+ operator: ConditionOperator,
343
+ value: unknown,
344
+ timestamp: boolean,
345
+ what: string,
346
+ ): ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand {
347
+ if (operator === 'isNull') {
348
+ if (typeof value !== 'boolean') {
349
+ throw new PolicyError(`${what}.isNull takes true or false`)
350
+ }
351
+ return value
352
+ }
353
+ if (operator === 'in' || operator === 'notIn') {
354
+ const items = parseList(value, (item) => literalOf(item, `${what}.${operator}`))
355
+ if (items === undefined || items.length === 0) {
356
+ throw new PolicyError(`${what}.${operator} takes a non-empty plain array of literals`)
357
+ }
358
+ return freeze(items)
359
+ }
360
+ if (typeof value === 'object' && value !== null && !isArray(value)) {
361
+ const record = plainRecord(value, what)
362
+ const keys = ownKeys(record)
363
+ if (keys.length !== 1 || keys[0] !== 'now' || ownEntry(record, 'now') !== true) {
364
+ throw new PolicyError(`${what}.${operator} takes a literal or { now: true }`)
365
+ }
366
+ if (operator === 'eq' || operator === 'notEq') {
367
+ throw new PolicyError(`${what}.${operator}: { now: true } is compared with lt, lte, gt or gte`)
368
+ }
369
+ if (!timestamp) {
370
+ throw new PolicyError(`${what}: { now: true } is compared with a timestamp column only`)
371
+ }
372
+ return NOW
373
+ }
374
+ return literalOf(value, `${what}.${operator}`)
375
+ }
376
+
377
+ /** The tables a condition's subqueries read, each with the column it selects: what the guard admits under it. */
378
+ export function conditionReach(condition: ConditionModel, select: (table: string, column: string) => void): void {
379
+ if (condition.kind === 'not') {
380
+ conditionReach(condition.term, select)
381
+ return
382
+ }
383
+ if (condition.kind === 'some') {
384
+ for (let index = 0; index < condition.hops.length; index++) {
385
+ const hop = condition.hops[index]
386
+ if (hop !== undefined) select(hop.table, hop.key)
387
+ }
388
+ select(condition.table, condition.column)
389
+ conditionReach(condition.term, select)
390
+ return
391
+ }
392
+ if (condition.kind !== 'test') {
393
+ for (let index = 0; index < condition.terms.length; index++) {
394
+ const term = condition.terms[index]
395
+ if (term !== undefined) conditionReach(term, select)
396
+ }
397
+ return
398
+ }
399
+ for (let index = 0; index < condition.hops.length; index++) {
400
+ const hop = condition.hops[index]
401
+ if (hop !== undefined) select(hop.table, hop.key)
402
+ }
403
+ }
404
+
405
+ /** A test's single literal; a list is compared only with in or notIn. */
406
+ export function scalar(value: ConditionLiteral | readonly ConditionLiteral[] | boolean | NowOperand): ConditionLiteral {
407
+ if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') {
408
+ return value
409
+ }
410
+ throw new PolicyError('a list is compared with in or notIn')
411
+ }
412
+
413
+ /**
414
+ * One step of the rows an insert's condition reads: from the rows reached so far, the rows of `table` whose `to` column
415
+ * holds their `from` column. A path's hop goes to the row a foreign key names (`from` the key column, `to` the target's
416
+ * key); a `some` goes back to the rows naming it (`from` the referenced key, `to` the naming column).
417
+ */
418
+ export interface ReadStep {
419
+ readonly from: string
420
+ readonly table: string
421
+ readonly to: string
422
+ }
423
+
424
+ /**
425
+ * Every sequence of steps from an insert's own row to the rows its condition reads, each one no other extends: the rows
426
+ * the insert locks, step by step, before it judges them. Empty when the condition reads the row alone.
427
+ */
428
+ export function readPaths(condition: ConditionModel): readonly (readonly ReadStep[])[] {
429
+ const paths: (readonly ReadStep[])[] = []
430
+ const hopSteps = (prefix: readonly ReadStep[], hops: readonly ConditionHop[]): ReadStep[] => {
431
+ const steps: ReadStep[] = [...prefix]
432
+ for (let index = 0; index < hops.length; index++) {
433
+ const hop = hops[index]
434
+ if (hop !== undefined) steps[steps.length] = freeze({ from: hop.column, table: hop.table, to: hop.key })
435
+ }
436
+ return steps
437
+ }
438
+ const visit = (node: ConditionModel, prefix: readonly ReadStep[]): void => {
439
+ if (node.kind === 'not') {
440
+ visit(node.term, prefix)
441
+ } else if (node.kind === 'test') {
442
+ if (node.hops.length > 0) paths[paths.length] = freeze(hopSteps(prefix, node.hops))
443
+ } else if (node.kind === 'some') {
444
+ const steps = hopSteps(prefix, node.hops)
445
+ steps[steps.length] = freeze({ from: node.key, table: node.table, to: node.column })
446
+ paths[paths.length] = freeze(steps)
447
+ visit(node.term, steps)
448
+ } else {
449
+ for (let index = 0; index < node.terms.length; index++) {
450
+ const term = node.terms[index]
451
+ if (term !== undefined) visit(term, prefix)
452
+ }
453
+ }
454
+ }
455
+ visit(condition, [])
456
+ const kept: (readonly ReadStep[])[] = []
457
+ for (let index = 0; index < paths.length; index++) {
458
+ const path = paths[index] ?? []
459
+ let extended = false
460
+ for (let other = 0; other < paths.length && !extended; other++) {
461
+ const longer = paths[other] ?? []
462
+ extended = other !== index && longer.length > path.length && startsWith(longer, path)
463
+ }
464
+ if (!extended) kept[kept.length] = path
465
+ }
466
+ return freeze(kept)
467
+ }
468
+
469
+ function startsWith(path: readonly ReadStep[], prefix: readonly ReadStep[]): boolean {
470
+ for (let index = 0; index < prefix.length; index++) {
471
+ const step = prefix[index]
472
+ const same = path[index]
473
+ if (step === undefined || same === undefined || step.from !== same.from || step.table !== same.table || step.to !== same.to) return false
474
+ }
475
+ return true
476
+ }
477
+
478
+ /**
479
+ * Why `condition` cannot be judged on an inserted row, or `undefined` when it can. The insert locks every row its
480
+ * condition reads, which holds a column test and a row a `some` found until the commit, but not a row inserted meanwhile:
481
+ * that turns `none`, and a `some` under `not`, false. And no row names the inserted row before it exists.
482
+ */
483
+ export function insertProblem(condition: ConditionModel, table: string): string | undefined {
484
+ const visit = (node: ConditionModel, negated: boolean, past: boolean): string | undefined => {
485
+ if (node.kind === 'not') return visit(node.term, true, past)
486
+ if (node.kind === 'test') return undefined
487
+ if (node.kind === 'some') {
488
+ if (!past && node.hops.length === 0) {
489
+ return "an insert's condition takes no some or none of the rows naming the inserted row: no row names a row that does not exist yet; follow a path first, such as { project_id: { some: … } }"
490
+ }
491
+ if (node.table === table) {
492
+ return `an insert's condition takes no some of ${table}'s own rows: it is judged after the write, so the inserted row would count itself`
493
+ }
494
+ if (node.negated || negated) {
495
+ return "an insert's condition takes no none, and no some under not: a row inserted before the commit could make it false, which no lock on the rows it read holds"
496
+ }
497
+ return visit(node.term, negated, true)
498
+ }
499
+ for (let index = 0; index < node.terms.length; index++) {
500
+ const term = node.terms[index]
501
+ const problem = term === undefined ? undefined : visit(term, negated, past)
502
+ if (problem !== undefined) return problem
503
+ }
504
+ return undefined
505
+ }
506
+ return visit(condition, false, false)
507
+ }
508
+
509
+ /**
510
+ * The value of `condition` on an insert's own row, under SQL's three-valued logic: a NULL compared is unknown, `not`
511
+ * of unknown stays unknown, and only `true` passes. A condition with a path is judged in SQL on the written row instead.
512
+ */
513
+ export function rowSatisfies(condition: ConditionModel, row: ReadonlyMap<string, Primitive | null>, now: Date): boolean {
514
+ return truth(condition, row, now) === true
515
+ }
516
+
517
+ function truth(condition: ConditionModel, row: ReadonlyMap<string, Primitive | null>, now: Date): boolean | undefined {
518
+ switch (condition.kind) {
519
+ case 'all': {
520
+ let result: boolean | undefined = true
521
+ for (let index = 0; index < condition.terms.length; index++) {
522
+ const term = condition.terms[index]
523
+ const value = term === undefined ? undefined : truth(term, row, now)
524
+ if (value === false) return false
525
+ if (value === undefined) result = undefined
526
+ }
527
+ return result
528
+ }
529
+ case 'any': {
530
+ let result: boolean | undefined = false
531
+ for (let index = 0; index < condition.terms.length; index++) {
532
+ const term = condition.terms[index]
533
+ const value = term === undefined ? undefined : truth(term, row, now)
534
+ if (value === true) return true
535
+ if (value === undefined) result = undefined
536
+ }
537
+ return result
538
+ }
539
+ case 'not': {
540
+ const value = truth(condition.term, row, now)
541
+ return value === undefined ? undefined : !value
542
+ }
543
+ case 'some':
544
+ return undefined
545
+ case 'test': {
546
+ if (condition.hops.length > 0) return undefined
547
+ const cell = row.has(condition.column) ? row.get(condition.column) : null
548
+ return testTruth(condition, cell ?? null, now)
549
+ }
550
+ }
551
+ }
552
+
553
+ function testTruth(test: Extract<ConditionModel, { kind: 'test' }>, cell: Primitive | null, now: Date): boolean | undefined {
554
+ if (test.operator === 'isNull') {
555
+ return (cell === null) === test.value
556
+ }
557
+ if (cell === null) {
558
+ return undefined
559
+ }
560
+ const value = test.value
561
+ if (test.operator === 'in' || test.operator === 'notIn') {
562
+ let found = false
563
+ if (isArray(value)) {
564
+ for (let index = 0; index < value.length; index++) {
565
+ if (same(cell, value[index])) found = true
566
+ }
567
+ }
568
+ return test.operator === 'in' ? found : !found
569
+ }
570
+ const right: Primitive = value === NOW ? now : scalar(value)
571
+ const order = compare(cell, right)
572
+ if (order === undefined) return undefined
573
+ switch (test.operator) {
574
+ case 'eq':
575
+ return order === 0
576
+ case 'notEq':
577
+ return order !== 0
578
+ case 'lt':
579
+ return order < 0
580
+ case 'lte':
581
+ return order <= 0
582
+ case 'gt':
583
+ return order > 0
584
+ case 'gte':
585
+ return order >= 0
586
+ }
587
+ }
588
+
589
+ function same(left: Primitive, right: ConditionLiteral | undefined): boolean {
590
+ return right !== undefined && compare(left, right) === 0
591
+ }
592
+
593
+ /** Orders two values the way both dialects compare a column with a bound value of its type; `undefined` across types. */
594
+ function compare(left: Primitive, right: Primitive): number | undefined {
595
+ const a = left instanceof Date ? left.getTime() : left
596
+ const b = right instanceof Date ? right.getTime() : typeof right === 'string' && left instanceof Date ? Date.parse(right) : right
597
+ if (typeof a === 'boolean' || typeof b === 'boolean') {
598
+ return typeof a === typeof b ? (a === b ? 0 : a ? 1 : -1) : undefined
599
+ }
600
+ if (typeof a === 'string' && typeof b === 'string') {
601
+ return a < b ? -1 : a > b ? 1 : 0
602
+ }
603
+ if ((typeof a === 'number' || typeof a === 'bigint') && (typeof b === 'number' || typeof b === 'bigint')) {
604
+ return a < b ? -1 : a > b ? 1 : 0
605
+ }
606
+ return undefined
607
+ }
608
+
609
+ export function hasOwnCondition(record: Readonly<Record<string, ConditionModel>>, action: string): boolean {
610
+ return hasOwn(record, action)
611
+ }
612
+
613
+ /** A condition as the artifact records it: the policy's own form, a path written back as `fk_column.column`. */
614
+ export function conditionArtifact(condition: ConditionModel): ConditionArtifact {
615
+ switch (condition.kind) {
616
+ case 'all':
617
+ return { allOf: artifactsOf(condition.terms) }
618
+ case 'any':
619
+ return { anyOf: artifactsOf(condition.terms) }
620
+ case 'not':
621
+ return { not: conditionArtifact(condition.term) }
622
+ case 'some': {
623
+ const rows: Record<string, ConditionArtifact> = {}
624
+ rows[condition.table] = conditionArtifact(condition.term)
625
+ const named: RowsTestArtifact = condition.negated ? { none: rows } : { some: rows }
626
+ if (condition.hops.length === 0) return named
627
+ const test: Record<string, RowsTestArtifact> = {}
628
+ test[pathText(condition.hops).slice(0, -1)] = named
629
+ return test
630
+ }
631
+ case 'test': {
632
+ const test: Record<string, ColumnTestArtifact> = {}
633
+ test[pathText(condition.hops) + condition.column] = testArtifact(condition)
634
+ return test
635
+ }
636
+ }
637
+ }
638
+
639
+ /** Each hop's column followed by a dot: the prefix of a path's text. */
640
+ function pathText(hops: readonly ConditionHop[]): string {
641
+ let path = ''
642
+ for (let index = 0; index < hops.length; index++) {
643
+ path += `${hops[index]?.column ?? ''}.`
644
+ }
645
+ return path
646
+ }
647
+
648
+ function artifactsOf(terms: readonly ConditionModel[]): ConditionArtifact[] {
649
+ const artifacts: ConditionArtifact[] = []
650
+ for (let index = 0; index < terms.length; index++) {
651
+ const term = terms[index]
652
+ if (term !== undefined) artifacts[artifacts.length] = conditionArtifact(term)
653
+ }
654
+ return artifacts
655
+ }
656
+
657
+ function testArtifact(test: Extract<ConditionModel, { kind: 'test' }>): ColumnTestArtifact {
658
+ const value = test.value
659
+ switch (test.operator) {
660
+ case 'isNull':
661
+ return { isNull: value === true }
662
+ case 'in':
663
+ case 'notIn': {
664
+ const list: ConditionLiteral[] = []
665
+ if (isArray(value)) {
666
+ for (let index = 0; index < value.length; index++) list[list.length] = value[index] ?? ''
667
+ }
668
+ return test.operator === 'in' ? { in: list } : { notIn: list }
669
+ }
670
+ case 'eq':
671
+ return { eq: scalar(value) }
672
+ case 'notEq':
673
+ return { notEq: scalar(value) }
674
+ case 'lt':
675
+ return { lt: value === NOW ? { now: true } : scalar(value) }
676
+ case 'lte':
677
+ return { lte: value === NOW ? { now: true } : scalar(value) }
678
+ case 'gt':
679
+ return { gt: value === NOW ? { now: true } : scalar(value) }
680
+ case 'gte':
681
+ return { gte: value === NOW ? { now: true } : scalar(value) }
682
+ }
683
+ }
@@ -1,3 +1,4 @@
1
+ import type { OperationNode } from 'kysely'
1
2
  import { inSet, isSafeInteger, type NameSet, nameSet, namesOf, ownEntry, ownKeys, parseList } from './builtins'
2
3
  import { QueryRefusedError } from './errors'
3
4
  import { isPlainIdentifier } from './identifier'
@@ -74,6 +75,8 @@ export interface JoinShape {
74
75
  export interface JoinState {
75
76
  readonly join: JoinShape
76
77
  readonly select: SelectState
78
+ /** The child's condition for the action the select holds, which the layer adds to the ON; never the builder's. */
79
+ readonly condition?: OperationNode
77
80
  }
78
81
 
79
82
  export interface SelectState {