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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/package.json +39 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +230 -41
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +10 -6
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +15 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +17 -1
  19. package/src/job-leases.ts +228 -55
  20. package/src/job-wakes.ts +600 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/list-cursor.ts +82 -0
  24. package/src/migrations-sqlite.ts +210 -0
  25. package/src/migrations.ts +73 -0
  26. package/src/nodes.ts +84 -14
  27. package/src/orm-types.ts +206 -71
  28. package/src/orm.ts +425 -170
  29. package/src/policy.ts +1979 -141
  30. package/src/postgres.ts +26 -0
  31. package/src/registry.ts +55 -3
  32. package/src/request-receipts.ts +107 -0
  33. package/src/sql.ts +247 -476
  34. package/src/sqlite-bun.ts +149 -0
  35. package/src/sqlite-migrate.ts +242 -0
  36. package/src/sqlite.ts +269 -0
  37. package/src/store.ts +2292 -239
  38. package/src/stored-files.ts +188 -52
  39. package/src/tables.ts +172 -6
  40. package/src/temporal.ts +122 -9
  41. package/src/testing-shared.ts +1351 -0
  42. package/src/testing-sqlite.ts +685 -0
  43. package/src/testing.ts +310 -494
  44. package/src/vocabulary-tables.ts +159 -27
  45. package/types/src/application-rows.d.ts +58 -0
  46. package/types/src/authority.d.ts +147 -0
  47. package/types/src/builtins.d.ts +2 -0
  48. package/types/src/capability.d.ts +55 -2
  49. package/types/src/codegen-sqlite.d.ts +13 -0
  50. package/types/src/codegen.d.ts +79 -5
  51. package/types/src/condition-nodes.d.ts +9 -0
  52. package/types/src/conditions.d.ts +151 -0
  53. package/types/src/database.d.ts +81 -20
  54. package/types/src/description.d.ts +26 -8
  55. package/types/src/errors.d.ts +9 -6
  56. package/types/src/file-columns.d.ts +6 -4
  57. package/types/src/framework.d.ts +12 -5
  58. package/types/src/guard.d.ts +24 -0
  59. package/types/src/index.d.ts +5 -4
  60. package/types/src/job-leases.d.ts +40 -5
  61. package/types/src/job-wakes.d.ts +124 -0
  62. package/types/src/json.d.ts +18 -0
  63. package/types/src/list-cursor.d.ts +13 -0
  64. package/types/src/migrations-sqlite.d.ts +4 -0
  65. package/types/src/migrations.d.ts +4 -0
  66. package/types/src/nodes.d.ts +17 -2
  67. package/types/src/orm-types.d.ts +163 -71
  68. package/types/src/orm.d.ts +21 -0
  69. package/types/src/policy.d.ts +351 -23
  70. package/types/src/postgres.d.ts +12 -0
  71. package/types/src/registry.d.ts +40 -3
  72. package/types/src/request-receipts.d.ts +22 -0
  73. package/types/src/sql.d.ts +29 -21
  74. package/types/src/sqlite-bun.d.ts +21 -0
  75. package/types/src/sqlite-migrate.d.ts +28 -0
  76. package/types/src/sqlite.d.ts +24 -0
  77. package/types/src/store.d.ts +143 -34
  78. package/types/src/stored-files.d.ts +6 -2
  79. package/types/src/tables.d.ts +18 -2
  80. package/types/src/temporal.d.ts +24 -0
  81. package/types/src/testing-shared.d.ts +290 -0
  82. package/types/src/testing-sqlite.d.ts +37 -0
  83. package/types/src/testing.d.ts +2 -93
  84. package/types/src/vocabulary-tables.d.ts +169 -22
@@ -0,0 +1,194 @@
1
+ // @fabrika/db/codegen-sqlite — `fabrika db codegen` for an application on Cloudflare (ADR-0065): applies its bundles to
2
+ // an in-memory SQLite database, reads its tables back and renders `SCHEMA_FILE` with the Postgres codegen's renderer.
3
+ // Runs in the CLI, on Bun.
4
+
5
+ import { Database } from 'bun:sqlite'
6
+ import { z } from 'zod/v4'
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'
21
+ import { migrateSqlite, type SqliteMigrationBundle, type SqliteMigrationTarget } from './sqlite-migrate'
22
+
23
+ const STRING: ScalarType = { select: 'string' }
24
+ const NUMBER: ScalarType = { select: 'number' }
25
+
26
+ /** A column's TypeScript types and list field by its declared type, without a length (`VARCHAR(80)` → `VARCHAR`). */
27
+ const DECLARED_TYPES: ReadonlyMap<string, { readonly scalar: ScalarType; readonly list: DescribedColumn['list'] }> = new Map([
28
+ ['TEXT', { scalar: STRING, list: undefined }],
29
+ ['VARCHAR', { scalar: STRING, list: undefined }],
30
+ ['CHAR', { scalar: STRING, list: undefined }],
31
+ ['UUID', { scalar: STRING, list: undefined }],
32
+ ['INTEGER', { scalar: NUMBER, list: undefined }],
33
+ ['INT', { scalar: NUMBER, list: undefined }],
34
+ ['BIGINT', { scalar: NUMBER, list: undefined }],
35
+ ['SMALLINT', { scalar: NUMBER, list: undefined }],
36
+ ['REAL', { scalar: NUMBER, list: undefined }],
37
+ ['DOUBLE', { scalar: NUMBER, list: undefined }],
38
+ ['FLOAT', { scalar: NUMBER, list: undefined }],
39
+ ['BOOLEAN', { scalar: { select: 'boolean' }, list: 'booleans' }],
40
+ ['TIMESTAMP', { scalar: { select: 'Date', write: 'Date | string' }, list: 'timestamps' }],
41
+ ['TIMESTAMPTZ', { scalar: { select: 'Date', write: 'Date | string' }, list: 'timestamps' }],
42
+ ['DATETIME', { scalar: { select: 'Date', write: 'Date | string' }, list: 'timestamps' }],
43
+ ['DATE', { scalar: STRING, list: 'dates' }],
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' }],
47
+ ])
48
+
49
+ interface SqliteColumn extends RelationColumn {
50
+ readonly declared: string
51
+ readonly nullable: boolean
52
+ /** `always` is a column `GENERATED ALWAYS AS (…)` computes (`hidden` 2 or 3): SQLite has no identity column. */
53
+ readonly generated: DescribedColumn['generated']
54
+ /** The column is in the primary key or in a unique index. */
55
+ readonly keyed: boolean
56
+ }
57
+
58
+ const tableSchema = z.object({ name: z.string(), type: z.string(), wr: z.number() })
59
+
60
+ const columnSchema = z.object({
61
+ name: z.string(),
62
+ type: z.string(),
63
+ notnull: z.number(),
64
+ dflt_value: z.string().nullable(),
65
+ pk: z.number(),
66
+ /** 0 an ordinary column, 2 or 3 a generated one. */
67
+ hidden: z.number(),
68
+ })
69
+
70
+ const foreignKeySchema = z.object({ id: z.number(), seq: z.number(), table: z.string(), from: z.string(), to: z.string().nullable() })
71
+
72
+ /** Runs multi-statement text the way a Durable Object's `sql.exec` does; `prepare` alone compiles only its first statement. */
73
+ function bunTarget(db: Database): SqliteMigrationTarget {
74
+ return {
75
+ exec(query, ...bindings) {
76
+ const rows = execStatements(db, query, bindings)
77
+ return { toArray: () => rows }
78
+ },
79
+ transactionSync: (fn) => db.transaction(fn)(),
80
+ }
81
+ }
82
+
83
+ function describeSqlite(column: SqliteColumn): DescribedColumn | LeftOut {
84
+ const base = column.declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
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' }
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
+ }
100
+ throw new CodegenError(
101
+ `${columnPath(column)} has declared type '${column.declared}', which the data layer does not read or bind on SQLite (supported: ${
102
+ [...DECLARED_TYPES.keys()].join(', ')
103
+ })${computed && base === '' ? '; declare the type of the generated column' : ''}`,
104
+ )
105
+ }
106
+ return { scalar: mapped.scalar, nullable: column.nullable, generated: column.generated, list: mapped.list }
107
+ }
108
+
109
+ function primaryKeyOf(db: Database, table: string): string[] {
110
+ const columns = z.array(columnSchema).parse(db.query('SELECT * FROM pragma_table_xinfo(?) WHERE pk > 0 ORDER BY pk').all(table))
111
+ return columns.map((column) => column.name)
112
+ }
113
+
114
+ /** Every column of the application's ordinary tables and views, and the tables' foreign keys in declaration order. */
115
+ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: ForeignKeyColumns[] } {
116
+ const tables = z.array(tableSchema).parse(
117
+ db.query(`SELECT name, type, wr FROM pragma_table_list WHERE schema = 'main' AND type IN ('table', 'view', 'virtual') ORDER BY name`).all(),
118
+ ).filter((table) => !table.name.startsWith('sqlite_') && !table.name.startsWith('fabrika_'))
119
+ const columns: SqliteColumn[] = []
120
+ const foreignKeys: ForeignKeyColumns[] = []
121
+ for (const table of tables) {
122
+ if (table.type === 'virtual') throw new CodegenError(`table ${table.name} is a virtual table, which the data layer does not read`)
123
+ const declared = z.array(columnSchema).parse(db.query('SELECT * FROM pragma_table_xinfo(?) ORDER BY cid').all(table.name))
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
+ )
130
+ for (const column of declared) {
131
+ // An INTEGER PRIMARY KEY of a rowid table is the rowid: never null, assigned when an insert omits it.
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
134
+ columns.push({
135
+ table_name: table.name,
136
+ column_name: column.name,
137
+ view: table.type === 'view',
138
+ declared: column.type,
139
+ nullable: !rowid && column.notnull === 0,
140
+ generated: computed ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
141
+ keyed: column.pk > 0 || unique.has(column.name),
142
+ })
143
+ }
144
+ const references = z.array(foreignKeySchema).parse(db.query('SELECT * FROM pragma_foreign_key_list(?) ORDER BY id DESC, seq').all(table.name))
145
+ for (const id of new Set(references.map((reference) => reference.id))) {
146
+ const parts = references.filter((reference) => reference.id === id)
147
+ const referenced = parts[0]?.table
148
+ if (referenced === undefined) continue
149
+ // `REFERENCES parent` without columns names the parent's primary key.
150
+ const implicit = parts.some((part) => part.to === null) ? primaryKeyOf(db, referenced) : []
151
+ const referencedColumns: string[] = []
152
+ for (const [index, part] of parts.entries()) {
153
+ const name = part.to ?? implicit[index]
154
+ if (name === undefined) {
155
+ throw new CodegenError(`${table.name}: a foreign key to ${referenced} names no columns, and ${referenced} has no primary key of that width`)
156
+ }
157
+ referencedColumns.push(name)
158
+ }
159
+ foreignKeys.push({
160
+ table_name: table.name,
161
+ columns: parts.map((part) => part.from),
162
+ referenced_table: referenced,
163
+ referenced_columns: referencedColumns,
164
+ })
165
+ }
166
+ }
167
+ return { columns, foreignKeys }
168
+ }
169
+
170
+ /**
171
+ * Applies `bundles` (the framework's `fabrika`, then the application's `app`) to a fresh in-memory database and renders
172
+ * the module for `SCHEMA_FILE` from its application tables. Deterministic for given migrations.
173
+ */
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> {
186
+ const db = new Database(':memory:')
187
+ try {
188
+ db.run('PRAGMA foreign_keys = ON')
189
+ await migrateSqlite(bunTarget(db), bundles)
190
+ return read(db)
191
+ } finally {
192
+ db.close()
193
+ }
194
+ }
package/src/codegen.ts CHANGED
@@ -8,11 +8,13 @@ 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
 
14
16
  /** A column's TypeScript types: what a read returns, and what an insert or update may bind when that differs. */
15
- interface ScalarType {
17
+ export interface ScalarType {
16
18
  readonly select: string
17
19
  readonly write?: string
18
20
  }
@@ -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 {
@@ -206,8 +223,111 @@ interface Rendered {
206
223
  readonly uses: 'ColumnType' | 'Generated' | 'GeneratedAlways' | undefined
207
224
  }
208
225
 
209
- function columnType(column: CatalogColumn): Rendered {
226
+ /** What the renderer needs of a column beyond its name, whichever database it was read from. */
227
+ export interface DescribedColumn {
228
+ readonly scalar: ScalarType
229
+ readonly nullable: boolean
230
+ readonly generated: 'no' | 'default' | 'always'
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[]
274
+ }
275
+
276
+ /** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
277
+ export interface ForeignKeyColumns {
278
+ readonly table_name: string
279
+ readonly columns: readonly string[]
280
+ readonly referenced_table: string
281
+ readonly referenced_columns: readonly string[]
282
+ }
283
+
284
+ /** A column as the renderer groups it, before its type is described. */
285
+ export interface NamedColumn {
286
+ readonly table_name: string
287
+ readonly column_name: string
288
+ }
289
+
290
+ /** A column of a table or of a view, as `renderTables` reads it. */
291
+ export interface RelationColumn extends NamedColumn {
292
+ /** The relation is a view: read-only, with no key or foreign key. */
293
+ readonly view: boolean
294
+ }
295
+
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 {
210
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
+ }
317
+ const list = column.type_type !== 'b'
318
+ ? undefined
319
+ : column.type_name === 'date'
320
+ ? 'dates'
321
+ : column.type_name === 'timestamp' || column.type_name === 'timestamptz'
322
+ ? 'timestamps'
323
+ : column.type_name === 'jsonb'
324
+ ? 'json'
325
+ : undefined
326
+ return { scalar, nullable: column.nullable, generated: column.generated, list }
327
+ }
328
+
329
+ function columnType(column: DescribedColumn): Rendered {
330
+ const { scalar } = column
211
331
  const nullable = column.nullable ? ' | null' : ''
212
332
  const select = `${scalar.select}${nullable}`
213
333
  const write = scalar.write === undefined ? select : `${scalar.write}${nullable}`
@@ -221,12 +341,27 @@ function columnType(column: CatalogColumn): Rendered {
221
341
  }
222
342
 
223
343
  /**
224
- * The generated module: one interface per application table, the `DB` map Kysely and `defineTables` take, and the
225
- * runtime column list with each table's foreign keys to application tables. Deterministic for a given catalog, so
226
- * `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.
347
+ */
348
+ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
349
+ return renderTables(catalog, foreignKeys, describePostgres)
350
+ }
351
+
352
+ /**
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.
227
358
  */
228
- export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): string {
229
- const tables = new Map<string, CatalogColumn[]>()
359
+ export function renderTables<C extends RelationColumn>(
360
+ catalog: readonly C[],
361
+ foreignKeys: readonly ForeignKeyColumns[],
362
+ describe: (column: C) => DescribedColumn | LeftOut,
363
+ ): GeneratedModule {
364
+ const tables = new Map<string, C[]>()
230
365
  for (const column of catalog) {
231
366
  if (column.table_name.startsWith(FRAMEWORK_TABLE_PREFIX)) continue
232
367
  for (const name of [column.table_name, column.column_name]) {
@@ -239,28 +374,65 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
239
374
  columns.push(column)
240
375
  tables.set(column.table_name, columns)
241
376
  }
377
+ const views = new Set(catalog.filter((column) => column.view).map((column) => column.table_name))
242
378
  const names = [...tables.keys()].sort()
243
379
  const owners = new Map<string, string>()
244
380
  const used = new Set<string>()
245
381
  const interfaces: string[] = []
382
+ const described = new Map<C, DescribedColumn>()
383
+ const leftOut: LeftOutColumn[] = []
384
+ const emptyViews = new Set<string>()
246
385
  for (const table of names) {
247
- const name = interfaceName(table)
386
+ const name = interfaceName(table, views.has(table))
248
387
  const owner = owners.get(name)
249
388
  if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
250
389
  owners.set(name, table)
251
- const fields = (tables.get(table) ?? []).map((column) => {
252
- const rendered = columnType(column)
390
+ const kept: C[] = []
391
+ const fields: string[] = []
392
+ for (const column of tables.get(table) ?? []) {
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)
402
+ described.set(column, description)
403
+ const rendered = columnType(description)
253
404
  if (rendered.uses !== undefined) used.add(rendered.uses)
254
- return `\t${column.column_name}: ${rendered.type}\n`
255
- })
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)
256
415
  interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
257
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
+ }
258
429
  const kyselyNames = ['ColumnType', 'Generated', 'GeneratedAlways'].filter((name) => used.has(name))
430
+ const json = [...described.values()].some((column) => column.list === 'json')
259
431
  const imports = [
260
- "import type { TypedColumnList } from '@fabrika/db'\n",
432
+ `import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
261
433
  ...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
262
434
  ]
263
- 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('')
264
436
  const keysOf = (table: string): string => {
265
437
  const keys = foreignKeys.filter((key) => key.table_name === table && tables.has(key.referenced_table))
266
438
  if (keys.length === 0) return '\t\tforeignKeys: [],\n'
@@ -271,32 +443,49 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
271
443
  return `\t\tforeignKeys: [\n${rendered.join('')}\t\t],\n`
272
444
  }
273
445
  /**
274
- * A table's columns of `types` as the list field `field`: the `date` columns, which the layer answers as `YYYY-MM-DD`,
275
- * and the timestamps, whose written text it checks. A table without one has no such field.
446
+ * A table's columns listed in `field`: the days, which the layer answers as `YYYY-MM-DD`, the timestamps, whose
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.
276
449
  */
277
- const listOf = (table: string, field: string, types: readonly string[]): string => {
278
- const listed = (tables.get(table) ?? []).filter((column) => column.type_type === 'b' && types.includes(column.type_name))
450
+ const listOf = (table: string, field: DescribedColumn['list']): string => {
451
+ const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
279
452
  return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
280
453
  }
281
- const datesOf = (table: string): string => `${listOf(table, 'dates', ['date'])}${listOf(table, 'timestamps', ['timestamp', 'timestamptz'])}`
282
- 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
283
465
  .map((table) =>
284
466
  `\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
285
467
  keysOf(table)
286
- }${datesOf(table)}\t},\n`
468
+ }${datesOf(table)}${views.has(table) ? '\t\tview: true,\n' : ''}\t},\n`
287
469
  )
288
470
  .join('')
289
- 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 = [
290
477
  `${HEADER}\n`,
291
478
  imports.join(''),
292
479
  ...interfaces,
293
480
  `export interface DB {\n${db}}\n`,
294
- `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`,
295
483
  ].join('\n')
484
+ return { source, leftOut }
296
485
  }
297
486
 
298
487
  /** Introspects the migrated schema, checked against the migrations' manifest, and renders the module for `SCHEMA_FILE`. */
299
- 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> {
300
489
  const catalog = await introspectCatalog(url, schema, objects)
301
490
  return renderSchema(catalog.columns, catalog.foreignKeys)
302
491
  }