@fabrika/db 0.9.0-dev.4 → 0.9.0-dev.40

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.
Files changed (84) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +10 -6
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +228 -55
  20. package/src/job-wakes.ts +600 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/list-cursor.ts +82 -0
  24. package/src/migrations-sqlite.ts +210 -0
  25. package/src/migrations.ts +73 -0
  26. package/src/nodes.ts +84 -14
  27. package/src/orm-types.ts +206 -71
  28. package/src/orm.ts +425 -170
  29. package/src/policy.ts +1979 -141
  30. package/src/postgres.ts +26 -0
  31. package/src/registry.ts +55 -3
  32. package/src/request-receipts.ts +107 -0
  33. package/src/sql.ts +247 -476
  34. package/src/sqlite-bun.ts +149 -0
  35. package/src/sqlite-migrate.ts +242 -0
  36. package/src/sqlite.ts +269 -0
  37. package/src/store.ts +2292 -239
  38. package/src/stored-files.ts +188 -52
  39. package/src/tables.ts +172 -6
  40. package/src/temporal.ts +122 -9
  41. package/src/testing-shared.ts +1351 -0
  42. package/src/testing-sqlite.ts +685 -0
  43. package/src/testing.ts +310 -494
  44. package/src/vocabulary-tables.ts +159 -27
  45. package/types/src/application-rows.d.ts +58 -0
  46. package/types/src/authority.d.ts +147 -0
  47. package/types/src/builtins.d.ts +2 -0
  48. package/types/src/capability.d.ts +55 -2
  49. package/types/src/codegen-sqlite.d.ts +13 -0
  50. package/types/src/codegen.d.ts +79 -5
  51. package/types/src/condition-nodes.d.ts +9 -0
  52. package/types/src/conditions.d.ts +151 -0
  53. package/types/src/database.d.ts +81 -20
  54. package/types/src/description.d.ts +26 -8
  55. package/types/src/errors.d.ts +9 -6
  56. package/types/src/file-columns.d.ts +6 -4
  57. package/types/src/framework.d.ts +12 -5
  58. package/types/src/guard.d.ts +24 -0
  59. package/types/src/index.d.ts +5 -4
  60. package/types/src/job-leases.d.ts +40 -5
  61. package/types/src/job-wakes.d.ts +124 -0
  62. package/types/src/json.d.ts +18 -0
  63. package/types/src/list-cursor.d.ts +13 -0
  64. package/types/src/migrations-sqlite.d.ts +4 -0
  65. package/types/src/migrations.d.ts +4 -0
  66. package/types/src/nodes.d.ts +17 -2
  67. package/types/src/orm-types.d.ts +163 -71
  68. package/types/src/orm.d.ts +21 -0
  69. package/types/src/policy.d.ts +351 -23
  70. package/types/src/postgres.d.ts +12 -0
  71. package/types/src/registry.d.ts +40 -3
  72. package/types/src/request-receipts.d.ts +22 -0
  73. package/types/src/sql.d.ts +29 -21
  74. package/types/src/sqlite-bun.d.ts +21 -0
  75. package/types/src/sqlite-migrate.d.ts +28 -0
  76. package/types/src/sqlite.d.ts +24 -0
  77. package/types/src/store.d.ts +143 -34
  78. package/types/src/stored-files.d.ts +6 -2
  79. package/types/src/tables.d.ts +18 -2
  80. package/types/src/temporal.d.ts +24 -0
  81. package/types/src/testing-shared.d.ts +290 -0
  82. package/types/src/testing-sqlite.d.ts +37 -0
  83. package/types/src/testing.d.ts +2 -93
  84. package/types/src/vocabulary-tables.d.ts +169 -22
package/src/guard.ts CHANGED
@@ -26,8 +26,48 @@ 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
39
+ }
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
+ /** The view's own access views, which list its rows beside the parent's reach (ADR-0076). */
47
+ readonly access?: readonly ViewAccessLink[]
29
48
  }
30
49
 
50
+ /** An access view of a child view: `V.<key> in (select A.<row> from A where <bindings>)`. */
51
+ export interface ViewAccessLink {
52
+ readonly key: string
53
+ readonly view: string
54
+ readonly row: string
55
+ }
56
+
57
+ /** A subquery of the scope predicate the shape check admitted, and the one table it reads. */
58
+ interface Admitted {
59
+ readonly node: unknown
60
+ readonly table: string
61
+ }
62
+
63
+ /**
64
+ * How deep subqueries of a scope nest, the deepest the layer builds: a reveal's row (1) under a condition path of three
65
+ * hops, and a reveal matched through a secondary path above the relation's dimension (the reveal's row, the path's
66
+ * table, the source, and the table a principal path reads). A child view's parent subquery stands once above them, at
67
+ * the top of its scope, and counts apart, so a view's scope nests at most one deeper.
68
+ */
69
+ const MAX_SCOPE_NESTING = 4
70
+
31
71
  function lookup(...names: string[]): NameSet {
32
72
  return nameSet(names)
33
73
  }
@@ -81,6 +121,8 @@ const NODE_KINDS = lookup(
81
121
  // Only as a selected own column's text, the exact position a keyset page continues from; checked below.
82
122
  'CastNode',
83
123
  'DataTypeNode',
124
+ // Only as `not` of a scope predicate's branch, which the shape check admitted.
125
+ 'UnaryOperationNode',
84
126
  )
85
127
 
86
128
  const COMPARISON_OPERATORS = lookup('=', '<>', '<', '<=', '>', '>=', 'like', 'ilike', 'not like', 'not ilike', 'in', 'not in', 'is', 'is not')
@@ -108,11 +150,12 @@ export function assertAllowedTree(root: OperationNode, context: GuardContext): v
108
150
  throw new QueryRefusedError('statement_shape', `${context.root}.${key} is not allowed`)
109
151
  }
110
152
  }
111
- checkRoot(root, context)
112
- walk(root, undefined, context)
153
+ const admitted: Admitted[] = []
154
+ checkRoot(root, context, admitted)
155
+ walk(root, undefined, context, admitted, undefined)
113
156
  }
114
157
 
115
- function checkRoot(root: OperationNode, context: GuardContext): void {
158
+ function checkRoot(root: OperationNode, context: GuardContext, admitted: Admitted[]): void {
116
159
  const target = context.root === 'InsertQueryNode'
117
160
  ? read(root, 'into')
118
161
  : context.root === 'UpdateQueryNode'
@@ -134,20 +177,296 @@ function checkRoot(root: OperationNode, context: GuardContext): void {
134
177
  if (!scoped) {
135
178
  throw new QueryRefusedError('scope_predicate', 'the scope predicate must be the top-level conjunct of WHERE')
136
179
  }
180
+ const through = context.through
181
+ // A child view's rows are placed by its parent row only: no column of the view stands in for that reach.
182
+ const reach = (node: unknown) =>
183
+ through === undefined
184
+ ? isReach(node, context.table, context.subqueries, admitted)
185
+ : isEverything(node) || isThroughParent(node, context.table, through, context.subqueries, admitted)
137
186
  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))
187
+ const shaped = reach(scope)
188
+ || (kindOf(scope) === 'AndNode' && hasOnly(scope, CONNECTIVE_KEYS) && reach(read(scope, 'left'))
189
+ && kindOf(read(scope, 'right')) === 'ParensNode'
190
+ && isScopeTree(read(scope, 'right'), context.table, context.subqueries, admitted, 0))
143
191
  if (!shaped) {
144
192
  throw new QueryRefusedError(
145
193
  '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',
194
+ '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
195
  )
148
196
  }
149
197
  }
150
198
 
199
+ /**
200
+ * What a capability reaches before its action's condition narrows it: everything (a global grant), a Ref's chain of
201
+ * equalities, and after them a union of its relation rows and its secondary paths' memberships of bound values, or a
202
+ * Within's memberships of values and relation rows. A relation's rows may be narrowed: `(<relation rows> and (<scope
203
+ * tree>))`, the condition's subqueries beside the relation's, never nested in it.
204
+ */
205
+ function isReach(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth = 0): boolean {
206
+ const equality = (leaf: unknown) => isScopeEquality(leaf, table)
207
+ const related = (leaf: unknown) =>
208
+ isRelationMembership(leaf, table, subqueries, admitted, depth)
209
+ || isNarrowed(leaf, table, subqueries, admitted, depth, (left) => isRelationMembership(left, table, subqueries, admitted, depth))
210
+ const member = (leaf: unknown) => isScopeMembership(leaf, table) || related(leaf)
211
+ return isEverything(node)
212
+ || isTreeOf(node, 'AndNode', equality)
213
+ || isUnionOf(node, member)
214
+ || (kindOf(node) === 'AndNode' && isTreeOf(read(node, 'left'), 'AndNode', equality) && isUnionOf(read(node, 'right'), member))
215
+ }
216
+
217
+ /**
218
+ * A child view's rows read through its parent: `V.<column> in (select P.<key> from P where <P's reach>)`, after an AND
219
+ * of equalities when one row is addressed. P's reach is one the guard admits for a statement on P, never `true`; a
220
+ * subquery without WHERE reads every parent row. Where the view narrows a relation (`relationWhen`), that relation's
221
+ * reach is a membership of its own, narrowed by the view's condition, in a parenthesized OR of such memberships.
222
+ */
223
+ function isThroughParent(
224
+ node: unknown,
225
+ table: string,
226
+ parent: ViewParentLink,
227
+ subqueries: GuardContext['subqueries'],
228
+ admitted: Admitted[],
229
+ ): boolean {
230
+ const membership = (leaf: unknown) =>
231
+ isParentMembership(leaf, table, parent, subqueries, admitted) || isViewAccess(leaf, table, parent.access ?? [], subqueries, admitted)
232
+ const member = (leaf: unknown) => isUnionOf(leaf, (branch) => membership(branch) || isNarrowed(branch, table, subqueries, admitted, 0, membership))
233
+ return member(node)
234
+ || (kindOf(node) === 'AndNode' && hasOnly(node, CONNECTIVE_KEYS) && isTreeOf(read(node, 'left'), 'AndNode', (leaf) => isScopeEquality(leaf, table))
235
+ && member(read(node, 'right')))
236
+ }
237
+
238
+ /**
239
+ * `V.<key> in (select A.<row> from A where <bindings>)` for one access view the view declares: the only test of a view's
240
+ * own column that places its rows, because the access view's SQL is the reviewed rule that decides them.
241
+ */
242
+ function isViewAccess(
243
+ node: unknown,
244
+ table: string,
245
+ links: readonly ViewAccessLink[],
246
+ subqueries: GuardContext['subqueries'],
247
+ admitted: Admitted[],
248
+ ): boolean {
249
+ if (kindOf(node) !== 'BinaryOperationNode' || !hasOnly(node, BINARY_KEYS) || read(read(node, 'operator'), 'operator') !== 'in') {
250
+ return false
251
+ }
252
+ const select = read(node, 'rightOperand')
253
+ const froms = read(read(select, 'from'), 'froms')
254
+ const selections = read(select, 'selections')
255
+ if (!isArray(froms) || froms.length !== 1 || !isArray(selections) || selections.length !== 1) {
256
+ return false
257
+ }
258
+ for (let index = 0; index < links.length; index++) {
259
+ const link = links[index]
260
+ if (
261
+ link !== undefined && isReference(read(node, 'leftOperand'), table, link.key) && tableName(froms[0]) === link.view
262
+ && isReference(read(selections[0], 'selection'), link.view, link.row)
263
+ ) {
264
+ return isScopeSubquery(select, subqueries, admitted, 1, true)
265
+ }
266
+ }
267
+ return false
268
+ }
269
+
270
+ function isParentMembership(
271
+ node: unknown,
272
+ table: string,
273
+ parent: ViewParentLink,
274
+ subqueries: GuardContext['subqueries'],
275
+ admitted: Admitted[],
276
+ ): boolean {
277
+ if (
278
+ kindOf(node) !== 'BinaryOperationNode' || !hasOnly(node, BINARY_KEYS) || read(read(node, 'operator'), 'operator') !== 'in'
279
+ || !isReference(read(node, 'leftOperand'), table, parent.column)
280
+ ) {
281
+ return false
282
+ }
283
+ const select = read(node, 'rightOperand')
284
+ const from = read(select, 'from')
285
+ const froms = read(from, 'froms')
286
+ const selections = read(select, 'selections')
287
+ const where = read(select, 'where')
288
+ if (
289
+ kindOf(select) !== 'SelectQueryNode' || !hasOnly(select, SUBQUERY_KEYS) || !hasOnly(from, FROM_KEYS) || !isArray(froms) || froms.length !== 1
290
+ || tableName(froms[0]) !== parent.table || !isArray(selections) || selections.length !== 1 || !hasOnly(selections[0], SELECTION_KEYS)
291
+ || !isReference(read(selections[0], 'selection'), parent.table, parent.key) || (where !== undefined && !hasOnly(where, WHERE_KEYS))
292
+ ) {
293
+ return false
294
+ }
295
+ // No WHERE: every parent row, a `Within` of `all`; strictly narrower than the `true` a view's statement admits.
296
+ if (where === undefined) {
297
+ admitted[admitted.length] = { node: select, table: parent.table }
298
+ return true
299
+ }
300
+ const reach = read(where, 'where')
301
+ // The parent's reach nests as deep as on a statement of the parent's own: the parent's subquery counts apart.
302
+ if (isEverything(reach) || !isReach(reach, parent.table, subqueries, admitted, 0)) {
303
+ return false
304
+ }
305
+ admitted[admitted.length] = { node: select, table: parent.table }
306
+ return true
307
+ }
308
+
309
+ /** `(<left> and (<scope tree over table>))`: one branch of a reach, `left`, narrowed by a condition on the table's rows. */
310
+ function isNarrowed(
311
+ node: unknown,
312
+ table: string,
313
+ subqueries: GuardContext['subqueries'],
314
+ admitted: Admitted[],
315
+ depth: number,
316
+ left: (node: unknown) => boolean,
317
+ ): boolean {
318
+ const inner = read(node, 'node')
319
+ const right = read(inner, 'right')
320
+ return kindOf(node) === 'ParensNode' && hasOnly(node, PARENS_KEYS) && kindOf(inner) === 'AndNode' && hasOnly(inner, CONNECTIVE_KEYS)
321
+ && left(read(inner, 'left')) && kindOf(right) === 'ParensNode' && isScopeTree(right, table, subqueries, admitted, depth)
322
+ }
323
+
324
+ /** One leaf, or a parenthesized OR tree of them. */
325
+ function isUnionOf(node: unknown, leaf: (node: unknown) => boolean): boolean {
326
+ return leaf(node) || (kindOf(node) === 'ParensNode' && kindOf(read(node, 'node')) === 'OrNode' && isTreeOf(read(node, 'node'), 'OrNode', leaf))
327
+ }
328
+
329
+ /** `table.<node> in (select S.<node> from S where S.<principal> = $me and …)`: the rows a relation reaches. */
330
+ function isRelationMembership(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth = 0): boolean {
331
+ return kindOf(node) === 'BinaryOperationNode' && hasOnly(node, BINARY_KEYS) && read(read(node, 'operator'), 'operator') === 'in'
332
+ && isOwnColumn(read(node, 'leftOperand'), table)
333
+ && isScopeSubquery(read(node, 'rightOperand'), subqueries, admitted, depth + 1, true)
334
+ }
335
+
336
+ /**
337
+ * A scope with relations or conditions: AND, OR, parentheses and `not` over tests of the table's own columns against a
338
+ * bound value, a bound list, null, or a subquery that reads one admitted table, selects one admitted column of it and
339
+ * is scoped the same way over that table. Never `true` inside: that would make a branch vacuous.
340
+ */
341
+ function isScopeTree(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
342
+ switch (kindOf(node)) {
343
+ case 'AndNode':
344
+ case 'OrNode':
345
+ return hasOnly(node, CONNECTIVE_KEYS) && isScopeTree(read(node, 'left'), table, subqueries, admitted, depth)
346
+ && isScopeTree(read(node, 'right'), table, subqueries, admitted, depth)
347
+ case 'ParensNode':
348
+ return hasOnly(node, PARENS_KEYS) && isScopeTree(read(node, 'node'), table, subqueries, admitted, depth)
349
+ case 'UnaryOperationNode':
350
+ return hasOnly(node, UNARY_KEYS) && read(read(node, 'operator'), 'operator') === 'not'
351
+ && isScopeTree(read(node, 'operand'), table, subqueries, admitted, depth)
352
+ case 'BinaryOperationNode':
353
+ return isScopeTest(node, table, subqueries, admitted, depth)
354
+ default:
355
+ return false
356
+ }
357
+ }
358
+
359
+ function isScopeTest(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
360
+ const operator = read(read(node, 'operator'), 'operator')
361
+ if (!hasOnly(node, BINARY_KEYS) || !isOwnColumn(read(node, 'leftOperand'), table) || !inSet(SCOPE_OPERATORS, operator)) {
362
+ return false
363
+ }
364
+ const right = read(node, 'rightOperand')
365
+ if (operator === 'is' || operator === 'is not') {
366
+ return kindOf(right) === 'ValueNode' && read(right, 'immediate') === true && read(right, 'value') === null
367
+ }
368
+ if (operator === 'in' || operator === 'not in') {
369
+ if (kindOf(right) === 'ValueListNode') {
370
+ return isBoundList(right)
371
+ }
372
+ return operator === 'in' && isScopeSubquery(right, subqueries, admitted, depth + 1, false)
373
+ }
374
+ return isBoundValue(right)
375
+ }
376
+
377
+ function isBoundList(list: unknown): boolean {
378
+ const values = read(list, 'values')
379
+ if (!isArray(values) || values.length === 0) {
380
+ return false
381
+ }
382
+ for (let index = 0; index < values.length; index++) {
383
+ if (!isBoundValue(values[index])) {
384
+ return false
385
+ }
386
+ }
387
+ return true
388
+ }
389
+
390
+ /**
391
+ * `(select S.<column> from S where <scope tree over S>)`, S and its column admitted, nothing else on the node. A relation's
392
+ * subquery is `anchored`: its WHERE starts with an equality to a bound value, the principal, so it never reads every row.
393
+ */
394
+ function isScopeSubquery(node: unknown, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number, anchored: boolean): boolean {
395
+ if (subqueries === undefined || depth > MAX_SCOPE_NESTING || kindOf(node) !== 'SelectQueryNode' || !hasOnly(node, SUBQUERY_KEYS)) {
396
+ return false
397
+ }
398
+ const from = read(node, 'from')
399
+ const froms = read(from, 'froms')
400
+ if (!hasOnly(from, FROM_KEYS) || !isArray(froms) || froms.length !== 1) {
401
+ return false
402
+ }
403
+ const table = tableName(froms[0])
404
+ if (table === undefined || !hasOwn(subqueries, table)) {
405
+ return false
406
+ }
407
+ const columns = subqueries[table] ?? []
408
+ const selections = read(node, 'selections')
409
+ if (!isArray(selections) || selections.length !== 1 || !hasOnly(selections[0], SELECTION_KEYS)) {
410
+ return false
411
+ }
412
+ const selected = read(selections[0], 'selection')
413
+ const name = read(read(read(selected, 'column'), 'column'), 'name')
414
+ let known = false
415
+ for (let index = 0; index < columns.length; index++) {
416
+ if (columns[index] === name) {
417
+ known = true
418
+ }
419
+ }
420
+ const where = read(node, 'where')
421
+ if (!known || !isOwnColumn(selected, table) || !hasOnly(where, WHERE_KEYS)) {
422
+ return false
423
+ }
424
+ const condition = read(where, 'where')
425
+ if (anchored ? !isAnchored(condition, table, subqueries, admitted, depth) : !isScopeTree(condition, table, subqueries, admitted, depth)) {
426
+ return false
427
+ }
428
+ admitted[admitted.length] = { node, table }
429
+ return true
430
+ }
431
+
432
+ /**
433
+ * `S.<column> = $n`, `S.<column> in ($1, …)` (a secondary path's container: the nodes inside bound containers), or a
434
+ * relation's membership over `S` (a reveal: `R.<key> in (<anchored subquery>)`), then any scope tree AND-ed after it.
435
+ * Each way the innermost subquery starts with a test against bound values, so it never reads every row.
436
+ */
437
+ function isAnchored(node: unknown, table: string, subqueries: GuardContext['subqueries'], admitted: Admitted[], depth: number): boolean {
438
+ if (kindOf(node) === 'AndNode') {
439
+ return hasOnly(node, CONNECTIVE_KEYS) && isAnchored(read(node, 'left'), table, subqueries, admitted, depth)
440
+ && isScopeTree(read(node, 'right'), table, subqueries, admitted, depth)
441
+ }
442
+ return isScopeEquality(node, table) || isScopeMembership(node, table) || isRelationMembership(node, table, subqueries, admitted, depth)
443
+ }
444
+
445
+ /** True when every own property of `node` is one of `keys`: a scope node carries nothing the shape check did not read. */
446
+ function hasOnly(node: unknown, keys: NameSet): boolean {
447
+ if (typeof node !== 'object' || node === null) {
448
+ return false
449
+ }
450
+ const own = ownKeys(node)
451
+ for (let index = 0; index < own.length; index++) {
452
+ const key = own[index] ?? ''
453
+ if (!inSet(keys, key) && read(node, key) !== undefined) {
454
+ return false
455
+ }
456
+ }
457
+ return true
458
+ }
459
+
460
+ const CONNECTIVE_KEYS = lookup('kind', 'left', 'right')
461
+ const PARENS_KEYS = lookup('kind', 'node')
462
+ const UNARY_KEYS = lookup('kind', 'operator', 'operand')
463
+ const BINARY_KEYS = lookup('kind', 'leftOperand', 'operator', 'rightOperand')
464
+ const SUBQUERY_KEYS = lookup('kind', 'from', 'selections', 'where')
465
+ const FROM_KEYS = lookup('kind', 'froms')
466
+ const SELECTION_KEYS = lookup('kind', 'selection')
467
+ const WHERE_KEYS = lookup('kind', 'where')
468
+ const SCOPE_OPERATORS = lookup('=', '<>', '<', '<=', '>', '>=', 'in', 'not in', 'is', 'is not')
469
+
151
470
  /** A Within that is not limited to scope values. */
152
471
  function isEverything(node: unknown): boolean {
153
472
  return kindOf(node) === 'ValueNode' && read(node, 'immediate') === true && read(node, 'value') === true
@@ -205,8 +524,18 @@ function soleFrom(from: unknown): unknown {
205
524
  return froms[0]
206
525
  }
207
526
 
208
- function walk(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
209
- checkNode(node, parent, context)
527
+ function walk(
528
+ node: OperationNode,
529
+ parent: Visit | undefined,
530
+ context: GuardContext,
531
+ admitted: readonly Admitted[],
532
+ inside: string | undefined,
533
+ ): void {
534
+ const subquery = parent === undefined ? undefined : admittedTable(node, admitted)
535
+ const reading = subquery ?? inside
536
+ if (subquery === undefined) {
537
+ checkNode(node, parent, context, reading)
538
+ }
210
539
  if (node.kind === 'ValueNode') {
211
540
  return
212
541
  }
@@ -218,7 +547,7 @@ function walk(node: OperationNode, parent: Visit | undefined, context: GuardCont
218
547
  for (let position = 0; position < children.length; position++) {
219
548
  const child = children[position]
220
549
  if (isOperationNode(child)) {
221
- walk(child, { node, key, up: parent }, context)
550
+ walk(child, { node, key, up: parent }, context, admitted, reading)
222
551
  } else if (typeof child === 'object' && child !== null) {
223
552
  throw new QueryRefusedError('statement_shape', `unexpected structure under ${node.kind}.${key}`)
224
553
  }
@@ -226,7 +555,18 @@ function walk(node: OperationNode, parent: Visit | undefined, context: GuardCont
226
555
  }
227
556
  }
228
557
 
229
- function checkNode(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
558
+ /** The table an admitted subquery reads, when `node` is one, by identity. */
559
+ function admittedTable(node: unknown, admitted: readonly Admitted[]): string | undefined {
560
+ for (let index = 0; index < admitted.length; index++) {
561
+ const entry = admitted[index]
562
+ if (entry !== undefined && entry.node === node) {
563
+ return entry.table
564
+ }
565
+ }
566
+ return undefined
567
+ }
568
+
569
+ function checkNode(node: OperationNode, parent: Visit | undefined, context: GuardContext, inside: string | undefined): void {
230
570
  if (inSet(ROOT_KINDS, node.kind)) {
231
571
  if (parent !== undefined) {
232
572
  throw new QueryRefusedError('statement_shape', 'subqueries are not allowed')
@@ -261,7 +601,15 @@ function checkNode(node: OperationNode, parent: Visit | undefined, context: Guar
261
601
  }
262
602
  return
263
603
  case 'TableNode':
264
- return checkTable(node, parent, context)
604
+ return checkTable(node, parent, context, inside)
605
+ case 'OrderByItemNode': {
606
+ // Kysely prints `nulls` as raw text; the layer only ever states the order Postgres has by default.
607
+ const nulls = read(node, 'nulls')
608
+ if (nulls !== undefined && nulls !== 'first' && nulls !== 'last') {
609
+ throw new QueryRefusedError('statement_shape', 'an order term states nulls first or nulls last, nothing else')
610
+ }
611
+ return
612
+ }
265
613
  case 'JoinNode':
266
614
  return checkJoin(node, context)
267
615
  case 'ReferenceNode':
@@ -305,6 +653,9 @@ function checkOperator(node: OperationNode, parent: Visit | undefined): void {
305
653
  if (inSet(COMPARISON_OPERATORS, operator)) {
306
654
  return
307
655
  }
656
+ if (operator === 'not' && parent?.node.kind === 'UnaryOperationNode') {
657
+ return
658
+ }
308
659
  // The version bump `version = version + 1` is the one arithmetic the layer writes, as a SET value.
309
660
  if (operator === '+' && parent?.up?.node.kind === 'ColumnUpdateNode') {
310
661
  return
@@ -385,8 +736,15 @@ function checkRaw(node: OperationNode, parent: Visit | undefined): void {
385
736
  }
386
737
  }
387
738
 
388
- function checkTable(node: OperationNode, parent: Visit | undefined, context: GuardContext): void {
739
+ function checkTable(node: OperationNode, parent: Visit | undefined, context: GuardContext, inside: string | undefined): void {
389
740
  const name = tableName(node)
741
+ // Inside an admitted subquery its own table is the one it reads, and the outer statement's is not reachable.
742
+ if (inside !== undefined) {
743
+ if (name === inside) {
744
+ return
745
+ }
746
+ throw new QueryRefusedError('statement_shape', `a scope subquery of ${inside} reads ${String(name)}`)
747
+ }
390
748
  if (name === context.table) {
391
749
  return
392
750
  }
package/src/index.ts CHANGED
@@ -7,13 +7,22 @@ export type {
7
7
  LeaseFence,
8
8
  Ref,
9
9
  RefGrant,
10
+ RelationHold,
10
11
  RowGrant,
11
12
  RowRef,
12
13
  Within,
13
14
  WithinGrant,
14
15
  } from './capability'
15
16
  export { MAX_WITHIN_VALUES } from './capability'
16
- export { applicationSchema, Database, type PostgresOptions } from './database'
17
+ export {
18
+ applicationSchema,
19
+ Database,
20
+ type DatabaseEngine,
21
+ type Executor,
22
+ type SqlDialect,
23
+ type TransactionOptions,
24
+ type TransactionRunner,
25
+ } from './database'
17
26
  export type {
18
27
  AllowedOperator,
19
28
  ComparisonOperator,
@@ -37,16 +46,21 @@ export {
37
46
  type QueryRefusal,
38
47
  QueryRefusedError,
39
48
  } from './errors'
49
+ export type { JsonColumnValue, JsonValue } from './json'
40
50
  export type {
51
+ AllOptions,
52
+ AllQuery,
41
53
  AnyDbIndex,
42
54
  ChildRows,
43
55
  ContainedRows,
44
56
  CountOptions,
57
+ CountQuery,
45
58
  DataKind,
46
59
  DbIndex,
47
60
  IndexedTable,
48
61
  ListOptions,
49
62
  ListPage,
63
+ ListQuery,
50
64
  NoUnscoped,
51
65
  OrderTerm,
52
66
  OwnerRow,
@@ -103,6 +117,7 @@ export {
103
117
  export { type TablePolicies, tablePolicies } from './tables'
104
118
  export type {
105
119
  ColumnTypes,
120
+ ColumnViews,
106
121
  DefineVocabularyPolicies,
107
122
  NormalizedPolicies,
108
123
  TableVocabulary,
@@ -115,4 +130,5 @@ export type {
115
130
  VocabularyDimensionScope,
116
131
  VocabularyPolicyMap,
117
132
  VocabularyTablePolicy,
133
+ VocabularyViewPolicy,
118
134
  } from './vocabulary-tables'