@fabrika/db 0.9.0-dev.11 → 0.9.0-dev.12
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/codegen-sqlite.ts +8 -5
- package/src/codegen.ts +64 -27
- package/src/index.ts +2 -0
- package/src/orm-types.ts +18 -10
- package/src/orm.ts +19 -5
- package/src/policy.ts +58 -9
- package/src/store.ts +4 -0
- package/src/tables.ts +3 -0
- package/src/testing-shared.ts +3 -0
- package/src/vocabulary-tables.ts +88 -17
- package/types/src/codegen.d.ts +24 -11
- package/types/src/index.d.ts +1 -1
- package/types/src/orm-types.d.ts +14 -9
- package/types/src/orm.d.ts +5 -0
- package/types/src/policy.d.ts +6 -2
- package/types/src/tables.d.ts +1 -1
- package/types/src/vocabulary-tables.d.ts +82 -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.12",
|
|
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.12",
|
|
96
|
+
"@fabrika/platform": "0.9.0-dev.12",
|
|
97
|
+
"@fabrika/platform-node": "0.9.0-dev.12",
|
|
98
98
|
"kysely": "0.29.6",
|
|
99
99
|
"kysely-postgres-js": "5.0.1",
|
|
100
100
|
"zod": "^3.25.76"
|
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
|
@@ -56,6 +56,8 @@ export class CodegenError extends Error {
|
|
|
56
56
|
|
|
57
57
|
const catalogColumnSchema = z.object({
|
|
58
58
|
table_name: z.string(),
|
|
59
|
+
/** The relation is a view (`relkind` `v`): read-only, every column nullable. A materialized view is left out (ADR-0072). */
|
|
60
|
+
view: z.boolean(),
|
|
59
61
|
column_name: z.string(),
|
|
60
62
|
type_name: z.string(),
|
|
61
63
|
/** `pg_type.typtype`: `b` base, `e` enum, `d` domain, … */
|
|
@@ -91,10 +93,11 @@ export interface Catalog {
|
|
|
91
93
|
readonly foreignKeys: readonly CatalogForeignKey[]
|
|
92
94
|
}
|
|
93
95
|
|
|
94
|
-
/** One row per column of every ordinary or partitioned table
|
|
96
|
+
/** One row per column of every ordinary or partitioned table and view of the schema, in table then column order. */
|
|
95
97
|
const CATALOG_QUERY = `
|
|
96
98
|
SELECT
|
|
97
99
|
c.relname::text AS table_name,
|
|
100
|
+
c.relkind = 'v' AS view,
|
|
98
101
|
a.attname::text AS column_name,
|
|
99
102
|
t.typname::text AS type_name,
|
|
100
103
|
t.typtype::text AS type_type,
|
|
@@ -113,7 +116,7 @@ FROM pg_attribute a
|
|
|
113
116
|
JOIN pg_class c ON c.oid = a.attrelid
|
|
114
117
|
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
115
118
|
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
|
|
119
|
+
WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'v') AND NOT c.relispartition AND a.attnum > 0 AND NOT a.attisdropped
|
|
117
120
|
ORDER BY c.relname, a.attnum
|
|
118
121
|
`
|
|
119
122
|
|
|
@@ -182,13 +185,14 @@ export async function introspectCatalog(url: string, schema: string, objects: re
|
|
|
182
185
|
}
|
|
183
186
|
|
|
184
187
|
/**
|
|
185
|
-
* `note_comments` → `NoteCommentsTable
|
|
186
|
-
* name that would not start with a letter (`_123`) gets a `T` prefix, so
|
|
188
|
+
* `note_comments` → `NoteCommentsTable`, a view `deal_summaries` → `DealSummariesView`; the suffix keeps every name
|
|
189
|
+
* clear of `DB` and the imported type names. A name that would not start with a letter (`_123`) gets a `T` prefix, so
|
|
190
|
+
* it stays a TypeScript identifier.
|
|
187
191
|
*/
|
|
188
|
-
function interfaceName(table: string): string {
|
|
192
|
+
function interfaceName(table: string, view: boolean): string {
|
|
189
193
|
const words = table.split('_').filter((word) => word !== '')
|
|
190
194
|
const pascal = words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')
|
|
191
|
-
return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}Table`
|
|
195
|
+
return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}${view ? 'View' : 'Table'}`
|
|
192
196
|
}
|
|
193
197
|
|
|
194
198
|
/** As keys of the generated object literal these would set or shadow the prototype instead of naming a table. */
|
|
@@ -226,23 +230,34 @@ export interface DescribedColumn {
|
|
|
226
230
|
readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined
|
|
227
231
|
}
|
|
228
232
|
|
|
229
|
-
/**
|
|
233
|
+
/**
|
|
234
|
+
* A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
|
|
235
|
+
* not read.
|
|
236
|
+
*/
|
|
230
237
|
export interface LeftOut {
|
|
231
|
-
/** The column's type, as its author wrote it. */
|
|
238
|
+
/** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
|
|
232
239
|
readonly leftOut: string
|
|
240
|
+
readonly of: LeftOutKind
|
|
233
241
|
}
|
|
234
242
|
|
|
243
|
+
/** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
|
|
244
|
+
export type LeftOutKind = 'generated' | 'view'
|
|
245
|
+
|
|
235
246
|
/** A column the module leaves out; only `ctx.sql` reaches it. */
|
|
236
247
|
export interface LeftOutColumn {
|
|
237
248
|
readonly table: string
|
|
238
249
|
readonly column: string
|
|
239
250
|
/** Its type, as its author wrote it. */
|
|
240
251
|
readonly type: string
|
|
252
|
+
readonly of: LeftOutKind
|
|
241
253
|
}
|
|
242
254
|
|
|
243
255
|
/** 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`
|
|
256
|
+
export function leftOutText(name: string, type: string, of: LeftOutKind): string {
|
|
257
|
+
if (of === 'generated') return `${name} (${type}, generated) is left out: the data layer does not read it; ctx.sql does`
|
|
258
|
+
return `${name} (${
|
|
259
|
+
type === '' ? 'no declared type' : type
|
|
260
|
+
}, 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
261
|
}
|
|
247
262
|
|
|
248
263
|
/** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
|
|
@@ -270,15 +285,22 @@ export interface NamedColumn {
|
|
|
270
285
|
readonly column_name: string
|
|
271
286
|
}
|
|
272
287
|
|
|
288
|
+
/** A column of a table or of a view, as `renderTables` reads it. */
|
|
289
|
+
export interface RelationColumn extends NamedColumn {
|
|
290
|
+
/** The relation is a view: read-only, with no key or foreign key. */
|
|
291
|
+
readonly view: boolean
|
|
292
|
+
}
|
|
293
|
+
|
|
273
294
|
/**
|
|
274
295
|
* 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
|
|
296
|
+
* 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
297
|
*/
|
|
277
298
|
function describePostgres(column: CatalogColumn): DescribedColumn | LeftOut {
|
|
278
299
|
const scalar = scalarType(column)
|
|
279
300
|
if (scalar === undefined) {
|
|
301
|
+
if (column.view) return { leftOut: column.formatted_type, of: 'view' }
|
|
280
302
|
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 }
|
|
303
|
+
if (column.computed) return { leftOut: column.formatted_type, of: 'generated' }
|
|
282
304
|
if (column.type_type === 'b' && column.type_name === 'json') {
|
|
283
305
|
throw new CodegenError(
|
|
284
306
|
`${columnPath(column)} has type json; declare it jsonb, which the data layer reads and binds (json keeps whitespace and duplicate keys)`,
|
|
@@ -317,9 +339,9 @@ function columnType(column: DescribedColumn): Rendered {
|
|
|
317
339
|
}
|
|
318
340
|
|
|
319
341
|
/**
|
|
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.
|
|
342
|
+
* The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
|
|
343
|
+
* and the runtime column list with each table's foreign keys to application tables and each view marked; with the
|
|
344
|
+
* columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
323
345
|
*/
|
|
324
346
|
export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
|
|
325
347
|
return renderTables(catalog, foreignKeys, describePostgres)
|
|
@@ -327,12 +349,12 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
|
|
|
327
349
|
|
|
328
350
|
/**
|
|
329
351
|
* `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.
|
|
352
|
+
* data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
|
|
353
|
+
* is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
354
|
+
* reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
|
|
355
|
+
* without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
|
|
334
356
|
*/
|
|
335
|
-
export function renderTables<C extends
|
|
357
|
+
export function renderTables<C extends RelationColumn>(
|
|
336
358
|
catalog: readonly C[],
|
|
337
359
|
foreignKeys: readonly ForeignKeyColumns[],
|
|
338
360
|
describe: (column: C) => DescribedColumn | LeftOut,
|
|
@@ -350,14 +372,16 @@ export function renderTables<C extends NamedColumn>(
|
|
|
350
372
|
columns.push(column)
|
|
351
373
|
tables.set(column.table_name, columns)
|
|
352
374
|
}
|
|
375
|
+
const views = new Set(catalog.filter((column) => column.view).map((column) => column.table_name))
|
|
353
376
|
const names = [...tables.keys()].sort()
|
|
354
377
|
const owners = new Map<string, string>()
|
|
355
378
|
const used = new Set<string>()
|
|
356
379
|
const interfaces: string[] = []
|
|
357
380
|
const described = new Map<C, DescribedColumn>()
|
|
358
381
|
const leftOut: LeftOutColumn[] = []
|
|
382
|
+
const emptyViews = new Set<string>()
|
|
359
383
|
for (const table of names) {
|
|
360
|
-
const name = interfaceName(table)
|
|
384
|
+
const name = interfaceName(table, views.has(table))
|
|
361
385
|
const owner = owners.get(name)
|
|
362
386
|
if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
|
|
363
387
|
owners.set(name, table)
|
|
@@ -367,9 +391,9 @@ export function renderTables<C extends NamedColumn>(
|
|
|
367
391
|
const description = describe(column)
|
|
368
392
|
if ('leftOut' in description) {
|
|
369
393
|
const type = description.leftOut
|
|
370
|
-
leftOut.push({ table, column: column.column_name, type })
|
|
394
|
+
leftOut.push({ table, column: column.column_name, type, of: description.of })
|
|
371
395
|
// 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`)
|
|
396
|
+
fields.push(`\t// ${leftOutText(column.column_name, type === '' || /^[\w (),.[\]]+$/.test(type) ? type : quote(type), description.of)}\n`)
|
|
373
397
|
continue
|
|
374
398
|
}
|
|
375
399
|
kept.push(column)
|
|
@@ -378,12 +402,19 @@ export function renderTables<C extends NamedColumn>(
|
|
|
378
402
|
if (rendered.uses !== undefined) used.add(rendered.uses)
|
|
379
403
|
fields.push(`\t${column.column_name}: ${rendered.type}\n`)
|
|
380
404
|
}
|
|
405
|
+
if (kept.length === 0 && views.has(table)) {
|
|
406
|
+
emptyViews.add(table)
|
|
407
|
+
continue
|
|
408
|
+
}
|
|
381
409
|
if (kept.length === 0) {
|
|
382
410
|
throw new CodegenError(`table ${table} has only generated columns of types the data layer does not read, which codegen leaves out`)
|
|
383
411
|
}
|
|
384
412
|
tables.set(table, kept)
|
|
385
413
|
interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
|
|
386
414
|
}
|
|
415
|
+
for (const view of emptyViews) tables.delete(view)
|
|
416
|
+
const rendered = names.filter((table) => !emptyViews.has(table))
|
|
417
|
+
const renderedViews = rendered.filter((table) => views.has(table))
|
|
387
418
|
const leftOutPaths = new Set(leftOut.map((column) => columnPath({ table_name: column.table, column_name: column.column })))
|
|
388
419
|
for (const key of foreignKeys) {
|
|
389
420
|
if (!tables.has(key.table_name) || !tables.has(key.referenced_table)) continue
|
|
@@ -399,7 +430,7 @@ export function renderTables<C extends NamedColumn>(
|
|
|
399
430
|
`import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
|
|
400
431
|
...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
|
|
401
432
|
]
|
|
402
|
-
const db =
|
|
433
|
+
const db = rendered.map((table) => `\t${table}: ${interfaceName(table, views.has(table))}\n`).join('')
|
|
403
434
|
const keysOf = (table: string): string => {
|
|
404
435
|
const keys = foreignKeys.filter((key) => key.table_name === table && tables.has(key.referenced_table))
|
|
405
436
|
if (keys.length === 0) return '\t\tforeignKeys: [],\n'
|
|
@@ -420,19 +451,25 @@ export function renderTables<C extends NamedColumn>(
|
|
|
420
451
|
}
|
|
421
452
|
const datesOf = (table: string): string =>
|
|
422
453
|
`${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}`
|
|
423
|
-
const columns =
|
|
454
|
+
const columns = rendered
|
|
424
455
|
.map((table) =>
|
|
425
456
|
`\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
|
|
426
457
|
keysOf(table)
|
|
427
|
-
}${datesOf(table)}\t},\n`
|
|
458
|
+
}${datesOf(table)}${views.has(table) ? '\t\tview: true,\n' : ''}\t},\n`
|
|
428
459
|
)
|
|
429
460
|
.join('')
|
|
461
|
+
// The views ride in the list's type, so the policy types know which tables only a read reaches. One per line, as
|
|
462
|
+
// dprint keeps a union of two or more, so the module stays formatter-stable however many views there are.
|
|
463
|
+
const viewsAlias = renderedViews.length === 1
|
|
464
|
+
? `export type Views = ${quote(renderedViews[0] ?? '')}\n`
|
|
465
|
+
: `export type Views =\n${renderedViews.map((view) => `\t| ${quote(view)}\n`).join('')}`
|
|
430
466
|
const source = [
|
|
431
467
|
`${HEADER}\n`,
|
|
432
468
|
imports.join(''),
|
|
433
469
|
...interfaces,
|
|
434
470
|
`export interface DB {\n${db}}\n`,
|
|
435
|
-
|
|
471
|
+
...(renderedViews.length === 0 ? [] : [viewsAlias]),
|
|
472
|
+
`export const columns: ${renderedViews.length === 0 ? 'TypedColumnList<DB>' : 'TypedColumnList<DB, Views>'} = {\n${columns}}\n`,
|
|
436
473
|
].join('\n')
|
|
437
474
|
return { source, leftOut }
|
|
438
475
|
}
|
package/src/index.ts
CHANGED
|
@@ -112,6 +112,7 @@ export {
|
|
|
112
112
|
export { type TablePolicies, tablePolicies } from './tables'
|
|
113
113
|
export type {
|
|
114
114
|
ColumnTypes,
|
|
115
|
+
ColumnViews,
|
|
115
116
|
DefineVocabularyPolicies,
|
|
116
117
|
NormalizedPolicies,
|
|
117
118
|
TableVocabulary,
|
|
@@ -124,4 +125,5 @@ export type {
|
|
|
124
125
|
VocabularyDimensionScope,
|
|
125
126
|
VocabularyPolicyMap,
|
|
126
127
|
VocabularyTablePolicy,
|
|
128
|
+
VocabularyViewPolicy,
|
|
127
129
|
} from './vocabulary-tables'
|
package/src/orm-types.ts
CHANGED
|
@@ -103,6 +103,8 @@ export interface IndexedTable {
|
|
|
103
103
|
readonly versioned: boolean
|
|
104
104
|
/** A queue table: its rows are claimed and finished through `row.ref`. */
|
|
105
105
|
readonly queued: boolean
|
|
106
|
+
/** A view: read like its scope's tables, written by no site (ADR-0072). */
|
|
107
|
+
readonly view: boolean
|
|
106
108
|
}
|
|
107
109
|
|
|
108
110
|
type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> = {
|
|
@@ -128,6 +130,7 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
|
|
|
128
130
|
readonly reach: ReachOf<P, T, V>
|
|
129
131
|
readonly versioned: PolicyOf<P, T> extends { readonly version: string } ? true : false
|
|
130
132
|
readonly queued: PolicyOf<P, T> extends { readonly queue: object } ? true : false
|
|
133
|
+
readonly view: PolicyOf<P, T> extends { readonly view: true } ? true : false
|
|
131
134
|
}
|
|
132
135
|
|
|
133
136
|
type OwnerTable<P, D> = { [K in keyof P]: P[K] extends { readonly scope: { readonly dimension: D } } ? K : never }[keyof P]
|
|
@@ -386,19 +389,21 @@ export interface UnownedTarget<D extends string> {
|
|
|
386
389
|
readonly remove: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>
|
|
387
390
|
}
|
|
388
391
|
|
|
389
|
-
/** A child table of the target: its rows are addressed by their own key under the target. */
|
|
392
|
+
/** A child table of the target: its rows are addressed by their own key under the target; a view's are only read. */
|
|
390
393
|
export interface ChildRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
|
|
391
394
|
readonly list: Read<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>
|
|
392
395
|
readonly get: Read<T, E, A, (key: string) => Promise<RowFor<E, A>>>
|
|
393
|
-
readonly insert:
|
|
394
|
-
|
|
396
|
+
readonly insert: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`>
|
|
397
|
+
: Write<T, E, 'insert', A, K, InsertMethod<E>>
|
|
398
|
+
readonly update: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Update<
|
|
395
399
|
T,
|
|
396
400
|
E,
|
|
397
401
|
A,
|
|
398
402
|
K,
|
|
399
403
|
(key: string, values: { [C in keyof UpdateValuesOf<E, A>]: UpdateValuesOf<E, A>[C] }, ...version: VersionArguments<E>) => Promise<Saved<E>>
|
|
400
404
|
>
|
|
401
|
-
readonly remove:
|
|
405
|
+
readonly remove: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`>
|
|
406
|
+
: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>
|
|
402
407
|
}
|
|
403
408
|
|
|
404
409
|
/** A dimension table the target contains: listed in it, and inserted into it by a mutation of its insert action. */
|
|
@@ -603,19 +608,22 @@ export type UnscopedMode = 'read' | 'write'
|
|
|
603
608
|
export type UnscopedDeclaration<Table extends string, Mode extends UnscopedMode> = { readonly [T in Table]?: Mode }
|
|
604
609
|
|
|
605
610
|
/**
|
|
606
|
-
* The tables of `U` whose mode may be `'write'` that no site writes: a reference table. A union or optional
|
|
607
|
-
* admits `'write'` counts, because the declaration it types may hold it.
|
|
611
|
+
* The tables of `U` whose mode may be `'write'` that no site writes: a reference table or a view. A union or optional
|
|
612
|
+
* mode that admits `'write'` counts, because the declaration it types may hold it.
|
|
608
613
|
*/
|
|
609
614
|
type ReadOnlyWritten<Ix extends AnyDbIndex, U> = {
|
|
610
|
-
[T in keyof U & TableName<Ix>]: 'write' extends U[T]
|
|
615
|
+
[T in keyof U & TableName<Ix>]: 'write' extends U[T]
|
|
616
|
+
? Ix['tables'][T]['mode'] extends 'reference' ? T : Ix['tables'][T]['view'] extends true ? T : never
|
|
617
|
+
: never
|
|
611
618
|
}[keyof U & TableName<Ix>]
|
|
612
619
|
|
|
613
|
-
type ReadOnlyMessage<T extends string> =
|
|
614
|
-
`${T} is a
|
|
620
|
+
type ReadOnlyMessage<T extends string, E extends IndexedTable> = E['view'] extends true
|
|
621
|
+
? `${T} is a view, which no site writes: its rows come from the tables it reads, so declare unscoped: { ${T}: 'read' }`
|
|
622
|
+
: `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`
|
|
615
623
|
|
|
616
624
|
/** An `unscoped` declaration's `'write'` of a reference table, refused at its own line. */
|
|
617
625
|
export type ReadOnlyUnscoped<Ix extends AnyDbIndex, U> = [ReadOnlyWritten<Ix, U>] extends [never] ? unknown
|
|
618
|
-
: { readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T>> }
|
|
626
|
+
: { readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T, Ix['tables'][T]>> }
|
|
619
627
|
|
|
620
628
|
type KeylessMessage<T extends string> = `${T} is a reference table, which has no key: read it with list`
|
|
621
629
|
|
package/src/orm.ts
CHANGED
|
@@ -722,6 +722,17 @@ const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
|
|
|
722
722
|
/** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
|
|
723
723
|
const CLAIM_REARM_MIN_MS = 1_000
|
|
724
724
|
|
|
725
|
+
/**
|
|
726
|
+
* When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
|
|
727
|
+
* at the next due row it would take but no sooner than a second after it, or never when it would take none.
|
|
728
|
+
*/
|
|
729
|
+
export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
|
|
730
|
+
if (full) {
|
|
731
|
+
return new Date(now.getTime() + 1)
|
|
732
|
+
}
|
|
733
|
+
return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
|
|
734
|
+
}
|
|
735
|
+
|
|
725
736
|
/** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
|
|
726
737
|
function backoffMs(tickMs: number, attempts: number): number {
|
|
727
738
|
let backoff = tickMs
|
|
@@ -827,9 +838,9 @@ async function claimRows(
|
|
|
827
838
|
// The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
|
|
828
839
|
const fence = runtime.capabilities.fence()
|
|
829
840
|
if (fence !== null && rows.length > 0) {
|
|
830
|
-
|
|
831
|
-
let
|
|
832
|
-
if (
|
|
841
|
+
const full = rows.length >= limit
|
|
842
|
+
let next: Date | null = null
|
|
843
|
+
if (!full) {
|
|
833
844
|
const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
|
|
834
845
|
const [row] = answerRows(
|
|
835
846
|
dialect,
|
|
@@ -837,9 +848,9 @@ async function claimRows(
|
|
|
837
848
|
rowColumnsOf(model),
|
|
838
849
|
await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
|
|
839
850
|
)
|
|
840
|
-
|
|
851
|
+
next = row === undefined ? null : dueOf(row, table, queue.due)
|
|
841
852
|
}
|
|
842
|
-
await rearmClaim(runtime, session, fence,
|
|
853
|
+
await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
|
|
843
854
|
}
|
|
844
855
|
return {
|
|
845
856
|
rows: await answerFiles(
|
|
@@ -996,6 +1007,9 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
|
|
|
996
1007
|
return equals(table, keyOf(model), id)
|
|
997
1008
|
}
|
|
998
1009
|
const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
|
|
1010
|
+
if (model.view) {
|
|
1011
|
+
return refused(site, 'read_only', `${table} is a view, which no handler writes`)
|
|
1012
|
+
}
|
|
999
1013
|
if (mode === 'read') {
|
|
1000
1014
|
const verb = operation === 'remove' ? 'remove' : operation
|
|
1001
1015
|
return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
|
package/src/policy.ts
CHANGED
|
@@ -22,7 +22,7 @@ import { PolicyError } from './errors'
|
|
|
22
22
|
import { isPlainIdentifier } from './identifier'
|
|
23
23
|
import type { Unavailable } from './orm-types'
|
|
24
24
|
export type { RowOf } from './orm-types'
|
|
25
|
-
import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
|
|
25
|
+
import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables'
|
|
26
26
|
|
|
27
27
|
export interface DimensionScope<Col extends string> {
|
|
28
28
|
readonly dimension: string
|
|
@@ -164,6 +164,8 @@ export interface TableColumns<Col extends string = string, Table extends string
|
|
|
164
164
|
readonly booleans?: readonly Col[]
|
|
165
165
|
/** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
|
|
166
166
|
readonly json?: readonly Col[]
|
|
167
|
+
/** A view: read-only, with no foreign key; absent for a table. */
|
|
168
|
+
readonly view?: true
|
|
167
169
|
}
|
|
168
170
|
|
|
169
171
|
/** The columns and foreign keys of every table, generated next to the schema types. */
|
|
@@ -231,6 +233,8 @@ export interface TableModel {
|
|
|
231
233
|
readonly json: NameSet
|
|
232
234
|
/** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
|
|
233
235
|
readonly foreignKeys: readonly ForeignKey[]
|
|
236
|
+
/** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
|
|
237
|
+
readonly view: boolean
|
|
234
238
|
/**
|
|
235
239
|
* The containment links this table carries a column for, nearest first: a dimension table's container and
|
|
236
240
|
* the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
|
|
@@ -305,7 +309,7 @@ export function defineTables<DB, P>(vocabularyInput: unknown, columns: unknown):
|
|
|
305
309
|
/** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
|
|
306
310
|
export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never]
|
|
307
311
|
? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'>
|
|
308
|
-
: DefineVocabularyPolicies<ColumnTypes<C>, V
|
|
312
|
+
: DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>
|
|
309
313
|
|
|
310
314
|
/**
|
|
311
315
|
* The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
|
|
@@ -350,7 +354,7 @@ function parseVocabulary(input: unknown): VocabularyModel {
|
|
|
350
354
|
return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
|
|
351
355
|
}
|
|
352
356
|
|
|
353
|
-
const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json'])
|
|
357
|
+
const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json', 'view'])
|
|
354
358
|
const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
|
|
355
359
|
const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
|
|
356
360
|
const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
|
|
@@ -407,14 +411,28 @@ function parseTables(columnsInput: unknown, policiesInput: unknown, vocabulary:
|
|
|
407
411
|
for (let index = 0; index < tables.length; index++) {
|
|
408
412
|
const table = tables[index] ?? ''
|
|
409
413
|
const policy = ownEntry(policies, table)
|
|
414
|
+
const entry = ownEntry(columns, table)
|
|
415
|
+
// A view without a policy stays what it was before codegen read views: only ctx.sql reads it.
|
|
416
|
+
if (policy === undefined && isViewEntry(table, entry)) {
|
|
417
|
+
continue
|
|
418
|
+
}
|
|
410
419
|
if (policy === undefined) {
|
|
411
420
|
throw new PolicyError(`${table}: every table needs a policy in tables.ts`)
|
|
412
421
|
}
|
|
413
|
-
parsed[
|
|
422
|
+
parsed[parsed.length] = parseTable(table, entry, policy, vocabulary)
|
|
414
423
|
}
|
|
415
424
|
return linkTables(parsed, vocabulary.dimensions)
|
|
416
425
|
}
|
|
417
426
|
|
|
427
|
+
/** Whether a column list entry marks a view: its `view` is `true`, or absent for a table. */
|
|
428
|
+
function isViewEntry(table: string, entry: unknown): boolean {
|
|
429
|
+
const view = ownEntry(plainRecord(entry, `${table}: the column list entry`), 'view')
|
|
430
|
+
if (view !== undefined && view !== true) {
|
|
431
|
+
throw new PolicyError(`${table}: the column list entry's view is true or absent`)
|
|
432
|
+
}
|
|
433
|
+
return view === true
|
|
434
|
+
}
|
|
435
|
+
|
|
418
436
|
/** How a policy names its columns: one it states must exist, and so must one a convention derives for it. */
|
|
419
437
|
interface ColumnReader {
|
|
420
438
|
readonly column: (name: unknown, field: string) => string
|
|
@@ -468,6 +486,14 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
468
486
|
const scopeInput = plainRecord(ownEntry(policy, 'scope'), `${table}: scope`)
|
|
469
487
|
const foreignKeys = parseForeignKeys(table, ownEntry(entry, 'foreignKeys'), column)
|
|
470
488
|
const scope = parseScope(table, scopeInput, { column, columnsOf, derived }, vocabulary.dimensions)
|
|
489
|
+
const view = isViewEntry(table, entry)
|
|
490
|
+
if (view && scope.mode !== 'child' && scope.mode !== 'reference') {
|
|
491
|
+
throw new PolicyError(
|
|
492
|
+
`${table}: a view is read-only, so it takes a child scope, { child, key?, column?, inherit? }, or { reference }; ${
|
|
493
|
+
scope.mode === 'app' ? 'an application' : 'a dimension'
|
|
494
|
+
} table's rows are written`,
|
|
495
|
+
)
|
|
496
|
+
}
|
|
471
497
|
const action = (value: unknown, field: string): string => {
|
|
472
498
|
const name = nonEmpty(table, value, field)
|
|
473
499
|
if (!inSet(vocabulary.actions, name)) {
|
|
@@ -507,6 +533,9 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
507
533
|
restricted[restricted.length] = name
|
|
508
534
|
}
|
|
509
535
|
}
|
|
536
|
+
if (writeInput !== undefined && view) {
|
|
537
|
+
throw new PolicyError(viewWrite(table))
|
|
538
|
+
}
|
|
510
539
|
if (writeInput !== undefined) {
|
|
511
540
|
setOwn(columnWrites, name, columnWrite(table, name, action(writeInput, `columns.${name}.write`), actions, update))
|
|
512
541
|
}
|
|
@@ -520,15 +549,20 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
520
549
|
if (version !== undefined && hasOwn(columnPolicies, version)) {
|
|
521
550
|
throw new PolicyError(`${table}: the version ${version} takes no action of its own`)
|
|
522
551
|
}
|
|
523
|
-
const writable = scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app'
|
|
552
|
+
const writable = !view && (scope.mode === 'dimension' || scope.mode === 'child' || scope.mode === 'app')
|
|
524
553
|
const queueInput = ownEntry(policy, 'queue')
|
|
525
554
|
const filesInput = ownEntry(policy, 'files')
|
|
555
|
+
// On a view, an empty insert or update list is refused too: it states a write the view never takes.
|
|
556
|
+
if (view && (hasOwn(policy, 'insert') || hasOwn(policy, 'update'))) {
|
|
557
|
+
throw new PolicyError(viewWrite(table))
|
|
558
|
+
}
|
|
526
559
|
if (
|
|
527
560
|
!writable
|
|
528
561
|
&& (namesOf(insert).length > 0 || namesOf(update).length > 0 || version !== undefined || createdBy !== undefined
|
|
529
|
-
|| ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
|
|
562
|
+
|| ownKeys(columnWrites).length > 0 || queueInput !== undefined || filesInput !== undefined
|
|
563
|
+
|| actions.insert.length > 0 || actions.update.length > 0 || actions.delete.length > 0)
|
|
530
564
|
) {
|
|
531
|
-
throw new PolicyError(`${table}: a ${scope.mode} table is never written by a handler`)
|
|
565
|
+
throw new PolicyError(view ? viewWrite(table) : `${table}: a ${scope.mode} table is never written by a handler`)
|
|
532
566
|
}
|
|
533
567
|
const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
|
|
534
568
|
const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
|
|
@@ -564,6 +598,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
|
|
|
564
598
|
booleans,
|
|
565
599
|
json,
|
|
566
600
|
foreignKeys,
|
|
601
|
+
view,
|
|
567
602
|
}
|
|
568
603
|
}
|
|
569
604
|
|
|
@@ -860,6 +895,10 @@ function parseContainer(
|
|
|
860
895
|
return freeze({ dimension: container, column: columns.column(ownEntry(stated, 'column'), 'scope.in.column') })
|
|
861
896
|
}
|
|
862
897
|
|
|
898
|
+
function viewWrite(table: string): string {
|
|
899
|
+
return `${table}: a view is never written by a handler, so its policy takes only actions.read, appRead, appCount and column read actions`
|
|
900
|
+
}
|
|
901
|
+
|
|
863
902
|
function parseActions(
|
|
864
903
|
table: string,
|
|
865
904
|
scope: Readonly<Record<string, unknown>>,
|
|
@@ -985,6 +1024,13 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
|
|
|
985
1024
|
if (stamp === undefined) {
|
|
986
1025
|
continue
|
|
987
1026
|
}
|
|
1027
|
+
// Nothing writes a view, so its key may be its parent column; a predicate still compares each.
|
|
1028
|
+
if (table.view) {
|
|
1029
|
+
if (inSet(table.json, stamp.column)) {
|
|
1030
|
+
throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which no predicate compares as ${stamp.role}; give it a scalar type`)
|
|
1031
|
+
}
|
|
1032
|
+
continue
|
|
1033
|
+
}
|
|
988
1034
|
for (let other = 0; other < index; other++) {
|
|
989
1035
|
const earlier = stamps[other]
|
|
990
1036
|
if (earlier !== undefined && earlier.column === stamp.column) {
|
|
@@ -1153,8 +1199,11 @@ function resolveChain(
|
|
|
1153
1199
|
}
|
|
1154
1200
|
const dimension = parent.scope.dimension
|
|
1155
1201
|
const link = { dimension, column: scope.column ?? parentColumn(table, `${dimension}_id`, scope.parent) }
|
|
1156
|
-
|
|
1157
|
-
|
|
1202
|
+
// A view has no foreign key: its SQL alone states its containment, and the approver reviews it (ADR-0072).
|
|
1203
|
+
if (!table.view) {
|
|
1204
|
+
requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
|
|
1205
|
+
requireCoveringKey(table, link, parent, parentChain)
|
|
1206
|
+
}
|
|
1158
1207
|
return {
|
|
1159
1208
|
scope: freeze({ mode: 'child', parent: scope.parent, key: scope.key, column: link.column, inherit }),
|
|
1160
1209
|
chain: prepend(link, parentChain),
|
package/src/store.ts
CHANGED
|
@@ -926,6 +926,10 @@ export function childObjectPredicate(context: TableContext, parent: unknown, key
|
|
|
926
926
|
}
|
|
927
927
|
|
|
928
928
|
export function guard(context: TableContext, root: RootKind, scope: OperationNode | undefined): GuardContext {
|
|
929
|
+
// Every store write reaches its statement through here: a view's rows are its tables', never written (ADR-0072).
|
|
930
|
+
if (context.model.view && root !== 'SelectQueryNode') {
|
|
931
|
+
throw new QueryRefusedError('read_only', `${context.model.name} is a view, which no handler writes`)
|
|
932
|
+
}
|
|
929
933
|
return { root, table: context.model.name, joins: root === 'SelectQueryNode' ? context.joins : {}, scope }
|
|
930
934
|
}
|
|
931
935
|
|
package/src/tables.ts
CHANGED
|
@@ -85,6 +85,7 @@ export {
|
|
|
85
85
|
} from './policy'
|
|
86
86
|
export type {
|
|
87
87
|
ColumnTypes,
|
|
88
|
+
ColumnViews,
|
|
88
89
|
DefineVocabularyPolicies,
|
|
89
90
|
NormalizedPolicies,
|
|
90
91
|
TableVocabulary,
|
|
@@ -97,6 +98,7 @@ export type {
|
|
|
97
98
|
VocabularyDimensionScope,
|
|
98
99
|
VocabularyPolicyMap,
|
|
99
100
|
VocabularyTablePolicy,
|
|
101
|
+
VocabularyViewPolicy,
|
|
100
102
|
} from './vocabulary-tables'
|
|
101
103
|
|
|
102
104
|
/**
|
|
@@ -154,6 +156,7 @@ function artifactOf(model: TableModel): TablePolicyArtifact {
|
|
|
154
156
|
createdBy: model.createdBy ?? null,
|
|
155
157
|
columns,
|
|
156
158
|
...(ownKeys(model.files).length === 0 ? {} : { files: { ...model.files } }),
|
|
159
|
+
...(model.view ? { view: true } : {}),
|
|
157
160
|
}
|
|
158
161
|
}
|
|
159
162
|
|
package/src/testing-shared.ts
CHANGED
|
@@ -378,6 +378,9 @@ function scopedModel<DB, P>(tables: Tables<DB, P>, table: string): { readonly mo
|
|
|
378
378
|
if (model === undefined) {
|
|
379
379
|
throw new Error(`${table} is not a table of the policies`)
|
|
380
380
|
}
|
|
381
|
+
if (model.view) {
|
|
382
|
+
throw new Error(`${table} is a view, whose rows come from the tables it reads: seed those instead`)
|
|
383
|
+
}
|
|
381
384
|
return { models, model }
|
|
382
385
|
}
|
|
383
386
|
|
package/src/vocabulary-tables.ts
CHANGED
|
@@ -1,20 +1,40 @@
|
|
|
1
1
|
// The table policies of the vocabulary form, `defineTables(vocabulary, columns)`: how an application writes them, with
|
|
2
2
|
// containment taken from the vocabulary, and the normalized policies the kit and the handles read. Types only.
|
|
3
3
|
|
|
4
|
-
import type {
|
|
4
|
+
import type {
|
|
5
|
+
ColumnList,
|
|
6
|
+
ColumnPolicies,
|
|
7
|
+
FilePolicies,
|
|
8
|
+
RecordActions,
|
|
9
|
+
ReferencePolicy,
|
|
10
|
+
TableAction,
|
|
11
|
+
TableActions,
|
|
12
|
+
Tables,
|
|
13
|
+
VersionColumn,
|
|
14
|
+
} from './policy'
|
|
5
15
|
|
|
6
16
|
declare const databaseType: unique symbol
|
|
17
|
+
declare const viewNames: unique symbol
|
|
7
18
|
|
|
8
19
|
/**
|
|
9
|
-
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types
|
|
10
|
-
* `defineTables(vocabulary, columns)` takes no type argument. The
|
|
20
|
+
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types and the names of
|
|
21
|
+
* its views, so that `defineTables(vocabulary, columns)` takes no type argument. The brands are type-only: no value
|
|
22
|
+
* has either property.
|
|
11
23
|
*/
|
|
12
|
-
export type TypedColumnList<DB> = ColumnList<DB> & {
|
|
24
|
+
export type TypedColumnList<DB, Views extends keyof DB & string = never> = ColumnList<DB> & {
|
|
25
|
+
readonly [databaseType]?: DB
|
|
26
|
+
readonly [viewNames]?: { readonly views: Views }
|
|
27
|
+
}
|
|
13
28
|
|
|
14
29
|
/** The row types a typed column list carries; `never` for a list without them. */
|
|
15
30
|
export type ColumnTypes<C> = typeof databaseType extends keyof C ? C extends { readonly [databaseType]?: infer DB } ? Exclude<DB, undefined> : never
|
|
16
31
|
: never
|
|
17
32
|
|
|
33
|
+
/** The views a typed column list names; `never` for a list without views. */
|
|
34
|
+
export type ColumnViews<C> = typeof viewNames extends keyof C
|
|
35
|
+
? C extends { readonly [viewNames]?: { readonly views: infer Views extends string } } ? Views : never
|
|
36
|
+
: never
|
|
37
|
+
|
|
18
38
|
/**
|
|
19
39
|
* What `defineTables(vocabulary, columns)` reads of `@fabrika/app/contract`'s `defineVocabulary` result: the action
|
|
20
40
|
* and dimension names, and each dimension's container. `@fabrika/db` does not import `@fabrika/app`.
|
|
@@ -126,6 +146,43 @@ type AuthoredChildPolicy<Table extends string, Col extends string, A extends str
|
|
|
126
146
|
& {
|
|
127
147
|
readonly scope: ChildScopes<Table, Col, S, P>
|
|
128
148
|
}
|
|
149
|
+
/** What a view's policy holds besides its scope: read actions only, no write list and no stamped column. */
|
|
150
|
+
type ViewIsReadOnly = 'a view is never written: its actions are read, appRead and appCount'
|
|
151
|
+
|
|
152
|
+
/** The write actions a view's policy may not name, each typed as the message: a literal is not checked for excess keys. */
|
|
153
|
+
interface NoWriteActions {
|
|
154
|
+
readonly insert?: ViewIsReadOnly
|
|
155
|
+
readonly update?: ViewIsReadOnly
|
|
156
|
+
readonly delete?: ViewIsReadOnly
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
interface ReadOnlyFields<Col extends string, A extends string> {
|
|
160
|
+
readonly actions: { readonly read: TableAction<A>; readonly appRead?: readonly A[]; readonly appCount?: readonly A[] } & NoWriteActions
|
|
161
|
+
readonly insert?: never
|
|
162
|
+
readonly update?: never
|
|
163
|
+
readonly version?: never
|
|
164
|
+
readonly createdBy?: never
|
|
165
|
+
readonly queue?: never
|
|
166
|
+
readonly files?: never
|
|
167
|
+
readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). */
|
|
171
|
+
type AuthoredChildViewPolicy<Table extends string, Col extends string, A extends string, S, P> = ReadOnlyFields<Col, A> & {
|
|
172
|
+
readonly scope: ChildScopes<Table, Col, S, P>
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** A view's policy as written: a read-only child, or a reference table every site reads. */
|
|
176
|
+
export type VocabularyViewPolicy<Table extends string, Col extends string, A extends string, S = unknown, P = unknown> = S extends
|
|
177
|
+
{ readonly child: unknown } ? AuthoredChildViewPolicy<Table, Col, A, S, P>
|
|
178
|
+
: S extends { readonly reference: unknown } ? ReferenceViewPolicy<Col, A>
|
|
179
|
+
: AuthoredChildViewPolicy<Table, Col, A, S, P> | ReferenceViewPolicy<Col, A>
|
|
180
|
+
|
|
181
|
+
type ReferenceViewPolicy<Col extends string, A extends string> = ReferencePolicy<Col, A> & {
|
|
182
|
+
readonly actions: NoWriteActions
|
|
183
|
+
readonly columns?: { readonly [C in Col]?: { readonly read: A; readonly write?: never } }
|
|
184
|
+
}
|
|
185
|
+
|
|
129
186
|
/** An application table's scope: why its rows belong to no dimension; `key` defaults to `id`. */
|
|
130
187
|
type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, Ver> & {
|
|
131
188
|
readonly scope: { readonly app: string } & KeyField<Col>
|
|
@@ -157,15 +214,24 @@ type AnyTablePolicy<DB, V, T extends keyof DB & string> = VocabularyTablePolicy<
|
|
|
157
214
|
VersionColumn<DB[T]>
|
|
158
215
|
>
|
|
159
216
|
|
|
217
|
+
/** The policy of view `T` with nothing stated: both forms, any parent. */
|
|
218
|
+
type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>>
|
|
219
|
+
|
|
160
220
|
/**
|
|
161
|
-
* Every table of the schema, and no other, maps to a policy; a
|
|
162
|
-
* `P` is the policies as written, which picks each table's form by the scope it
|
|
163
|
-
* map's own annotation states nothing narrower, so it is checked against every
|
|
221
|
+
* Every table of the schema, and no other, maps to a policy; a view `Views` names may (ADR-0072). A misspelt action or
|
|
222
|
+
* dimension fails at its own line. `P` is the policies as written, which picks each table's form by the scope it
|
|
223
|
+
* states; a policy written under this map's own annotation states nothing narrower, so it is checked against every
|
|
224
|
+
* form.
|
|
164
225
|
*/
|
|
165
|
-
export type VocabularyPolicyMap<DB, V, P = unknown> =
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
226
|
+
export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> =
|
|
227
|
+
& {
|
|
228
|
+
readonly [T in Exclude<keyof DB & string, Views>]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T>
|
|
229
|
+
: VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>
|
|
230
|
+
}
|
|
231
|
+
& {
|
|
232
|
+
readonly [T in Views & keyof DB & string]?: AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T>
|
|
233
|
+
: VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>
|
|
234
|
+
}
|
|
169
235
|
|
|
170
236
|
type Flat<T> = { [K in keyof T]: T[K] }
|
|
171
237
|
|
|
@@ -192,15 +258,20 @@ type NormalScope<S, V, P> = S extends { readonly dimension: infer D extends stri
|
|
|
192
258
|
: S extends { readonly app: infer R extends string } ? { readonly app: R; readonly key: KeyOf<S> }
|
|
193
259
|
: S
|
|
194
260
|
|
|
261
|
+
/** A view's normalized policy says so, which the handle types read: no site writes it. */
|
|
262
|
+
type ViewMark<T, Views> = T extends Views ? { readonly view: true } : unknown
|
|
263
|
+
|
|
195
264
|
/**
|
|
196
265
|
* The policies as the layer models them: every dimension table's key and container, and every child's key and
|
|
197
|
-
* column, stated as the vocabulary and the conventions derive them.
|
|
266
|
+
* column, stated as the vocabulary and the conventions derive them; each view marked.
|
|
198
267
|
*/
|
|
199
|
-
export type NormalizedPolicies<P, V> = {
|
|
200
|
-
readonly [T in keyof P]: P[T] extends { readonly scope: infer S }
|
|
268
|
+
export type NormalizedPolicies<P, V, Views = never> = {
|
|
269
|
+
readonly [T in keyof P]: P[T] extends { readonly scope: infer S }
|
|
270
|
+
? Flat<Omit<P[T], 'scope' | 'view'> & { readonly scope: NormalScope<S, V, P> } & ViewMark<T, Views>>
|
|
271
|
+
: P[T]
|
|
201
272
|
}
|
|
202
273
|
|
|
203
|
-
/** Takes the policies of exactly the tables of the schema, written in the vocabulary form. */
|
|
204
|
-
export type DefineVocabularyPolicies<DB, V> = <const P extends VocabularyPolicyMap<DB, V, P>>(
|
|
274
|
+
/** Takes the policies of exactly the tables of the schema, and of any of its views, written in the vocabulary form. */
|
|
275
|
+
export type DefineVocabularyPolicies<DB, V, Views extends string = never> = <const P extends VocabularyPolicyMap<DB, V, P, Views>>(
|
|
205
276
|
policies: P & { readonly [K in Exclude<keyof P, keyof DB>]: never },
|
|
206
|
-
) => Tables<DB, NormalizedPolicies<P, V>>
|
|
277
|
+
) => Tables<DB, NormalizedPolicies<P, V, Views>>
|
package/types/src/codegen.d.ts
CHANGED
|
@@ -14,6 +14,7 @@ export declare class CodegenError extends Error {
|
|
|
14
14
|
}
|
|
15
15
|
declare const catalogColumnSchema: z.ZodObject<{
|
|
16
16
|
table_name: z.ZodString;
|
|
17
|
+
view: z.ZodBoolean;
|
|
17
18
|
column_name: z.ZodString;
|
|
18
19
|
type_name: z.ZodString;
|
|
19
20
|
type_type: z.ZodString;
|
|
@@ -61,20 +62,27 @@ export interface DescribedColumn {
|
|
|
61
62
|
/** The column list field that names the column: a day, a timestamp, a JSON column, or (on SQLite) a boolean. */
|
|
62
63
|
readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined;
|
|
63
64
|
}
|
|
64
|
-
/**
|
|
65
|
+
/**
|
|
66
|
+
* A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
|
|
67
|
+
* not read.
|
|
68
|
+
*/
|
|
65
69
|
export interface LeftOut {
|
|
66
|
-
/** The column's type, as its author wrote it. */
|
|
70
|
+
/** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
|
|
67
71
|
readonly leftOut: string;
|
|
72
|
+
readonly of: LeftOutKind;
|
|
68
73
|
}
|
|
74
|
+
/** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
|
|
75
|
+
export type LeftOutKind = 'generated' | 'view';
|
|
69
76
|
/** A column the module leaves out; only `ctx.sql` reaches it. */
|
|
70
77
|
export interface LeftOutColumn {
|
|
71
78
|
readonly table: string;
|
|
72
79
|
readonly column: string;
|
|
73
80
|
/** Its type, as its author wrote it. */
|
|
74
81
|
readonly type: string;
|
|
82
|
+
readonly of: LeftOutKind;
|
|
75
83
|
}
|
|
76
84
|
/** What codegen says of a left-out column: in the module, `name` is the column; in its output, `table.column`. */
|
|
77
|
-
export declare function leftOutText(name: string, type: string): string;
|
|
85
|
+
export declare function leftOutText(name: string, type: string, of: LeftOutKind): string;
|
|
78
86
|
/** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
|
|
79
87
|
export declare function leftOutRefusal(path: string, what: string): CodegenError;
|
|
80
88
|
/** The text of `SCHEMA_FILE`, and the columns it leaves out, for the command to name. */
|
|
@@ -94,20 +102,25 @@ export interface NamedColumn {
|
|
|
94
102
|
readonly table_name: string;
|
|
95
103
|
readonly column_name: string;
|
|
96
104
|
}
|
|
105
|
+
/** A column of a table or of a view, as `renderTables` reads it. */
|
|
106
|
+
export interface RelationColumn extends NamedColumn {
|
|
107
|
+
/** The relation is a view: read-only, with no key or foreign key. */
|
|
108
|
+
readonly view: boolean;
|
|
109
|
+
}
|
|
97
110
|
/**
|
|
98
|
-
* The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take,
|
|
99
|
-
* runtime column list with each table's foreign keys to application tables
|
|
100
|
-
* Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
111
|
+
* The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
|
|
112
|
+
* and the runtime column list with each table's foreign keys to application tables and each view marked; with the
|
|
113
|
+
* columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
|
|
101
114
|
*/
|
|
102
115
|
export declare function renderSchema(catalog: readonly CatalogColumn[], foreignKeys?: readonly CatalogForeignKey[]): GeneratedModule;
|
|
103
116
|
/**
|
|
104
117
|
* `renderSchema` over columns of any database: `describe` gives each column's types and list field, refuses a type the
|
|
105
|
-
* data layer does not read, or answers `LeftOut` for a generated column of such a type. That column
|
|
106
|
-
* module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
107
|
-
* key that names it, and a table it would leave without a column, are refused
|
|
108
|
-
* not rendered; keys keep the given order.
|
|
118
|
+
* data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
|
|
119
|
+
* is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
|
|
120
|
+
* reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
|
|
121
|
+
* without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
|
|
109
122
|
*/
|
|
110
|
-
export declare function renderTables<C extends
|
|
123
|
+
export declare function renderTables<C extends RelationColumn>(catalog: readonly C[], foreignKeys: readonly ForeignKeyColumns[], describe: (column: C) => DescribedColumn | LeftOut): GeneratedModule;
|
|
111
124
|
/** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
|
|
112
125
|
export declare function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule>;
|
|
113
126
|
export {};
|
package/types/src/index.d.ts
CHANGED
|
@@ -8,4 +8,4 @@ export type { AnyDbIndex, ChildRows, ContainedRows, CountOptions, DataKind, DbIn
|
|
|
8
8
|
export { type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type InsertValues, isTables, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type RowOf, type TableActions, type TableInsert, Tables, type TableUpdate, type UpdateValues, type VersionColumn, type VocabularyTables, } from './policy';
|
|
9
9
|
export { type AggregateRow, type AggregateSpec, type ChildListScope, type DataLayer, type DataLayerRuntime, scoped, type ScopedDatabase, } from './store';
|
|
10
10
|
export { type TablePolicies, tablePolicies } from './tables';
|
|
11
|
-
export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
|
|
11
|
+
export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
|
package/types/src/orm-types.d.ts
CHANGED
|
@@ -101,6 +101,8 @@ export interface IndexedTable {
|
|
|
101
101
|
readonly versioned: boolean;
|
|
102
102
|
/** A queue table: its rows are claimed and finished through `row.ref`. */
|
|
103
103
|
readonly queued: boolean;
|
|
104
|
+
/** A view: read like its scope's tables, written by no site (ADR-0072). */
|
|
105
|
+
readonly view: boolean;
|
|
104
106
|
}
|
|
105
107
|
type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> = {
|
|
106
108
|
readonly mode: ModeOf<P, T>;
|
|
@@ -131,6 +133,9 @@ type IndexedTableOf<DB, P, T extends keyof P & keyof DB & string, V = unknown> =
|
|
|
131
133
|
readonly queued: PolicyOf<P, T> extends {
|
|
132
134
|
readonly queue: object;
|
|
133
135
|
} ? true : false;
|
|
136
|
+
readonly view: PolicyOf<P, T> extends {
|
|
137
|
+
readonly view: true;
|
|
138
|
+
} ? true : false;
|
|
134
139
|
};
|
|
135
140
|
type OwnerTable<P, D> = {
|
|
136
141
|
[K in keyof P]: P[K] extends {
|
|
@@ -379,15 +384,15 @@ export interface UnownedTarget<D extends string> {
|
|
|
379
384
|
readonly update: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>;
|
|
380
385
|
readonly remove: Unavailable<`no table owns the dimension ${D}, so ctx.db.target has no row of its own`>;
|
|
381
386
|
}
|
|
382
|
-
/** A child table of the target: its rows are addressed by their own key under the target. */
|
|
387
|
+
/** A child table of the target: its rows are addressed by their own key under the target; a view's are only read. */
|
|
383
388
|
export interface ChildRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
|
|
384
389
|
readonly list: Read<T, E, A, (options?: ListOptions<RowFor<E, A>>) => Promise<ListPage<RowFor<E, A>>>>;
|
|
385
390
|
readonly get: Read<T, E, A, (key: string) => Promise<RowFor<E, A>>>;
|
|
386
|
-
readonly insert: Write<T, E, 'insert', A, K, InsertMethod<E>>;
|
|
387
|
-
readonly update: Update<T, E, A, K, (key: string, values: {
|
|
391
|
+
readonly insert: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Write<T, E, 'insert', A, K, InsertMethod<E>>;
|
|
392
|
+
readonly update: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Update<T, E, A, K, (key: string, values: {
|
|
388
393
|
[C in keyof UpdateValuesOf<E, A>]: UpdateValuesOf<E, A>[C];
|
|
389
394
|
}, ...version: VersionArguments<E>) => Promise<Saved<E>>>;
|
|
390
|
-
readonly remove: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>;
|
|
395
|
+
readonly remove: E['view'] extends true ? Unavailable<`${T} is a view, which no site writes: write the tables it reads`> : Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>;
|
|
391
396
|
}
|
|
392
397
|
/** A dimension table the target contains: listed in it, and inserted into it by a mutation of its insert action. */
|
|
393
398
|
export interface ContainedRows<T extends string, E extends IndexedTable, A extends string, K extends DataKind> {
|
|
@@ -543,16 +548,16 @@ export type UnscopedDeclaration<Table extends string, Mode extends UnscopedMode>
|
|
|
543
548
|
readonly [T in Table]?: Mode;
|
|
544
549
|
};
|
|
545
550
|
/**
|
|
546
|
-
* The tables of `U` whose mode may be `'write'` that no site writes: a reference table. A union or optional
|
|
547
|
-
* admits `'write'` counts, because the declaration it types may hold it.
|
|
551
|
+
* The tables of `U` whose mode may be `'write'` that no site writes: a reference table or a view. A union or optional
|
|
552
|
+
* mode that admits `'write'` counts, because the declaration it types may hold it.
|
|
548
553
|
*/
|
|
549
554
|
type ReadOnlyWritten<Ix extends AnyDbIndex, U> = {
|
|
550
|
-
[T in keyof U & TableName<Ix>]: 'write' extends U[T] ? Ix['tables'][T]['mode'] extends 'reference' ? T : never : never;
|
|
555
|
+
[T in keyof U & TableName<Ix>]: 'write' extends U[T] ? Ix['tables'][T]['mode'] extends 'reference' ? T : Ix['tables'][T]['view'] extends true ? T : never : never;
|
|
551
556
|
}[keyof U & TableName<Ix>];
|
|
552
|
-
type ReadOnlyMessage<T extends string> = `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`;
|
|
557
|
+
type ReadOnlyMessage<T extends string, E extends IndexedTable> = E['view'] extends true ? `${T} is a view, which no site writes: its rows come from the tables it reads, so declare unscoped: { ${T}: 'read' }` : `${T} is a reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`;
|
|
553
558
|
/** An `unscoped` declaration's `'write'` of a reference table, refused at its own line. */
|
|
554
559
|
export type ReadOnlyUnscoped<Ix extends AnyDbIndex, U> = [ReadOnlyWritten<Ix, U>] extends [never] ? unknown : {
|
|
555
|
-
readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T>>;
|
|
560
|
+
readonly [T in ReadOnlyWritten<Ix, U>]: Unavailable<ReadOnlyMessage<T, Ix['tables'][T]>>;
|
|
556
561
|
};
|
|
557
562
|
type KeylessMessage<T extends string> = `${T} is a reference table, which has no key: read it with list`;
|
|
558
563
|
/** A table a site declared `unscoped`: its scope predicate is `true`, and `'read'` writes nothing. */
|
package/types/src/orm.d.ts
CHANGED
|
@@ -80,3 +80,8 @@ export interface DataLayerParts {
|
|
|
80
80
|
fenced<T>(runtime: DataLayerRuntime, work: (session: Session) => Promise<T>): Promise<T>;
|
|
81
81
|
}
|
|
82
82
|
export declare function dataAccess(parts: DataLayerParts): DataAccess;
|
|
83
|
+
/**
|
|
84
|
+
* When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
|
|
85
|
+
* at the next due row it would take but no sooner than a second after it, or never when it would take none.
|
|
86
|
+
*/
|
|
87
|
+
export declare function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null;
|
package/types/src/policy.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { Insertable, Selectable, SelectType, Updateable } from 'kysely';
|
|
|
2
2
|
import { type NameSet } from './builtins';
|
|
3
3
|
import type { Unavailable } from './orm-types';
|
|
4
4
|
export type { RowOf } from './orm-types';
|
|
5
|
-
import type { ColumnTypes, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables';
|
|
5
|
+
import type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, TableVocabulary } from './vocabulary-tables';
|
|
6
6
|
export interface DimensionScope<Col extends string> {
|
|
7
7
|
readonly dimension: string;
|
|
8
8
|
readonly key: Col;
|
|
@@ -136,6 +136,8 @@ export interface TableColumns<Col extends string = string, Table extends string
|
|
|
136
136
|
readonly booleans?: readonly Col[];
|
|
137
137
|
/** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
|
|
138
138
|
readonly json?: readonly Col[];
|
|
139
|
+
/** A view: read-only, with no foreign key; absent for a table. */
|
|
140
|
+
readonly view?: true;
|
|
139
141
|
}
|
|
140
142
|
/** The columns and foreign keys of every table, generated next to the schema types. */
|
|
141
143
|
export type ColumnList<DB> = {
|
|
@@ -212,6 +214,8 @@ export interface TableModel {
|
|
|
212
214
|
readonly json: NameSet;
|
|
213
215
|
/** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
|
|
214
216
|
readonly foreignKeys: readonly ForeignKey[];
|
|
217
|
+
/** A view: a child or reference table no operation but a read reaches, whose containment only its SQL states. */
|
|
218
|
+
readonly view: boolean;
|
|
215
219
|
/**
|
|
216
220
|
* The containment links this table carries a column for, nearest first: a dimension table's container and
|
|
217
221
|
* the container's own chain; a child's parent and the parent's chain. Every predicate of a Ref covers all.
|
|
@@ -238,7 +242,7 @@ export declare function modelOf(models: TableModels, table: string): TableModel
|
|
|
238
242
|
*/
|
|
239
243
|
export declare function defineTables<const V extends TableVocabulary, C extends object>(vocabulary: V, columns: C): VocabularyTables<V, C>;
|
|
240
244
|
/** `defineTables(vocabulary, columns)` answers the policies' builder, or names the fix for an untyped column list. */
|
|
241
|
-
export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never] ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'> : DefineVocabularyPolicies<ColumnTypes<C>, V
|
|
245
|
+
export type VocabularyTables<V, C> = [ColumnTypes<C>] extends [never] ? Unavailable<'the column list carries no row types: import columns from the generated src/db/schema.generated.ts (fabrika db codegen)'> : DefineVocabularyPolicies<ColumnTypes<C>, V, ColumnViews<C>>;
|
|
242
246
|
/**
|
|
243
247
|
* The same policies read from values nobody type-checked: `src/db/tables.ts` and its vocabulary as the static reader
|
|
244
248
|
* has them from a commit. Every shape `defineTables` refuses at runtime is refused here, through the same parse.
|
package/types/src/tables.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export { PolicyError } from './errors';
|
|
|
7
7
|
export type { FileReference } from './file-references';
|
|
8
8
|
export type { AnyDbIndex, ApplicationRows, ApplicationTables, AppRecordRows, ChildRows, ClaimedRow, ClaimedRowHandle, ClaimOptions, ContainedRows, CountOptions, DataKind, DbIndex, FragmentTable, IndexedTable, InsertConflict, InsertMethod, ListOptions, ListPage, NoUnscoped, OrderTerm, OwnerRow, PublicApplicationRows, PublicApplicationTables, PublicInsertMethod, ReadOnlyUnscoped, ReferenceRows, ReferenceTables, RowFor, RowOf, Saved, ScopedApplicationRows, ScopedApplicationTables, ScopeTarget, TableNameOf, TargetForm, TargetRow, Unavailable, UnownedTarget, UnscopedDeclaration, UnscopedInsert, UnscopedMode, UnscopedRows, UnscopedTables, VersionArguments, WithinRows, WithinTables, } from './orm-types';
|
|
9
9
|
export { type ApplicationPolicy, type ApplicationScope, type ChildPolicy, type ChildScope, type ColumnList, defineTables, type DimensionPolicy, type DimensionScope, type FilePolicies, isTables, type QueuePolicy, readTables, type RecordActions, type ReferencePolicy, type ReferenceScope, type TableAction, type TableActions, type TableInsert, Tables, type TableUpdate, type VersionColumn, type VocabularyTables, } from './policy';
|
|
10
|
-
export type { ColumnTypes, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, } from './vocabulary-tables';
|
|
10
|
+
export type { ColumnTypes, ColumnViews, DefineVocabularyPolicies, NormalizedPolicies, TableVocabulary, TypedColumnList, VocabularyAction, VocabularyChildScope, VocabularyContainer, VocabularyContainerOf, VocabularyDimension, VocabularyDimensionScope, VocabularyPolicyMap, VocabularyTablePolicy, VocabularyViewPolicy, } from './vocabulary-tables';
|
|
11
11
|
/**
|
|
12
12
|
* The plan of seeding one row of each application table `rows` names (table → column → value), as an endpoint access
|
|
13
13
|
* case seeds its `appRows`: the order, the foreign keys that link one given row to another, and every refusal.
|
|
@@ -1,16 +1,27 @@
|
|
|
1
|
-
import type { ColumnList, ColumnPolicies, FilePolicies, RecordActions, ReferencePolicy, TableActions, Tables, VersionColumn } from './policy';
|
|
1
|
+
import type { ColumnList, ColumnPolicies, FilePolicies, RecordActions, ReferencePolicy, TableAction, TableActions, Tables, VersionColumn } from './policy';
|
|
2
2
|
declare const databaseType: unique symbol;
|
|
3
|
+
declare const viewNames: unique symbol;
|
|
3
4
|
/**
|
|
4
|
-
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types
|
|
5
|
-
* `defineTables(vocabulary, columns)` takes no type argument. The
|
|
5
|
+
* The generated column list (`src/db/schema.generated.ts`), which also carries the schema's row types and the names of
|
|
6
|
+
* its views, so that `defineTables(vocabulary, columns)` takes no type argument. The brands are type-only: no value
|
|
7
|
+
* has either property.
|
|
6
8
|
*/
|
|
7
|
-
export type TypedColumnList<DB> = ColumnList<DB> & {
|
|
9
|
+
export type TypedColumnList<DB, Views extends keyof DB & string = never> = ColumnList<DB> & {
|
|
8
10
|
readonly [databaseType]?: DB;
|
|
11
|
+
readonly [viewNames]?: {
|
|
12
|
+
readonly views: Views;
|
|
13
|
+
};
|
|
9
14
|
};
|
|
10
15
|
/** The row types a typed column list carries; `never` for a list without them. */
|
|
11
16
|
export type ColumnTypes<C> = typeof databaseType extends keyof C ? C extends {
|
|
12
17
|
readonly [databaseType]?: infer DB;
|
|
13
18
|
} ? Exclude<DB, undefined> : never : never;
|
|
19
|
+
/** The views a typed column list names; `never` for a list without views. */
|
|
20
|
+
export type ColumnViews<C> = typeof viewNames extends keyof C ? C extends {
|
|
21
|
+
readonly [viewNames]?: {
|
|
22
|
+
readonly views: infer Views extends string;
|
|
23
|
+
};
|
|
24
|
+
} ? Views : never : never;
|
|
14
25
|
/**
|
|
15
26
|
* What `defineTables(vocabulary, columns)` reads of `@fabrika/app/contract`'s `defineVocabulary` result: the action
|
|
16
27
|
* and dimension names, and each dimension's container. `@fabrika/db` does not import `@fabrika/app`.
|
|
@@ -134,6 +145,52 @@ type AuthoredDimensionPolicy<Col extends string, A extends string, V, Ver extend
|
|
|
134
145
|
type AuthoredChildPolicy<Table extends string, Col extends string, A extends string, Ver extends Col, S, P> = WritableFields<Col, A, Ver, RecordActions<A>> & {
|
|
135
146
|
readonly scope: ChildScopes<Table, Col, S, P>;
|
|
136
147
|
};
|
|
148
|
+
/** What a view's policy holds besides its scope: read actions only, no write list and no stamped column. */
|
|
149
|
+
type ViewIsReadOnly = 'a view is never written: its actions are read, appRead and appCount';
|
|
150
|
+
/** The write actions a view's policy may not name, each typed as the message: a literal is not checked for excess keys. */
|
|
151
|
+
interface NoWriteActions {
|
|
152
|
+
readonly insert?: ViewIsReadOnly;
|
|
153
|
+
readonly update?: ViewIsReadOnly;
|
|
154
|
+
readonly delete?: ViewIsReadOnly;
|
|
155
|
+
}
|
|
156
|
+
interface ReadOnlyFields<Col extends string, A extends string> {
|
|
157
|
+
readonly actions: {
|
|
158
|
+
readonly read: TableAction<A>;
|
|
159
|
+
readonly appRead?: readonly A[];
|
|
160
|
+
readonly appCount?: readonly A[];
|
|
161
|
+
} & NoWriteActions;
|
|
162
|
+
readonly insert?: never;
|
|
163
|
+
readonly update?: never;
|
|
164
|
+
readonly version?: never;
|
|
165
|
+
readonly createdBy?: never;
|
|
166
|
+
readonly queue?: never;
|
|
167
|
+
readonly files?: never;
|
|
168
|
+
readonly columns?: {
|
|
169
|
+
readonly [C in Col]?: {
|
|
170
|
+
readonly read: A;
|
|
171
|
+
readonly write?: never;
|
|
172
|
+
};
|
|
173
|
+
};
|
|
174
|
+
}
|
|
175
|
+
/** A view read as a child table: its parent's `Ref` and `Within` read it; nothing writes it (ADR-0072). */
|
|
176
|
+
type AuthoredChildViewPolicy<Table extends string, Col extends string, A extends string, S, P> = ReadOnlyFields<Col, A> & {
|
|
177
|
+
readonly scope: ChildScopes<Table, Col, S, P>;
|
|
178
|
+
};
|
|
179
|
+
/** A view's policy as written: a read-only child, or a reference table every site reads. */
|
|
180
|
+
export type VocabularyViewPolicy<Table extends string, Col extends string, A extends string, S = unknown, P = unknown> = S extends {
|
|
181
|
+
readonly child: unknown;
|
|
182
|
+
} ? AuthoredChildViewPolicy<Table, Col, A, S, P> : S extends {
|
|
183
|
+
readonly reference: unknown;
|
|
184
|
+
} ? ReferenceViewPolicy<Col, A> : AuthoredChildViewPolicy<Table, Col, A, S, P> | ReferenceViewPolicy<Col, A>;
|
|
185
|
+
type ReferenceViewPolicy<Col extends string, A extends string> = ReferencePolicy<Col, A> & {
|
|
186
|
+
readonly actions: NoWriteActions;
|
|
187
|
+
readonly columns?: {
|
|
188
|
+
readonly [C in Col]?: {
|
|
189
|
+
readonly read: A;
|
|
190
|
+
readonly write?: never;
|
|
191
|
+
};
|
|
192
|
+
};
|
|
193
|
+
};
|
|
137
194
|
/** An application table's scope: why its rows belong to no dimension; `key` defaults to `id`. */
|
|
138
195
|
type AuthoredApplicationPolicy<Col extends string, A extends string, Ver extends Col> = WritableFields<Col, A, Ver> & {
|
|
139
196
|
readonly scope: {
|
|
@@ -158,13 +215,18 @@ type StatedScope<P, T> = T extends keyof P ? P[T] extends {
|
|
|
158
215
|
} ? S : unknown : unknown;
|
|
159
216
|
/** The policy of table `T` with nothing stated: every form, every dimension's scope, any parent. */
|
|
160
217
|
type AnyTablePolicy<DB, V, T extends keyof DB & string> = VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>>;
|
|
218
|
+
/** The policy of view `T` with nothing stated: both forms, any parent. */
|
|
219
|
+
type AnyViewPolicy<DB, V, T extends keyof DB & string> = VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>>;
|
|
161
220
|
/**
|
|
162
|
-
* Every table of the schema, and no other, maps to a policy; a
|
|
163
|
-
* `P` is the policies as written, which picks each table's form by the scope it
|
|
164
|
-
* map's own annotation states nothing narrower, so it is checked against every
|
|
221
|
+
* Every table of the schema, and no other, maps to a policy; a view `Views` names may (ADR-0072). A misspelt action or
|
|
222
|
+
* dimension fails at its own line. `P` is the policies as written, which picks each table's form by the scope it
|
|
223
|
+
* states; a policy written under this map's own annotation states nothing narrower, so it is checked against every
|
|
224
|
+
* form.
|
|
165
225
|
*/
|
|
166
|
-
export type VocabularyPolicyMap<DB, V, P = unknown> = {
|
|
167
|
-
readonly [T in keyof DB & string]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>;
|
|
226
|
+
export type VocabularyPolicyMap<DB, V, P = unknown, Views extends string = never> = {
|
|
227
|
+
readonly [T in Exclude<keyof DB & string, Views>]: AnyTablePolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyTablePolicy<DB, V, T> : VocabularyTablePolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, V, VersionColumn<DB[T]>, StatedScope<P, T>, P>;
|
|
228
|
+
} & {
|
|
229
|
+
readonly [T in Views & keyof DB & string]?: AnyViewPolicy<DB, V, T> extends (T extends keyof P ? P[T] : unknown) ? AnyViewPolicy<DB, V, T> : VocabularyViewPolicy<keyof DB & string, keyof DB[T] & string, VocabularyAction<V>, StatedScope<P, T>, P>;
|
|
168
230
|
};
|
|
169
231
|
type Flat<T> = {
|
|
170
232
|
[K in keyof T]: T[K];
|
|
@@ -207,19 +269,23 @@ type NormalScope<S, V, P> = S extends {
|
|
|
207
269
|
readonly app: R;
|
|
208
270
|
readonly key: KeyOf<S>;
|
|
209
271
|
} : S;
|
|
272
|
+
/** A view's normalized policy says so, which the handle types read: no site writes it. */
|
|
273
|
+
type ViewMark<T, Views> = T extends Views ? {
|
|
274
|
+
readonly view: true;
|
|
275
|
+
} : unknown;
|
|
210
276
|
/**
|
|
211
277
|
* The policies as the layer models them: every dimension table's key and container, and every child's key and
|
|
212
|
-
* column, stated as the vocabulary and the conventions derive them.
|
|
278
|
+
* column, stated as the vocabulary and the conventions derive them; each view marked.
|
|
213
279
|
*/
|
|
214
|
-
export type NormalizedPolicies<P, V> = {
|
|
280
|
+
export type NormalizedPolicies<P, V, Views = never> = {
|
|
215
281
|
readonly [T in keyof P]: P[T] extends {
|
|
216
282
|
readonly scope: infer S;
|
|
217
|
-
} ? Flat<Omit<P[T], 'scope'> & {
|
|
283
|
+
} ? Flat<Omit<P[T], 'scope' | 'view'> & {
|
|
218
284
|
readonly scope: NormalScope<S, V, P>;
|
|
219
|
-
}
|
|
285
|
+
} & ViewMark<T, Views>> : P[T];
|
|
220
286
|
};
|
|
221
|
-
/** Takes the policies of exactly the tables of the schema, written in the vocabulary form. */
|
|
222
|
-
export type DefineVocabularyPolicies<DB, V> = <const P extends VocabularyPolicyMap<DB, V, P>>(policies: P & {
|
|
287
|
+
/** Takes the policies of exactly the tables of the schema, and of any of its views, written in the vocabulary form. */
|
|
288
|
+
export type DefineVocabularyPolicies<DB, V, Views extends string = never> = <const P extends VocabularyPolicyMap<DB, V, P, Views>>(policies: P & {
|
|
223
289
|
readonly [K in Exclude<keyof P, keyof DB>]: never;
|
|
224
|
-
}) => Tables<DB, NormalizedPolicies<P, V>>;
|
|
290
|
+
}) => Tables<DB, NormalizedPolicies<P, V, Views>>;
|
|
225
291
|
export {};
|