@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/package.json +5 -5
- package/src/authority.ts +254 -0
- package/src/builtins.ts +21 -0
- package/src/capability.ts +15 -0
- package/src/codegen-sqlite.ts +8 -5
- package/src/codegen.ts +75 -28
- package/src/condition-nodes.ts +119 -0
- package/src/conditions.ts +683 -0
- package/src/description.ts +3 -0
- package/src/framework.ts +1 -1
- package/src/guard.ts +302 -15
- package/src/index.ts +2 -0
- package/src/nodes.ts +9 -6
- package/src/orm-types.ts +31 -12
- package/src/orm.ts +85 -33
- package/src/policy.ts +1247 -40
- package/src/registry.ts +11 -0
- package/src/sql.ts +22 -3
- package/src/store.ts +744 -55
- package/src/tables.ts +104 -2
- package/src/testing-shared.ts +3 -0
- package/src/vocabulary-tables.ts +110 -17
- package/types/src/authority.d.ts +66 -0
- package/types/src/builtins.d.ts +2 -0
- package/types/src/capability.d.ts +15 -0
- package/types/src/codegen.d.ts +24 -11
- package/types/src/condition-nodes.d.ts +9 -0
- package/types/src/conditions.d.ts +151 -0
- package/types/src/description.d.ts +3 -0
- package/types/src/framework.d.ts +1 -1
- package/types/src/guard.d.ts +16 -0
- package/types/src/index.d.ts +1 -1
- package/types/src/nodes.d.ts +2 -0
- package/types/src/orm-types.d.ts +31 -11
- package/types/src/orm.d.ts +5 -0
- package/types/src/policy.d.ts +197 -2
- package/types/src/registry.d.ts +9 -0
- package/types/src/sql.d.ts +2 -2
- package/types/src/store.d.ts +45 -7
- package/types/src/tables.d.ts +7 -1
- package/types/src/vocabulary-tables.d.ts +117 -16
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@fabrika/db",
|
|
3
|
-
"version": "0.9.0-dev.
|
|
3
|
+
"version": "0.9.0-dev.13",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -88,13 +88,13 @@
|
|
|
88
88
|
}
|
|
89
89
|
},
|
|
90
90
|
"scripts": {
|
|
91
|
-
"typecheck": "
|
|
91
|
+
"typecheck": "tsrs --build tsconfig.test.json",
|
|
92
92
|
"test": "bun test"
|
|
93
93
|
},
|
|
94
94
|
"dependencies": {
|
|
95
|
-
"@fabrika/auth-core": "0.9.0-dev.
|
|
96
|
-
"@fabrika/platform": "0.9.0-dev.
|
|
97
|
-
"@fabrika/platform-node": "0.9.0-dev.
|
|
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"
|
package/src/authority.ts
ADDED
|
@@ -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-sqlite.ts
CHANGED
|
@@ -13,7 +13,7 @@ import {
|
|
|
13
13
|
JSON_COLUMN,
|
|
14
14
|
type LeftOut,
|
|
15
15
|
leftOutRefusal,
|
|
16
|
-
type
|
|
16
|
+
type RelationColumn,
|
|
17
17
|
renderTables,
|
|
18
18
|
type ScalarType,
|
|
19
19
|
} from './codegen'
|
|
@@ -46,7 +46,7 @@ const DECLARED_TYPES: ReadonlyMap<string, { readonly scalar: ScalarType; readonl
|
|
|
46
46
|
['JSONB', { scalar: JSON_COLUMN, list: 'json' }],
|
|
47
47
|
])
|
|
48
48
|
|
|
49
|
-
interface SqliteColumn extends
|
|
49
|
+
interface SqliteColumn extends RelationColumn {
|
|
50
50
|
readonly declared: string
|
|
51
51
|
readonly nullable: boolean
|
|
52
52
|
/** `always` is a column `GENERATED ALWAYS AS (…)` computes (`hidden` 2 or 3): SQLite has no identity column. */
|
|
@@ -83,11 +83,13 @@ function bunTarget(db: Database): SqliteMigrationTarget {
|
|
|
83
83
|
function describeSqlite(column: SqliteColumn): DescribedColumn | LeftOut {
|
|
84
84
|
const base = column.declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
|
|
85
85
|
const mapped = DECLARED_TYPES.get(base)
|
|
86
|
+
// A view's column has the declared type of the table column it selects; an expression none, or its cast's affinity.
|
|
87
|
+
if (mapped === undefined && column.view) return { leftOut: column.declared.trim(), of: 'view' }
|
|
86
88
|
if (mapped === undefined) {
|
|
87
89
|
const computed = column.generated === 'always'
|
|
88
90
|
if (computed && column.keyed) throw leftOutRefusal(columnPath(column), 'it is in the primary key or a unique key')
|
|
89
91
|
// A generated column without a declared type is one its author may mean to read: it is refused, not left out.
|
|
90
|
-
if (computed && base !== '') return { leftOut: column.declared.trim() }
|
|
92
|
+
if (computed && base !== '') return { leftOut: column.declared.trim(), of: 'generated' }
|
|
91
93
|
if (base === 'JSON') {
|
|
92
94
|
throw new CodegenError(
|
|
93
95
|
`${
|
|
@@ -109,10 +111,10 @@ function primaryKeyOf(db: Database, table: string): string[] {
|
|
|
109
111
|
return columns.map((column) => column.name)
|
|
110
112
|
}
|
|
111
113
|
|
|
112
|
-
/** Every column of the application's ordinary tables, and
|
|
114
|
+
/** Every column of the application's ordinary tables and views, and the tables' foreign keys in declaration order. */
|
|
113
115
|
function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: ForeignKeyColumns[] } {
|
|
114
116
|
const tables = z.array(tableSchema).parse(
|
|
115
|
-
db.query(`SELECT name, type, wr FROM pragma_table_list WHERE schema = 'main' AND type IN ('table', 'virtual') ORDER BY name`).all(),
|
|
117
|
+
db.query(`SELECT name, type, wr FROM pragma_table_list WHERE schema = 'main' AND type IN ('table', 'view', 'virtual') ORDER BY name`).all(),
|
|
116
118
|
).filter((table) => !table.name.startsWith('sqlite_') && !table.name.startsWith('fabrika_'))
|
|
117
119
|
const columns: SqliteColumn[] = []
|
|
118
120
|
const foreignKeys: ForeignKeyColumns[] = []
|
|
@@ -132,6 +134,7 @@ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: Forei
|
|
|
132
134
|
columns.push({
|
|
133
135
|
table_name: table.name,
|
|
134
136
|
column_name: column.name,
|
|
137
|
+
view: table.type === 'view',
|
|
135
138
|
declared: column.type,
|
|
136
139
|
nullable: !rowid && column.notnull === 0,
|
|
137
140
|
generated: computed ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
|
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
|
|
|
@@ -56,6 +58,8 @@ export class CodegenError extends Error {
|
|
|
56
58
|
|
|
57
59
|
const catalogColumnSchema = z.object({
|
|
58
60
|
table_name: z.string(),
|
|
61
|
+
/** The relation is a view (`relkind` `v`): read-only, every column nullable. A materialized view is left out (ADR-0072). */
|
|
62
|
+
view: z.boolean(),
|
|
59
63
|
column_name: z.string(),
|
|
60
64
|
type_name: z.string(),
|
|
61
65
|
/** `pg_type.typtype`: `b` base, `e` enum, `d` domain, … */
|
|
@@ -91,10 +95,11 @@ export interface Catalog {
|
|
|
91
95
|
readonly foreignKeys: readonly CatalogForeignKey[]
|
|
92
96
|
}
|
|
93
97
|
|
|
94
|
-
/** One row per column of every ordinary or partitioned table
|
|
98
|
+
/** One row per column of every ordinary or partitioned table and view of the schema, in table then column order. */
|
|
95
99
|
const CATALOG_QUERY = `
|
|
96
100
|
SELECT
|
|
97
101
|
c.relname::text AS table_name,
|
|
102
|
+
c.relkind = 'v' AS view,
|
|
98
103
|
a.attname::text AS column_name,
|
|
99
104
|
t.typname::text AS type_name,
|
|
100
105
|
t.typtype::text AS type_type,
|
|
@@ -113,7 +118,7 @@ FROM pg_attribute a
|
|
|
113
118
|
JOIN pg_class c ON c.oid = a.attrelid
|
|
114
119
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
115
120
|
JOIN pg_type t ON t.oid = a.atttypid
|
|
116
|
-
WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') AND NOT c.relispartition AND a.attnum > 0 AND NOT a.attisdropped
|
|
121
|
+
WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'v') AND NOT c.relispartition AND a.attnum > 0 AND NOT a.attisdropped
|
|
117
122
|
ORDER BY c.relname, a.attnum
|
|
118
123
|
`
|
|
119
124
|
|
|
@@ -182,13 +187,14 @@ export async function introspectCatalog(url: string, schema: string, objects: re
|
|
|
182
187
|
}
|
|
183
188
|
|
|
184
189
|
/**
|
|
185
|
-
* `note_comments` → `NoteCommentsTable
|
|
186
|
-
* name that would not start with a letter (`_123`) gets a `T` prefix, so
|
|
190
|
+
* `note_comments` → `NoteCommentsTable`, a view `deal_summaries` → `DealSummariesView`; the suffix keeps every name
|
|
191
|
+
* clear of `DB` and the imported type names. A name that would not start with a letter (`_123`) gets a `T` prefix, so
|
|
192
|
+
* it stays a TypeScript identifier.
|
|
187
193
|
*/
|
|
188
|
-
function interfaceName(table: string): string {
|
|
194
|
+
function interfaceName(table: string, view: boolean): string {
|
|
189
195
|
const words = table.split('_').filter((word) => word !== '')
|
|
190
196
|
const pascal = words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')
|
|
191
|
-
return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}Table`
|
|
197
|
+
return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}${view ? 'View' : 'Table'}`
|
|
192
198
|
}
|
|
193
199
|
|
|
194
200
|
/** As keys of the generated object literal these would set or shadow the prototype instead of naming a table. */
|
|
@@ -226,23 +232,34 @@ export interface DescribedColumn {
|
|
|
226
232
|
readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined
|
|
227
233
|
}
|
|
228
234
|
|
|
229
|
-
/**
|
|
235
|
+
/**
|
|
236
|
+
* A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
|
|
237
|
+
* not read.
|
|
238
|
+
*/
|
|
230
239
|
export interface LeftOut {
|
|
231
|
-
/** The column's type, as its author wrote it. */
|
|
240
|
+
/** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
|
|
232
241
|
readonly leftOut: string
|
|
242
|
+
readonly of: LeftOutKind
|
|
233
243
|
}
|
|
234
244
|
|
|
245
|
+
/** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
|
|
246
|
+
export type LeftOutKind = 'generated' | 'view'
|
|
247
|
+
|
|
235
248
|
/** A column the module leaves out; only `ctx.sql` reaches it. */
|
|
236
249
|
export interface LeftOutColumn {
|
|
237
250
|
readonly table: string
|
|
238
251
|
readonly column: string
|
|
239
252
|
/** Its type, as its author wrote it. */
|
|
240
253
|
readonly type: string
|
|
254
|
+
readonly of: LeftOutKind
|
|
241
255
|
}
|
|
242
256
|
|
|
243
257
|
/** What codegen says of a left-out column: in the module, `name` is the column; in its output, `table.column`. */
|
|
244
|
-
export function leftOutText(name: string, type: string): string {
|
|
245
|
-
return `${name} (${type}, generated) is left out: the data layer does not read it; ctx.sql does`
|
|
258
|
+
export function leftOutText(name: string, type: string, of: LeftOutKind): string {
|
|
259
|
+
if (of === 'generated') return `${name} (${type}, generated) is left out: the data layer does not read it; ctx.sql does`
|
|
260
|
+
return `${name} (${
|
|
261
|
+
type === '' ? 'no declared type' : type
|
|
262
|
+
}, of a view) is left out: the data layer does not read it; cast it to a type it reads, or read it with ctx.sql`
|
|
246
263
|
}
|
|
247
264
|
|
|
248
265
|
/** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
|
|
@@ -270,15 +287,22 @@ export interface NamedColumn {
|
|
|
270
287
|
readonly column_name: string
|
|
271
288
|
}
|
|
272
289
|
|
|
290
|
+
/** A column of a table or of a view, as `renderTables` reads it. */
|
|
291
|
+
export interface RelationColumn extends NamedColumn {
|
|
292
|
+
/** The relation is a view: read-only, with no key or foreign key. */
|
|
293
|
+
readonly view: boolean
|
|
294
|
+
}
|
|
295
|
+
|
|
273
296
|
/**
|
|
274
297
|
* A column's types; for a type the data layer does not read, a generated column (any such type: an array, `json`, a
|
|
275
|
-
* range, a composite, a domain) is left out, unless a key needs it, and any other
|
|
298
|
+
* range, a composite, a domain) is left out, unless a key needs it, and so is a view's column; any other is refused.
|
|
276
299
|
*/
|
|
277
300
|
function describePostgres(column: CatalogColumn): DescribedColumn | LeftOut {
|
|
278
301
|
const scalar = scalarType(column)
|
|
279
302
|
if (scalar === undefined) {
|
|
303
|
+
if (column.view) return { leftOut: column.formatted_type, of: 'view' }
|
|
280
304
|
if (column.computed && column.keyed) throw leftOutRefusal(columnPath(column), 'it is in the primary key or a unique key')
|
|
281
|
-
if (column.computed) return { leftOut: column.formatted_type }
|
|
305
|
+
if (column.computed) return { leftOut: column.formatted_type, of: 'generated' }
|
|
282
306
|
if (column.type_type === 'b' && column.type_name === 'json') {
|
|
283
307
|
throw new CodegenError(
|
|
284
308
|
`${columnPath(column)} has type json; declare it jsonb, which the data layer reads and binds (json keeps whitespace and duplicate keys)`,
|
|
@@ -317,9 +341,9 @@ function columnType(column: DescribedColumn): Rendered {
|
|
|
317
341
|
}
|
|
318
342
|
|
|
319
343
|
/**
|
|
320
|
-
* The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take,
|
|
321
|
-
* runtime column list with each table's foreign keys to application tables
|
|
322
|
-
* Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
344
|
+
* The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
|
|
345
|
+
* and the runtime column list with each table's foreign keys to application tables and each view marked; with the
|
|
346
|
+
* columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
323
347
|
*/
|
|
324
348
|
export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
|
|
325
349
|
return renderTables(catalog, foreignKeys, describePostgres)
|
|
@@ -327,12 +351,12 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
|
|
|
327
351
|
|
|
328
352
|
/**
|
|
329
353
|
* `renderSchema` over columns of any database: `describe` gives each column's types and list field, refuses a type the
|
|
330
|
-
* data layer does not read, or answers `LeftOut` for a generated column of such a type. That column
|
|
331
|
-
* module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
332
|
-
* key that names it, and a table it would leave without a column, are refused
|
|
333
|
-
* not rendered; keys keep the given order.
|
|
354
|
+
* data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
|
|
355
|
+
* is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
356
|
+
* reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
|
|
357
|
+
* without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
|
|
334
358
|
*/
|
|
335
|
-
export function renderTables<C extends
|
|
359
|
+
export function renderTables<C extends RelationColumn>(
|
|
336
360
|
catalog: readonly C[],
|
|
337
361
|
foreignKeys: readonly ForeignKeyColumns[],
|
|
338
362
|
describe: (column: C) => DescribedColumn | LeftOut,
|
|
@@ -350,14 +374,16 @@ export function renderTables<C extends NamedColumn>(
|
|
|
350
374
|
columns.push(column)
|
|
351
375
|
tables.set(column.table_name, columns)
|
|
352
376
|
}
|
|
377
|
+
const views = new Set(catalog.filter((column) => column.view).map((column) => column.table_name))
|
|
353
378
|
const names = [...tables.keys()].sort()
|
|
354
379
|
const owners = new Map<string, string>()
|
|
355
380
|
const used = new Set<string>()
|
|
356
381
|
const interfaces: string[] = []
|
|
357
382
|
const described = new Map<C, DescribedColumn>()
|
|
358
383
|
const leftOut: LeftOutColumn[] = []
|
|
384
|
+
const emptyViews = new Set<string>()
|
|
359
385
|
for (const table of names) {
|
|
360
|
-
const name = interfaceName(table)
|
|
386
|
+
const name = interfaceName(table, views.has(table))
|
|
361
387
|
const owner = owners.get(name)
|
|
362
388
|
if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
|
|
363
389
|
owners.set(name, table)
|
|
@@ -367,9 +393,9 @@ export function renderTables<C extends NamedColumn>(
|
|
|
367
393
|
const description = describe(column)
|
|
368
394
|
if ('leftOut' in description) {
|
|
369
395
|
const type = description.leftOut
|
|
370
|
-
leftOut.push({ table, column: column.column_name, type })
|
|
396
|
+
leftOut.push({ table, column: column.column_name, type, of: description.of })
|
|
371
397
|
// A type name is the database's text: one that could end the comment line is quoted there.
|
|
372
|
-
fields.push(`\t// ${leftOutText(column.column_name, /^[\w (),.[\]]+$/.test(type) ? type : quote(type))}\n`)
|
|
398
|
+
fields.push(`\t// ${leftOutText(column.column_name, type === '' || /^[\w (),.[\]]+$/.test(type) ? type : quote(type), description.of)}\n`)
|
|
373
399
|
continue
|
|
374
400
|
}
|
|
375
401
|
kept.push(column)
|
|
@@ -378,12 +404,19 @@ export function renderTables<C extends NamedColumn>(
|
|
|
378
404
|
if (rendered.uses !== undefined) used.add(rendered.uses)
|
|
379
405
|
fields.push(`\t${column.column_name}: ${rendered.type}\n`)
|
|
380
406
|
}
|
|
407
|
+
if (kept.length === 0 && views.has(table)) {
|
|
408
|
+
emptyViews.add(table)
|
|
409
|
+
continue
|
|
410
|
+
}
|
|
381
411
|
if (kept.length === 0) {
|
|
382
412
|
throw new CodegenError(`table ${table} has only generated columns of types the data layer does not read, which codegen leaves out`)
|
|
383
413
|
}
|
|
384
414
|
tables.set(table, kept)
|
|
385
415
|
interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
|
|
386
416
|
}
|
|
417
|
+
for (const view of emptyViews) tables.delete(view)
|
|
418
|
+
const rendered = names.filter((table) => !emptyViews.has(table))
|
|
419
|
+
const renderedViews = rendered.filter((table) => views.has(table))
|
|
387
420
|
const leftOutPaths = new Set(leftOut.map((column) => columnPath({ table_name: column.table, column_name: column.column })))
|
|
388
421
|
for (const key of foreignKeys) {
|
|
389
422
|
if (!tables.has(key.table_name) || !tables.has(key.referenced_table)) continue
|
|
@@ -399,7 +432,7 @@ export function renderTables<C extends NamedColumn>(
|
|
|
399
432
|
`import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
|
|
400
433
|
...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
|
|
401
434
|
]
|
|
402
|
-
const db =
|
|
435
|
+
const db = rendered.map((table) => `\t${table}: ${interfaceName(table, views.has(table))}\n`).join('')
|
|
403
436
|
const keysOf = (table: string): string => {
|
|
404
437
|
const keys = foreignKeys.filter((key) => key.table_name === table && tables.has(key.referenced_table))
|
|
405
438
|
if (keys.length === 0) return '\t\tforeignKeys: [],\n'
|
|
@@ -418,21 +451,35 @@ export function renderTables<C extends NamedColumn>(
|
|
|
418
451
|
const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
|
|
419
452
|
return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
|
|
420
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
|
+
}
|
|
421
462
|
const datesOf = (table: string): string =>
|
|
422
|
-
`${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}`
|
|
423
|
-
const columns =
|
|
463
|
+
`${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}${notNullOf(table)}`
|
|
464
|
+
const columns = rendered
|
|
424
465
|
.map((table) =>
|
|
425
466
|
`\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
|
|
426
467
|
keysOf(table)
|
|
427
|
-
}${datesOf(table)}\t},\n`
|
|
468
|
+
}${datesOf(table)}${views.has(table) ? '\t\tview: true,\n' : ''}\t},\n`
|
|
428
469
|
)
|
|
429
470
|
.join('')
|
|
471
|
+
// The views ride in the list's type, so the policy types know which tables only a read reaches. One per line, as
|
|
472
|
+
// dprint keeps a union of two or more, so the module stays formatter-stable however many views there are.
|
|
473
|
+
const viewsAlias = renderedViews.length === 1
|
|
474
|
+
? `export type Views = ${quote(renderedViews[0] ?? '')}\n`
|
|
475
|
+
: `export type Views =\n${renderedViews.map((view) => `\t| ${quote(view)}\n`).join('')}`
|
|
430
476
|
const source = [
|
|
431
477
|
`${HEADER}\n`,
|
|
432
478
|
imports.join(''),
|
|
433
479
|
...interfaces,
|
|
434
480
|
`export interface DB {\n${db}}\n`,
|
|
435
|
-
|
|
481
|
+
...(renderedViews.length === 0 ? [] : [viewsAlias]),
|
|
482
|
+
`export const columns: ${renderedViews.length === 0 ? 'TypedColumnList<DB>' : 'TypedColumnList<DB, Views>'} = {\n${columns}}\n`,
|
|
436
483
|
].join('\n')
|
|
437
484
|
return { source, leftOut }
|
|
438
485
|
}
|