@fabrika/db 0.9.0-dev.5 → 0.9.0-dev.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/package.json +9 -5
  2. package/src/authority.ts +560 -0
  3. package/src/builtins.ts +21 -0
  4. package/src/capability.ts +51 -2
  5. package/src/codegen-sqlite.ts +62 -22
  6. package/src/codegen.ts +181 -42
  7. package/src/condition-nodes.ts +119 -0
  8. package/src/conditions.ts +683 -0
  9. package/src/description.ts +37 -8
  10. package/src/errors.ts +8 -4
  11. package/src/file-columns.ts +52 -10
  12. package/src/framework.ts +5 -2
  13. package/src/guard.ts +365 -15
  14. package/src/index.ts +8 -0
  15. package/src/job-leases.ts +19 -2
  16. package/src/job-wakes.ts +183 -33
  17. package/src/json.ts +124 -0
  18. package/src/list-cursor.ts +82 -0
  19. package/src/migrations-sqlite.ts +93 -0
  20. package/src/migrations.ts +99 -0
  21. package/src/nodes.ts +21 -6
  22. package/src/notifications.ts +152 -0
  23. package/src/orm-types.ts +208 -74
  24. package/src/orm.ts +368 -146
  25. package/src/policy.ts +1973 -141
  26. package/src/push-subscriptions.ts +287 -0
  27. package/src/registry.ts +50 -1
  28. package/src/request-receipts.ts +107 -0
  29. package/src/sql.ts +39 -11
  30. package/src/sqlite-bun.ts +41 -14
  31. package/src/sqlite-migrate.ts +102 -1
  32. package/src/sqlite.ts +46 -1
  33. package/src/store.ts +1930 -167
  34. package/src/tables.ts +156 -6
  35. package/src/temporal.ts +8 -1
  36. package/src/testing-shared.ts +758 -140
  37. package/src/testing-sqlite.ts +212 -40
  38. package/src/testing.ts +151 -22
  39. package/src/vocabulary-tables.ts +159 -27
  40. package/types/src/authority.d.ts +147 -0
  41. package/types/src/builtins.d.ts +2 -0
  42. package/types/src/capability.d.ts +50 -2
  43. package/types/src/codegen-sqlite.d.ts +8 -1
  44. package/types/src/codegen.d.ts +54 -10
  45. package/types/src/condition-nodes.d.ts +9 -0
  46. package/types/src/conditions.d.ts +151 -0
  47. package/types/src/description.d.ts +26 -8
  48. package/types/src/errors.d.ts +7 -4
  49. package/types/src/file-columns.d.ts +6 -4
  50. package/types/src/framework.d.ts +5 -2
  51. package/types/src/guard.d.ts +24 -0
  52. package/types/src/index.d.ts +4 -3
  53. package/types/src/job-leases.d.ts +8 -1
  54. package/types/src/job-wakes.d.ts +28 -5
  55. package/types/src/json.d.ts +18 -0
  56. package/types/src/list-cursor.d.ts +13 -0
  57. package/types/src/migrations.d.ts +5 -0
  58. package/types/src/nodes.d.ts +4 -0
  59. package/types/src/notifications.d.ts +37 -0
  60. package/types/src/orm-types.d.ts +165 -73
  61. package/types/src/orm.d.ts +21 -0
  62. package/types/src/policy.d.ts +347 -23
  63. package/types/src/push-subscriptions.d.ts +49 -0
  64. package/types/src/registry.d.ts +36 -1
  65. package/types/src/request-receipts.d.ts +22 -0
  66. package/types/src/sql.d.ts +2 -2
  67. package/types/src/sqlite-bun.d.ts +11 -3
  68. package/types/src/sqlite-migrate.d.ts +32 -0
  69. package/types/src/store.d.ts +118 -31
  70. package/types/src/tables.d.ts +8 -2
  71. package/types/src/temporal.d.ts +4 -1
  72. package/types/src/testing-shared.d.ts +112 -23
  73. package/types/src/testing-sqlite.d.ts +17 -2
  74. package/types/src/testing.d.ts +1 -1
  75. package/types/src/vocabulary-tables.d.ts +169 -22
package/src/capability.ts CHANGED
@@ -36,6 +36,33 @@ export interface RefGrant {
36
36
  readonly id: string
37
37
  /** The values of the containers this object lies in, by dimension (`workspace → w1` for a note). */
38
38
  readonly chain: ReadonlyMap<string, string>
39
+ /**
40
+ * The relations the caller holds the action through on this object or a container, when no grant holds it: every
41
+ * statement of the Ref then also requires a row of one of them. Empty for a Ref an IAM grant holds.
42
+ */
43
+ readonly relations: readonly RelationHold[]
44
+ /**
45
+ * The caller's grants of the action at nodes whose rows reveal the object, or a container on its chain, to their
46
+ * members (`memberReveals`), when no grant holds it: every statement of the Ref then also requires such a row, as
47
+ * for `relations`. Empty for a Ref an IAM grant holds.
48
+ */
49
+ readonly revealing: readonly ContainerGrant[]
50
+ /**
51
+ * The caller's grants of the action at nodes of a dimension the object's table reads through a path that holds the
52
+ * action (`writeThrough`), or at containers of such a node, when no grant holds it on the chain: every statement then
53
+ * also requires the row to reach one of them through such a path. Empty for a Ref an IAM grant holds.
54
+ */
55
+ readonly paths: readonly ContainerGrant[]
56
+ }
57
+
58
+ /**
59
+ * A relation the caller holds the action through: anywhere (`inside: null`, a `~rel` entry), or only on rows that lie
60
+ * inside one of `inside`'s values (`~relin` entries of grants at those values): a row whose column for that dimension,
61
+ * its key at its own dimension, names one of them. A row with no such column is not inside, so the hold reaches none.
62
+ */
63
+ export interface RelationHold {
64
+ readonly relation: string
65
+ readonly inside: ContainerGrant | null
39
66
  }
40
67
 
41
68
  /** The values of one container dimension in which the caller holds the action: `organization → [o1]`. */
@@ -67,13 +94,29 @@ export interface WithinGrant {
67
94
  * the action: a row that lies in one of their values is listed, as a single-object read of it is allowed.
68
95
  */
69
96
  readonly contained: readonly ContainerGrant[]
97
+ /**
98
+ * The relations through which the caller also holds the action (`~rel` and `~relin` entries of its token): a row lies
99
+ * in the `Within` too where a row of one of them names the caller at the row's node, read by the statement itself.
100
+ */
101
+ readonly relations: readonly RelationHold[]
102
+ /**
103
+ * The caller's grants of the action at nodes whose rows reveal the `Within`'s dimension or a container of it to their
104
+ * members (`memberReveals`): a row under a node such a row reveals is read too, the statement judging the revealing row.
105
+ */
106
+ readonly revealing: readonly ContainerGrant[]
70
107
  }
71
108
 
72
- /** An `app` endpoint's grant: the action everywhere in the application, which the proxy checked was held globally. */
109
+ /**
110
+ * An `app` endpoint's grant: the actions held everywhere in the application, which the proxy checked were held globally.
111
+ * One action for `access: { action, app: true }`; for `anyOf`, every listed action the caller holds, which act as the
112
+ * actions of one role: an operation, a column or a `when` admits the grant when one of them admits it.
113
+ */
73
114
  export interface AppGrant {
74
115
  readonly kind: 'app'
75
- readonly action: string
116
+ readonly actions: readonly [string, ...string[]]
76
117
  readonly principal: string
118
+ /** A public procedure's workload: it reaches only the tables that name its action, never one read with `'any'`. */
119
+ readonly public: boolean
77
120
  }
78
121
 
79
122
  /** A row a claim leased: the table, its key, and the containment it had then, column by column. */
@@ -122,4 +165,10 @@ export interface CapabilityAuthority {
122
165
  * request. Every mutation checks it inside its own transaction.
123
166
  */
124
167
  fence(): LeaseFence | null
168
+ /**
169
+ * What the caller of the work running now holds of `action` in `dimension`, as a `Within` of it would carry it, with
170
+ * no values when it holds none; `undefined` when the work has no caller (a job attempt, a webhook delivery). An
171
+ * insert that hands out access through a path judges its writer by it; an authority without the method has no caller.
172
+ */
173
+ standing?(dimension: string, action: string): WithinGrant | undefined
125
174
  }
@@ -4,7 +4,20 @@
4
4
 
5
5
  import { Database } from 'bun:sqlite'
6
6
  import { z } from 'zod/v4'
7
- import { CodegenError, type DescribedColumn, type ForeignKeyColumns, type NamedColumn, renderTables, type ScalarType } from './codegen'
7
+ import {
8
+ CodegenError,
9
+ columnPath,
10
+ type DescribedColumn,
11
+ type ForeignKeyColumns,
12
+ type GeneratedModule,
13
+ JSON_COLUMN,
14
+ type LeftOut,
15
+ leftOutRefusal,
16
+ type RelationColumn,
17
+ renderTables,
18
+ type ScalarType,
19
+ } from './codegen'
20
+ import { execStatements } from './sqlite-bun'
8
21
  import { migrateSqlite, type SqliteMigrationBundle, type SqliteMigrationTarget } from './sqlite-migrate'
9
22
 
10
23
  const STRING: ScalarType = { select: 'string' }
@@ -29,12 +42,17 @@ const DECLARED_TYPES: ReadonlyMap<string, { readonly scalar: ScalarType; readonl
29
42
  ['DATETIME', { scalar: { select: 'Date', write: 'Date | string' }, list: 'timestamps' }],
30
43
  ['DATE', { scalar: STRING, list: 'dates' }],
31
44
  ['BLOB', { scalar: { select: 'Uint8Array' }, list: undefined }],
45
+ // JSON text; the name has NUMERIC affinity, so a JSON number is stored as a number (`sqliteJson`).
46
+ ['JSONB', { scalar: JSON_COLUMN, list: 'json' }],
32
47
  ])
33
48
 
34
- interface SqliteColumn extends NamedColumn {
49
+ interface SqliteColumn extends RelationColumn {
35
50
  readonly declared: string
36
51
  readonly nullable: boolean
52
+ /** `always` is a column `GENERATED ALWAYS AS (…)` computes (`hidden` 2 or 3): SQLite has no identity column. */
37
53
  readonly generated: DescribedColumn['generated']
54
+ /** The column is in the primary key or in a unique index. */
55
+ readonly keyed: boolean
38
56
  }
39
57
 
40
58
  const tableSchema = z.object({ name: z.string(), type: z.string(), wr: z.number() })
@@ -55,30 +73,34 @@ const foreignKeySchema = z.object({ id: z.number(), seq: z.number(), table: z.st
55
73
  function bunTarget(db: Database): SqliteMigrationTarget {
56
74
  return {
57
75
  exec(query, ...bindings) {
58
- const statement = db.prepare<Record<string, unknown>, (string | number | null)[]>(query)
59
- try {
60
- if (bindings.length > 0 || statement.columnNames.length > 0) {
61
- const rows = statement.all(...bindings)
62
- return { toArray: () => rows }
63
- }
64
- } finally {
65
- statement.finalize()
66
- }
67
- db.run(query)
68
- return { toArray: () => [] }
76
+ const rows = execStatements(db, query, bindings)
77
+ return { toArray: () => rows }
69
78
  },
70
79
  transactionSync: (fn) => db.transaction(fn)(),
71
80
  }
72
81
  }
73
82
 
74
- function describeSqlite(column: SqliteColumn): DescribedColumn {
83
+ function describeSqlite(column: SqliteColumn): DescribedColumn | LeftOut {
75
84
  const base = column.declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
76
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' }
77
88
  if (mapped === undefined) {
89
+ const computed = column.generated === 'always'
90
+ if (computed && column.keyed) throw leftOutRefusal(columnPath(column), 'it is in the primary key or a unique key')
91
+ // A generated column without a declared type is one its author may mean to read: it is refused, not left out.
92
+ if (computed && base !== '') return { leftOut: column.declared.trim(), of: 'generated' }
93
+ if (base === 'JSON') {
94
+ throw new CodegenError(
95
+ `${
96
+ columnPath(column)
97
+ } has declared type '${column.declared}'; declare it JSONB, the name the data layer reads and binds as JSON, as Postgres's jsonb`,
98
+ )
99
+ }
78
100
  throw new CodegenError(
79
- `${column.table_name}.${column.column_name} has declared type '${column.declared}', which the data layer does not read or bind on SQLite (supported: ${
101
+ `${columnPath(column)} has declared type '${column.declared}', which the data layer does not read or bind on SQLite (supported: ${
80
102
  [...DECLARED_TYPES.keys()].join(', ')
81
- })`,
103
+ })${computed && base === '' ? '; declare the type of the generated column' : ''}`,
82
104
  )
83
105
  }
84
106
  return { scalar: mapped.scalar, nullable: column.nullable, generated: column.generated, list: mapped.list }
@@ -89,10 +111,10 @@ function primaryKeyOf(db: Database, table: string): string[] {
89
111
  return columns.map((column) => column.name)
90
112
  }
91
113
 
92
- /** 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. */
93
115
  function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: ForeignKeyColumns[] } {
94
116
  const tables = z.array(tableSchema).parse(
95
- 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(),
96
118
  ).filter((table) => !table.name.startsWith('sqlite_') && !table.name.startsWith('fabrika_'))
97
119
  const columns: SqliteColumn[] = []
98
120
  const foreignKeys: ForeignKeyColumns[] = []
@@ -100,15 +122,23 @@ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: Forei
100
122
  if (table.type === 'virtual') throw new CodegenError(`table ${table.name} is a virtual table, which the data layer does not read`)
101
123
  const declared = z.array(columnSchema).parse(db.query('SELECT * FROM pragma_table_xinfo(?) ORDER BY cid').all(table.name))
102
124
  const keyColumns = declared.filter((column) => column.pk > 0)
125
+ const unique = new Set(
126
+ z.array(z.object({ name: z.string().nullable() })).parse(
127
+ db.query(`SELECT i.name FROM pragma_index_list(?1) l, pragma_index_info(l.name) i WHERE l."unique" = 1`).all(table.name),
128
+ ).map((column) => column.name),
129
+ )
103
130
  for (const column of declared) {
104
131
  // An INTEGER PRIMARY KEY of a rowid table is the rowid: never null, assigned when an insert omits it.
105
132
  const rowid = table.wr === 0 && keyColumns.length === 1 && column.pk === 1 && column.type.trim().toUpperCase() === 'INTEGER'
133
+ const computed = column.hidden === 2 || column.hidden === 3
106
134
  columns.push({
107
135
  table_name: table.name,
108
136
  column_name: column.name,
137
+ view: table.type === 'view',
109
138
  declared: column.type,
110
139
  nullable: !rowid && column.notnull === 0,
111
- generated: column.hidden === 2 || column.hidden === 3 ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
140
+ generated: computed ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
141
+ keyed: column.pk > 0 || unique.has(column.name),
112
142
  })
113
143
  }
114
144
  const references = z.array(foreignKeySchema).parse(db.query('SELECT * FROM pragma_foreign_key_list(?) ORDER BY id DESC, seq').all(table.name))
@@ -141,13 +171,23 @@ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: Forei
141
171
  * Applies `bundles` (the framework's `fabrika`, then the application's `app`) to a fresh in-memory database and renders
142
172
  * the module for `SCHEMA_FILE` from its application tables. Deterministic for given migrations.
143
173
  */
144
- export async function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<string> {
174
+ export function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<GeneratedModule> {
175
+ return withMigratedSqlite(bundles, (db) => {
176
+ const { columns, foreignKeys } = introspect(db)
177
+ return renderTables(columns, foreignKeys, describeSqlite)
178
+ })
179
+ }
180
+
181
+ /**
182
+ * `read` of a fresh in-memory database with foreign keys enforced and `bundles` applied, as the Durable Object applies
183
+ * them; the database is closed after. `fabrika-check` plans the backup of an application's schema with it.
184
+ */
185
+ export async function withMigratedSqlite<T>(bundles: readonly SqliteMigrationBundle[], read: (db: Database) => T): Promise<T> {
145
186
  const db = new Database(':memory:')
146
187
  try {
147
188
  db.run('PRAGMA foreign_keys = ON')
148
189
  await migrateSqlite(bunTarget(db), bundles)
149
- const { columns, foreignKeys } = introspect(db)
150
- return renderTables(columns, foreignKeys, describeSqlite)
190
+ return read(db)
151
191
  } finally {
152
192
  db.close()
153
193
  }
package/src/codegen.ts CHANGED
@@ -8,6 +8,8 @@ export const SCHEMA_FILE = 'src/db/schema.generated.ts'
8
8
 
9
9
  /** Framework tables (the migration ledger, and later files, job leases, webhook deliveries) are not application tables. */
10
10
  const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
11
+ /** The formatter's line width (`dprint.json`), a tab counted as one column: a longer line it would break. */
12
+ const LINE_WIDTH = 150
11
13
 
12
14
  const HEADER = '// @generated by fabrika db codegen from the migrated database. Do not edit: write a migration, then run fabrika db codegen.'
13
15
 
@@ -25,6 +27,8 @@ const DECIMAL_STRING: ScalarType = { select: 'string', write: 'bigint | number |
25
27
  const DAY: ScalarType = { select: 'string' }
26
28
  /** A point in time: Bun decodes a `Date`; a write binds a `Date` or its ISO 8601 text. */
27
29
  const TIMESTAMP: ScalarType = { select: 'Date', write: 'Date | string' }
30
+ /** A JSON column: a read answers the parsed value, which the handler parses with a schema; a write binds a JSON value. */
31
+ export const JSON_COLUMN: ScalarType = { select: 'unknown', write: 'JsonColumnValue' }
28
32
 
29
33
  /** Exactly the types whose decoding by `Bun.SQL` the codegen test pins; anything else is refused, not guessed. */
30
34
  const SCALAR_TYPES: ReadonlyMap<string, ScalarType> = new Map([
@@ -45,6 +49,7 @@ const SCALAR_TYPES: ReadonlyMap<string, ScalarType> = new Map([
45
49
  ['date', DAY],
46
50
  ['timestamp', TIMESTAMP],
47
51
  ['timestamptz', TIMESTAMP],
52
+ ['jsonb', JSON_COLUMN],
48
53
  ])
49
54
 
50
55
  export class CodegenError extends Error {
@@ -53,6 +58,8 @@ export class CodegenError extends Error {
53
58
 
54
59
  const catalogColumnSchema = z.object({
55
60
  table_name: z.string(),
61
+ /** The relation is a view (`relkind` `v`): read-only, every column nullable. A materialized view is left out (ADR-0072). */
62
+ view: z.boolean(),
56
63
  column_name: z.string(),
57
64
  type_name: z.string(),
58
65
  /** `pg_type.typtype`: `b` base, `e` enum, `d` domain, … */
@@ -61,6 +68,12 @@ const catalogColumnSchema = z.object({
61
68
  type_category: z.string(),
62
69
  nullable: z.boolean(),
63
70
  generated: z.enum(['no', 'default', 'always']),
71
+ /** A column `GENERATED ALWAYS AS (…)` computes (`pg_attribute.attgenerated`); an identity column is not one. */
72
+ computed: z.boolean(),
73
+ /** The column's type as its author wrote it (`format_type`, without the schema): `text[]` where `type_name` is `_text`. */
74
+ formatted_type: z.string(),
75
+ /** The column is in the primary key or in a unique index. */
76
+ keyed: z.boolean(),
64
77
  enum_labels: z.array(z.string()),
65
78
  })
66
79
 
@@ -82,10 +95,11 @@ export interface Catalog {
82
95
  readonly foreignKeys: readonly CatalogForeignKey[]
83
96
  }
84
97
 
85
- /** One row per column of every ordinary or partitioned table in the schema, in table then column order. */
98
+ /** One row per column of every ordinary or partitioned table and view of the schema, in table then column order. */
86
99
  const CATALOG_QUERY = `
87
100
  SELECT
88
101
  c.relname::text AS table_name,
102
+ c.relkind = 'v' AS view,
89
103
  a.attname::text AS column_name,
90
104
  t.typname::text AS type_name,
91
105
  t.typtype::text AS type_type,
@@ -96,12 +110,15 @@ SELECT
96
110
  WHEN a.atthasdef OR a.attidentity = 'd' THEN 'default'
97
111
  ELSE 'no'
98
112
  END AS generated,
113
+ a.attgenerated <> '' AS computed,
114
+ replace(format_type(a.atttypid, a.atttypmod), $1 || '.', '') AS formatted_type,
115
+ EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisunique AND a.attnum = ANY (i.indkey)) AS keyed,
99
116
  ARRAY(SELECT e.enumlabel::text FROM pg_enum e WHERE e.enumtypid = t.oid ORDER BY e.enumsortorder) AS enum_labels
100
117
  FROM pg_attribute a
101
118
  JOIN pg_class c ON c.oid = a.attrelid
102
119
  JOIN pg_namespace n ON n.oid = c.relnamespace
103
120
  JOIN pg_type t ON t.oid = a.atttypid
104
- WHERE n.nspname = $1 AND c.relkind IN ('r', 'p') AND NOT c.relispartition AND a.attnum > 0 AND NOT a.attisdropped
121
+ WHERE n.nspname = $1 AND c.relkind IN ('r', 'p', 'v') AND NOT c.relispartition AND a.attnum > 0 AND NOT a.attisdropped
105
122
  ORDER BY c.relname, a.attnum
106
123
  `
107
124
 
@@ -150,7 +167,7 @@ export async function introspectCatalog(url: string, schema: string, objects: re
150
167
  if (!Array.isArray(namespaces) || namespaces.length === 0) {
151
168
  throw new CodegenError(`schema ${schema} does not exist; run fabrika db migrate first`)
152
169
  }
153
- // The migration runner's own pre-commit check, so an object created outside a migration fails every start.
170
+ // The migration runner's own pre-commit check, so an object created outside a migration fails the check.
154
171
  const code = z.array(z.object({ violation: z.string() })).parse(await tx.unsafe(databaseCodeQuery(schema, objects)))
155
172
  if (code.length > 0) {
156
173
  throw new CodegenError(
@@ -170,13 +187,14 @@ export async function introspectCatalog(url: string, schema: string, objects: re
170
187
  }
171
188
 
172
189
  /**
173
- * `note_comments` → `NoteCommentsTable`; the suffix keeps every name clear of `DB` and the imported type names. A
174
- * name that would not start with a letter (`_123`) gets a `T` prefix, so it stays a TypeScript identifier.
190
+ * `note_comments` → `NoteCommentsTable`, a view `deal_summaries` → `DealSummariesView`; the suffix keeps every name
191
+ * clear of `DB` and the imported type names. A name that would not start with a letter (`_123`) gets a `T` prefix, so
192
+ * it stays a TypeScript identifier.
175
193
  */
176
- function interfaceName(table: string): string {
194
+ function interfaceName(table: string, view: boolean): string {
177
195
  const words = table.split('_').filter((word) => word !== '')
178
196
  const pascal = words.map((word) => `${word.charAt(0).toUpperCase()}${word.slice(1)}`).join('')
179
- return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}Table`
197
+ return `${/^[A-Z]/.test(pascal) ? pascal : `T${pascal}`}${view ? 'View' : 'Table'}`
180
198
  }
181
199
 
182
200
  /** As keys of the generated object literal these would set or shadow the prototype instead of naming a table. */
@@ -186,19 +204,18 @@ function quote(value: string): string {
186
204
  return `'${JSON.stringify(value).slice(1, -1).replaceAll('\\"', '"').replaceAll("'", "\\'")}'`
187
205
  }
188
206
 
189
- function scalarType(column: CatalogColumn): ScalarType {
190
- const where = `${column.table_name}.${column.column_name}`
207
+ /** `table.column`: how a message names a column. */
208
+ export function columnPath(column: NamedColumn): string {
209
+ return `${column.table_name}.${column.column_name}`
210
+ }
211
+
212
+ /** The column's types, or `undefined` for a type the data layer does not read or bind. */
213
+ function scalarType(column: CatalogColumn): ScalarType | undefined {
191
214
  if (column.type_type === 'e') {
192
- if (column.enum_labels.length === 0) throw new CodegenError(`${where}: enum ${column.type_name} has no labels`)
215
+ if (column.enum_labels.length === 0) throw new CodegenError(`${columnPath(column)}: enum ${column.type_name} has no labels`)
193
216
  return { select: column.enum_labels.map(quote).join(' | ') }
194
217
  }
195
- const scalar = column.type_category === 'A' || column.type_type !== 'b' ? undefined : SCALAR_TYPES.get(column.type_name)
196
- if (scalar === undefined) {
197
- throw new CodegenError(
198
- `${where} has type ${column.type_name}, which the data layer does not read or bind (supported: ${[...SCALAR_TYPES.keys()].join(', ')}, enums)`,
199
- )
200
- }
201
- return scalar
218
+ return column.type_category === 'A' || column.type_type !== 'b' ? undefined : SCALAR_TYPES.get(column.type_name)
202
219
  }
203
220
 
204
221
  interface Rendered {
@@ -211,8 +228,49 @@ export interface DescribedColumn {
211
228
  readonly scalar: ScalarType
212
229
  readonly nullable: boolean
213
230
  readonly generated: 'no' | 'default' | 'always'
214
- /** The column list field that names the column: a day, a timestamp, or (on SQLite) a boolean. */
215
- readonly list: 'dates' | 'timestamps' | 'booleans' | undefined
231
+ /** The column list field that names the column: a day, a timestamp, a JSON column, or (on SQLite) a boolean. */
232
+ readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined
233
+ }
234
+
235
+ /**
236
+ * A column `describe` leaves out of the module: a generated column, or a view's column, of a type the data layer does
237
+ * not read.
238
+ */
239
+ export interface LeftOut {
240
+ /** The column's type, as its author wrote it (empty: a SQLite view's expression, which has none). */
241
+ readonly leftOut: string
242
+ readonly of: LeftOutKind
243
+ }
244
+
245
+ /** Why a column is left out rather than refused: it is computed, by a generated column or by a view. */
246
+ export type LeftOutKind = 'generated' | 'view'
247
+
248
+ /** A column the module leaves out; only `ctx.sql` reaches it. */
249
+ export interface LeftOutColumn {
250
+ readonly table: string
251
+ readonly column: string
252
+ /** Its type, as its author wrote it. */
253
+ readonly type: string
254
+ readonly of: LeftOutKind
255
+ }
256
+
257
+ /** What codegen says of a left-out column: in the module, `name` is the column; in its output, `table.column`. */
258
+ export function leftOutText(name: string, type: string, of: LeftOutKind): string {
259
+ if (of === 'generated') return `${name} (${type}, generated) is left out: the data layer does not read it; ctx.sql does`
260
+ return `${name} (${
261
+ type === '' ? 'no declared type' : type
262
+ }, of a view) is left out: the data layer does not read it; cast it to a type it reads, or read it with ctx.sql`
263
+ }
264
+
265
+ /** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
266
+ export function leftOutRefusal(path: string, what: string): CodegenError {
267
+ return new CodegenError(`${path} is a generated column of a type the data layer does not read, so codegen leaves it out, but ${what}`)
268
+ }
269
+
270
+ /** The text of `SCHEMA_FILE`, and the columns it leaves out, for the command to name. */
271
+ export interface GeneratedModule {
272
+ readonly source: string
273
+ readonly leftOut: readonly LeftOutColumn[]
216
274
  }
217
275
 
218
276
  /** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
@@ -229,14 +287,41 @@ export interface NamedColumn {
229
287
  readonly column_name: string
230
288
  }
231
289
 
232
- function describePostgres(column: CatalogColumn): DescribedColumn {
290
+ /** A column of a table or of a view, as `renderTables` reads it. */
291
+ export interface RelationColumn extends NamedColumn {
292
+ /** The relation is a view: read-only, with no key or foreign key. */
293
+ readonly view: boolean
294
+ }
295
+
296
+ /**
297
+ * A column's types; for a type the data layer does not read, a generated column (any such type: an array, `json`, a
298
+ * range, a composite, a domain) is left out, unless a key needs it, and so is a view's column; any other is refused.
299
+ */
300
+ function describePostgres(column: CatalogColumn): DescribedColumn | LeftOut {
233
301
  const scalar = scalarType(column)
302
+ if (scalar === undefined) {
303
+ if (column.view) return { leftOut: column.formatted_type, of: 'view' }
304
+ if (column.computed && column.keyed) throw leftOutRefusal(columnPath(column), 'it is in the primary key or a unique key')
305
+ if (column.computed) return { leftOut: column.formatted_type, of: 'generated' }
306
+ if (column.type_type === 'b' && column.type_name === 'json') {
307
+ throw new CodegenError(
308
+ `${columnPath(column)} has type json; declare it jsonb, which the data layer reads and binds (json keeps whitespace and duplicate keys)`,
309
+ )
310
+ }
311
+ throw new CodegenError(
312
+ `${columnPath(column)} has type ${column.type_name}, which the data layer does not read or bind (supported: ${
313
+ [...SCALAR_TYPES.keys()].join(', ')
314
+ }, enums)`,
315
+ )
316
+ }
234
317
  const list = column.type_type !== 'b'
235
318
  ? undefined
236
319
  : column.type_name === 'date'
237
320
  ? 'dates'
238
321
  : column.type_name === 'timestamp' || column.type_name === 'timestamptz'
239
322
  ? 'timestamps'
323
+ : column.type_name === 'jsonb'
324
+ ? 'json'
240
325
  : undefined
241
326
  return { scalar, nullable: column.nullable, generated: column.generated, list }
242
327
  }
@@ -256,23 +341,26 @@ function columnType(column: DescribedColumn): Rendered {
256
341
  }
257
342
 
258
343
  /**
259
- * The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take, and the
260
- * runtime column list with each table's foreign keys to application tables. Deterministic for a given catalog, so
261
- * `fabrika db codegen --verify` can compare text.
344
+ * The generated module: one interface per application table and view, the `DB` map Kysely and `defineTables` take,
345
+ * and the runtime column list with each table's foreign keys to application tables and each view marked; with the
346
+ * columns it leaves out. Deterministic for a given catalog, so `fabrika db codegen --verify` can compare text.
262
347
  */
263
- export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): string {
348
+ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
264
349
  return renderTables(catalog, foreignKeys, describePostgres)
265
350
  }
266
351
 
267
352
  /**
268
- * `renderSchema` over columns of any database: `describe` gives each column's types and list field, and refuses a
269
- * type the data layer does not read. A foreign key's `constraint_name` is not rendered; keys keep the given order.
353
+ * `renderSchema` over columns of any database: `describe` gives each column's types and list field, refuses a type the
354
+ * data layer does not read, or answers `LeftOut` for a generated column or a view's column of such a type. That column
355
+ * is left out of the module but for a comment where it stands, so no handle reads or writes it and only `ctx.sql`
356
+ * reaches it; a foreign key that names it, and a table it would leave without a column, are refused, and a view left
357
+ * without a column is left out whole. A foreign key's `constraint_name` is not rendered; keys keep the given order.
270
358
  */
271
- export function renderTables<C extends NamedColumn>(
359
+ export function renderTables<C extends RelationColumn>(
272
360
  catalog: readonly C[],
273
361
  foreignKeys: readonly ForeignKeyColumns[],
274
- describe: (column: C) => DescribedColumn,
275
- ): string {
362
+ describe: (column: C) => DescribedColumn | LeftOut,
363
+ ): GeneratedModule {
276
364
  const tables = new Map<string, C[]>()
277
365
  for (const column of catalog) {
278
366
  if (column.table_name.startsWith(FRAMEWORK_TABLE_PREFIX)) continue
@@ -286,31 +374,65 @@ export function renderTables<C extends NamedColumn>(
286
374
  columns.push(column)
287
375
  tables.set(column.table_name, columns)
288
376
  }
377
+ const views = new Set(catalog.filter((column) => column.view).map((column) => column.table_name))
289
378
  const names = [...tables.keys()].sort()
290
379
  const owners = new Map<string, string>()
291
380
  const used = new Set<string>()
292
381
  const interfaces: string[] = []
293
382
  const described = new Map<C, DescribedColumn>()
383
+ const leftOut: LeftOutColumn[] = []
384
+ const emptyViews = new Set<string>()
294
385
  for (const table of names) {
295
- const name = interfaceName(table)
386
+ const name = interfaceName(table, views.has(table))
296
387
  const owner = owners.get(name)
297
388
  if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
298
389
  owners.set(name, table)
299
- const fields = (tables.get(table) ?? []).map((column) => {
390
+ const kept: C[] = []
391
+ const fields: string[] = []
392
+ for (const column of tables.get(table) ?? []) {
300
393
  const description = describe(column)
394
+ if ('leftOut' in description) {
395
+ const type = description.leftOut
396
+ leftOut.push({ table, column: column.column_name, type, of: description.of })
397
+ // A type name is the database's text: one that could end the comment line is quoted there.
398
+ fields.push(`\t// ${leftOutText(column.column_name, type === '' || /^[\w (),.[\]]+$/.test(type) ? type : quote(type), description.of)}\n`)
399
+ continue
400
+ }
401
+ kept.push(column)
301
402
  described.set(column, description)
302
403
  const rendered = columnType(description)
303
404
  if (rendered.uses !== undefined) used.add(rendered.uses)
304
- return `\t${column.column_name}: ${rendered.type}\n`
305
- })
405
+ fields.push(`\t${column.column_name}: ${rendered.type}\n`)
406
+ }
407
+ if (kept.length === 0 && views.has(table)) {
408
+ emptyViews.add(table)
409
+ continue
410
+ }
411
+ if (kept.length === 0) {
412
+ throw new CodegenError(`table ${table} has only generated columns of types the data layer does not read, which codegen leaves out`)
413
+ }
414
+ tables.set(table, kept)
306
415
  interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
307
416
  }
417
+ for (const view of emptyViews) tables.delete(view)
418
+ const rendered = names.filter((table) => !emptyViews.has(table))
419
+ const renderedViews = rendered.filter((table) => views.has(table))
420
+ const leftOutPaths = new Set(leftOut.map((column) => columnPath({ table_name: column.table, column_name: column.column })))
421
+ for (const key of foreignKeys) {
422
+ if (!tables.has(key.table_name) || !tables.has(key.referenced_table)) continue
423
+ const named = [
424
+ ...key.columns.map((column) => columnPath({ table_name: key.table_name, column_name: column })),
425
+ ...key.referenced_columns.map((column) => columnPath({ table_name: key.referenced_table, column_name: column })),
426
+ ].find((path) => leftOutPaths.has(path))
427
+ if (named !== undefined) throw leftOutRefusal(named, `a foreign key of ${key.table_name} names it`)
428
+ }
308
429
  const kyselyNames = ['ColumnType', 'Generated', 'GeneratedAlways'].filter((name) => used.has(name))
430
+ const json = [...described.values()].some((column) => column.list === 'json')
309
431
  const imports = [
310
- "import type { TypedColumnList } from '@fabrika/db'\n",
432
+ `import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
311
433
  ...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
312
434
  ]
313
- const db = names.map((table) => `\t${table}: ${interfaceName(table)}\n`).join('')
435
+ const db = rendered.map((table) => `\t${table}: ${interfaceName(table, views.has(table))}\n`).join('')
314
436
  const keysOf = (table: string): string => {
315
437
  const keys = foreignKeys.filter((key) => key.table_name === table && tables.has(key.referenced_table))
316
438
  if (keys.length === 0) return '\t\tforeignKeys: [],\n'
@@ -322,31 +444,48 @@ export function renderTables<C extends NamedColumn>(
322
444
  }
323
445
  /**
324
446
  * A table's columns listed in `field`: the days, which the layer answers as `YYYY-MM-DD`, the timestamps, whose
325
- * written text it checks, and SQLite's booleans, which it reads from 0 or 1. A table without one has no such field.
447
+ * written text it checks, SQLite's booleans, which it reads from 0 or 1, and the JSON columns, whose written value
448
+ * it serializes. A table without one has no such field.
326
449
  */
327
450
  const listOf = (table: string, field: DescribedColumn['list']): string => {
328
451
  const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
329
452
  return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
330
453
  }
331
- const datesOf = (table: string): string => `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}`
332
- const columns = names
454
+ // The NOT NULL columns, which a foreign key that holds a row's tenant needs its ancestor columns among. A list past
455
+ // the formatter's line width goes one column per line, as `columns` does, so the module stays formatter-stable.
456
+ const notNullOf = (table: string): string => {
457
+ const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.nullable === false).map((column) => quote(column.column_name))
458
+ if (listed.length === 0) return ''
459
+ const line = `\t\tnotNull: [${listed.join(', ')}],`
460
+ return line.length <= LINE_WIDTH ? `${line}\n` : `\t\tnotNull: [\n${listed.map((name) => `\t\t\t${name},\n`).join('')}\t\t],\n`
461
+ }
462
+ const datesOf = (table: string): string =>
463
+ `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}${notNullOf(table)}`
464
+ const columns = rendered
333
465
  .map((table) =>
334
466
  `\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
335
467
  keysOf(table)
336
- }${datesOf(table)}\t},\n`
468
+ }${datesOf(table)}${views.has(table) ? '\t\tview: true,\n' : ''}\t},\n`
337
469
  )
338
470
  .join('')
339
- return [
471
+ // The views ride in the list's type, so the policy types know which tables only a read reaches. One per line, as
472
+ // dprint keeps a union of two or more, so the module stays formatter-stable however many views there are.
473
+ const viewsAlias = renderedViews.length === 1
474
+ ? `export type Views = ${quote(renderedViews[0] ?? '')}\n`
475
+ : `export type Views =\n${renderedViews.map((view) => `\t| ${quote(view)}\n`).join('')}`
476
+ const source = [
340
477
  `${HEADER}\n`,
341
478
  imports.join(''),
342
479
  ...interfaces,
343
480
  `export interface DB {\n${db}}\n`,
344
- `export const columns: TypedColumnList<DB> = {\n${columns}}\n`,
481
+ ...(renderedViews.length === 0 ? [] : [viewsAlias]),
482
+ `export const columns: ${renderedViews.length === 0 ? 'TypedColumnList<DB>' : 'TypedColumnList<DB, Views>'} = {\n${columns}}\n`,
345
483
  ].join('\n')
484
+ return { source, leftOut }
346
485
  }
347
486
 
348
487
  /** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
349
- export async function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<string> {
488
+ export async function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule> {
350
489
  const catalog = await introspectCatalog(url, schema, objects)
351
490
  return renderSchema(catalog.columns, catalog.foreignKeys)
352
491
  }