@fabrika/db 0.9.0-dev.10 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.10",
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": "tsc --noEmit",
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.10",
96
- "@fabrika/platform": "0.9.0-dev.10",
97
- "@fabrika/platform-node": "0.9.0-dev.10",
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"
@@ -13,7 +13,7 @@ import {
13
13
  JSON_COLUMN,
14
14
  type LeftOut,
15
15
  leftOutRefusal,
16
- type NamedColumn,
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 NamedColumn {
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 their foreign keys in declaration order. */
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 in the schema, in table then column order. */
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`; the suffix keeps every name clear of `DB` and the imported type names. A
186
- * name that would not start with a letter (`_123`) gets a `T` prefix, so it stays a TypeScript identifier.
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
- /** A column `describe` leaves out of the module: a generated column of a type the data layer does not read. */
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 column is refused.
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, and the
321
- * runtime column list with each table's foreign keys to application tables; with the columns it leaves out.
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 is left out of the
331
- * module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql` reaches it; a foreign
332
- * key that names it, and a table it would leave without a column, are refused. A foreign key's `constraint_name` is
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 NamedColumn>(
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 = names.map((table) => `\t${table}: ${interfaceName(table)}\n`).join('')
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 = names
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
- `export const columns: TypedColumnList<DB> = {\n${columns}}\n`,
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: Write<T, E, 'insert', A, K, InsertMethod<E>>
394
- readonly update: Update<
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: Write<T, E, 'delete', A, K, (key: string, ...version: VersionArguments<E>) => Promise<void>>
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 mode that
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] ? Ix['tables'][T]['mode'] extends 'reference' ? T : never : never
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 reference table, which no site writes: its rows come from a migration, so declare unscoped: { ${T}: 'read' }`
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
- // A full claim left rows behind: due at once.
831
- let rearm: Date | null = new Date(now.getTime() + 1)
832
- if (rows.length < limit) {
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
- rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
851
+ next = row === undefined ? null : dueOf(row, table, queue.due)
841
852
  }
842
- await rearmClaim(runtime, session, fence, rearm)
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[index] = parseTable(table, ownEntry(columns, table), policy, vocabulary)
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
- requireReference(table, link, parent, (column) => `scope.column: '${column}'`)
1157
- requireCoveringKey(table, link, parent, parentChain)
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