@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.11
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 +44 -12
- package/src/admissions.ts +78 -12
- package/src/application-rows.ts +108 -0
- package/src/capability.ts +5 -0
- package/src/codegen-sqlite.ts +191 -0
- package/src/codegen.ts +170 -28
- package/src/database.ts +227 -61
- package/src/description.ts +34 -8
- package/src/errors.ts +6 -4
- package/src/file-columns.ts +36 -9
- package/src/framework-tables.ts +28 -8
- package/src/framework.ts +14 -5
- package/src/guard.ts +8 -0
- package/src/index.ts +10 -1
- package/src/job-leases.ts +210 -54
- package/src/job-wakes.ts +450 -0
- package/src/json.ts +124 -0
- package/src/links.ts +8 -1
- package/src/migrations-sqlite.ts +163 -0
- package/src/migrations.ts +25 -0
- package/src/nodes.ts +64 -9
- package/src/orm-types.ts +5 -5
- package/src/orm.ts +94 -37
- package/src/policy.ts +17 -2
- package/src/postgres.ts +26 -0
- package/src/registry.ts +11 -2
- package/src/sql.ts +230 -477
- package/src/sqlite-bun.ts +149 -0
- package/src/sqlite-migrate.ts +242 -0
- package/src/sqlite.ts +224 -0
- package/src/store.ts +385 -103
- package/src/stored-files.ts +188 -52
- package/src/tables.ts +16 -0
- package/src/temporal.ts +122 -9
- package/src/testing-shared.ts +999 -0
- package/src/testing-sqlite.ts +576 -0
- package/src/testing.ts +261 -482
- package/types/src/admissions.d.ts +21 -0
- package/types/src/application-rows.d.ts +58 -0
- package/types/src/builtins.d.ts +42 -0
- package/types/src/capability.d.ts +119 -0
- package/types/src/codegen-sqlite.d.ts +13 -0
- package/types/src/codegen.d.ts +113 -0
- package/types/src/database.d.ts +185 -0
- package/types/src/description.d.ts +124 -0
- package/types/src/errors.d.ts +98 -0
- package/types/src/file-columns.d.ts +39 -0
- package/types/src/file-references.d.ts +27 -0
- package/types/src/framework-tables.d.ts +59 -0
- package/types/src/framework.d.ts +38 -0
- package/types/src/guard.d.ts +23 -0
- package/types/src/identifier.d.ts +4 -0
- package/types/src/index.d.ts +11 -0
- package/types/src/job-leases.d.ts +112 -0
- package/types/src/job-wakes.d.ts +101 -0
- package/types/src/json.d.ts +18 -0
- package/types/src/links.d.ts +13 -0
- package/types/src/migrations-sqlite.d.ts +4 -0
- package/types/src/migrations.d.ts +26 -0
- package/types/src/nodes.d.ts +73 -0
- package/types/src/orm-types.d.ts +638 -0
- package/types/src/orm.d.ts +82 -0
- package/types/src/policy.d.ts +358 -0
- package/types/src/postgres.d.ts +12 -0
- package/types/src/production.d.ts +5 -0
- package/types/src/registry.d.ts +43 -0
- package/types/src/sql.d.ts +67 -0
- package/types/src/sqlite-bun.d.ts +21 -0
- package/types/src/sqlite-migrate.d.ts +28 -0
- package/types/src/sqlite.d.ts +24 -0
- package/types/src/store.d.ts +351 -0
- package/types/src/stored-files.d.ts +102 -0
- package/types/src/tables.d.ts +21 -0
- package/types/src/temporal.d.ts +36 -0
- package/types/src/testing-shared.d.ts +269 -0
- package/types/src/testing-sqlite.d.ts +22 -0
- package/types/src/testing.d.ts +35 -0
- package/types/src/vocabulary-tables.d.ts +225 -0
package/src/codegen.ts
CHANGED
|
@@ -12,7 +12,7 @@ const FRAMEWORK_TABLE_PREFIX = 'fabrika_'
|
|
|
12
12
|
const HEADER = '// @generated by fabrika db codegen from the migrated database. Do not edit: write a migration, then run fabrika db codegen.'
|
|
13
13
|
|
|
14
14
|
/** A column's TypeScript types: what a read returns, and what an insert or update may bind when that differs. */
|
|
15
|
-
interface ScalarType {
|
|
15
|
+
export interface ScalarType {
|
|
16
16
|
readonly select: string
|
|
17
17
|
readonly write?: string
|
|
18
18
|
}
|
|
@@ -25,6 +25,8 @@ const DECIMAL_STRING: ScalarType = { select: 'string', write: 'bigint | number |
|
|
|
25
25
|
const DAY: ScalarType = { select: 'string' }
|
|
26
26
|
/** A point in time: Bun decodes a `Date`; a write binds a `Date` or its ISO 8601 text. */
|
|
27
27
|
const TIMESTAMP: ScalarType = { select: 'Date', write: 'Date | string' }
|
|
28
|
+
/** A JSON column: a read answers the parsed value, which the handler parses with a schema; a write binds a JSON value. */
|
|
29
|
+
export const JSON_COLUMN: ScalarType = { select: 'unknown', write: 'JsonColumnValue' }
|
|
28
30
|
|
|
29
31
|
/** Exactly the types whose decoding by `Bun.SQL` the codegen test pins; anything else is refused, not guessed. */
|
|
30
32
|
const SCALAR_TYPES: ReadonlyMap<string, ScalarType> = new Map([
|
|
@@ -45,6 +47,7 @@ const SCALAR_TYPES: ReadonlyMap<string, ScalarType> = new Map([
|
|
|
45
47
|
['date', DAY],
|
|
46
48
|
['timestamp', TIMESTAMP],
|
|
47
49
|
['timestamptz', TIMESTAMP],
|
|
50
|
+
['jsonb', JSON_COLUMN],
|
|
48
51
|
])
|
|
49
52
|
|
|
50
53
|
export class CodegenError extends Error {
|
|
@@ -61,6 +64,12 @@ const catalogColumnSchema = z.object({
|
|
|
61
64
|
type_category: z.string(),
|
|
62
65
|
nullable: z.boolean(),
|
|
63
66
|
generated: z.enum(['no', 'default', 'always']),
|
|
67
|
+
/** A column `GENERATED ALWAYS AS (…)` computes (`pg_attribute.attgenerated`); an identity column is not one. */
|
|
68
|
+
computed: z.boolean(),
|
|
69
|
+
/** The column's type as its author wrote it (`format_type`, without the schema): `text[]` where `type_name` is `_text`. */
|
|
70
|
+
formatted_type: z.string(),
|
|
71
|
+
/** The column is in the primary key or in a unique index. */
|
|
72
|
+
keyed: z.boolean(),
|
|
64
73
|
enum_labels: z.array(z.string()),
|
|
65
74
|
})
|
|
66
75
|
|
|
@@ -96,6 +105,9 @@ SELECT
|
|
|
96
105
|
WHEN a.atthasdef OR a.attidentity = 'd' THEN 'default'
|
|
97
106
|
ELSE 'no'
|
|
98
107
|
END AS generated,
|
|
108
|
+
a.attgenerated <> '' AS computed,
|
|
109
|
+
replace(format_type(a.atttypid, a.atttypmod), $1 || '.', '') AS formatted_type,
|
|
110
|
+
EXISTS (SELECT 1 FROM pg_index i WHERE i.indrelid = c.oid AND i.indisunique AND a.attnum = ANY (i.indkey)) AS keyed,
|
|
99
111
|
ARRAY(SELECT e.enumlabel::text FROM pg_enum e WHERE e.enumtypid = t.oid ORDER BY e.enumsortorder) AS enum_labels
|
|
100
112
|
FROM pg_attribute a
|
|
101
113
|
JOIN pg_class c ON c.oid = a.attrelid
|
|
@@ -186,19 +198,18 @@ function quote(value: string): string {
|
|
|
186
198
|
return `'${JSON.stringify(value).slice(1, -1).replaceAll('\\"', '"').replaceAll("'", "\\'")}'`
|
|
187
199
|
}
|
|
188
200
|
|
|
189
|
-
|
|
190
|
-
|
|
201
|
+
/** `table.column`: how a message names a column. */
|
|
202
|
+
export function columnPath(column: NamedColumn): string {
|
|
203
|
+
return `${column.table_name}.${column.column_name}`
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** The column's types, or `undefined` for a type the data layer does not read or bind. */
|
|
207
|
+
function scalarType(column: CatalogColumn): ScalarType | undefined {
|
|
191
208
|
if (column.type_type === 'e') {
|
|
192
|
-
if (column.enum_labels.length === 0) throw new CodegenError(`${
|
|
209
|
+
if (column.enum_labels.length === 0) throw new CodegenError(`${columnPath(column)}: enum ${column.type_name} has no labels`)
|
|
193
210
|
return { select: column.enum_labels.map(quote).join(' | ') }
|
|
194
211
|
}
|
|
195
|
-
|
|
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
|
|
212
|
+
return column.type_category === 'A' || column.type_type !== 'b' ? undefined : SCALAR_TYPES.get(column.type_name)
|
|
202
213
|
}
|
|
203
214
|
|
|
204
215
|
interface Rendered {
|
|
@@ -206,8 +217,93 @@ interface Rendered {
|
|
|
206
217
|
readonly uses: 'ColumnType' | 'Generated' | 'GeneratedAlways' | undefined
|
|
207
218
|
}
|
|
208
219
|
|
|
209
|
-
|
|
220
|
+
/** What the renderer needs of a column beyond its name, whichever database it was read from. */
|
|
221
|
+
export interface DescribedColumn {
|
|
222
|
+
readonly scalar: ScalarType
|
|
223
|
+
readonly nullable: boolean
|
|
224
|
+
readonly generated: 'no' | 'default' | 'always'
|
|
225
|
+
/** The column list field that names the column: a day, a timestamp, a JSON column, or (on SQLite) a boolean. */
|
|
226
|
+
readonly list: 'dates' | 'timestamps' | 'booleans' | 'json' | undefined
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** A column `describe` leaves out of the module: a generated column of a type the data layer does not read. */
|
|
230
|
+
export interface LeftOut {
|
|
231
|
+
/** The column's type, as its author wrote it. */
|
|
232
|
+
readonly leftOut: string
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** A column the module leaves out; only `ctx.sql` reaches it. */
|
|
236
|
+
export interface LeftOutColumn {
|
|
237
|
+
readonly table: string
|
|
238
|
+
readonly column: string
|
|
239
|
+
/** Its type, as its author wrote it. */
|
|
240
|
+
readonly type: string
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** 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`
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/** Why a left-out column refuses the schema: the table would lose a key, or a foreign key a column. */
|
|
249
|
+
export function leftOutRefusal(path: string, what: string): CodegenError {
|
|
250
|
+
return new CodegenError(`${path} is a generated column of a type the data layer does not read, so codegen leaves it out, but ${what}`)
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** The text of `SCHEMA_FILE`, and the columns it leaves out, for the command to name. */
|
|
254
|
+
export interface GeneratedModule {
|
|
255
|
+
readonly source: string
|
|
256
|
+
readonly leftOut: readonly LeftOutColumn[]
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
|
|
260
|
+
export interface ForeignKeyColumns {
|
|
261
|
+
readonly table_name: string
|
|
262
|
+
readonly columns: readonly string[]
|
|
263
|
+
readonly referenced_table: string
|
|
264
|
+
readonly referenced_columns: readonly string[]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** A column as the renderer groups it, before its type is described. */
|
|
268
|
+
export interface NamedColumn {
|
|
269
|
+
readonly table_name: string
|
|
270
|
+
readonly column_name: string
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* 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.
|
|
276
|
+
*/
|
|
277
|
+
function describePostgres(column: CatalogColumn): DescribedColumn | LeftOut {
|
|
210
278
|
const scalar = scalarType(column)
|
|
279
|
+
if (scalar === undefined) {
|
|
280
|
+
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 }
|
|
282
|
+
if (column.type_type === 'b' && column.type_name === 'json') {
|
|
283
|
+
throw new CodegenError(
|
|
284
|
+
`${columnPath(column)} has type json; declare it jsonb, which the data layer reads and binds (json keeps whitespace and duplicate keys)`,
|
|
285
|
+
)
|
|
286
|
+
}
|
|
287
|
+
throw new CodegenError(
|
|
288
|
+
`${columnPath(column)} has type ${column.type_name}, which the data layer does not read or bind (supported: ${
|
|
289
|
+
[...SCALAR_TYPES.keys()].join(', ')
|
|
290
|
+
}, enums)`,
|
|
291
|
+
)
|
|
292
|
+
}
|
|
293
|
+
const list = column.type_type !== 'b'
|
|
294
|
+
? undefined
|
|
295
|
+
: column.type_name === 'date'
|
|
296
|
+
? 'dates'
|
|
297
|
+
: column.type_name === 'timestamp' || column.type_name === 'timestamptz'
|
|
298
|
+
? 'timestamps'
|
|
299
|
+
: column.type_name === 'jsonb'
|
|
300
|
+
? 'json'
|
|
301
|
+
: undefined
|
|
302
|
+
return { scalar, nullable: column.nullable, generated: column.generated, list }
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function columnType(column: DescribedColumn): Rendered {
|
|
306
|
+
const { scalar } = column
|
|
211
307
|
const nullable = column.nullable ? ' | null' : ''
|
|
212
308
|
const select = `${scalar.select}${nullable}`
|
|
213
309
|
const write = scalar.write === undefined ? select : `${scalar.write}${nullable}`
|
|
@@ -222,11 +318,26 @@ function columnType(column: CatalogColumn): Rendered {
|
|
|
222
318
|
|
|
223
319
|
/**
|
|
224
320
|
* 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
|
|
226
|
-
* `fabrika db codegen --verify` can compare text.
|
|
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.
|
|
323
|
+
*/
|
|
324
|
+
export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
|
|
325
|
+
return renderTables(catalog, foreignKeys, describePostgres)
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* `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.
|
|
227
334
|
*/
|
|
228
|
-
export function
|
|
229
|
-
|
|
335
|
+
export function renderTables<C extends NamedColumn>(
|
|
336
|
+
catalog: readonly C[],
|
|
337
|
+
foreignKeys: readonly ForeignKeyColumns[],
|
|
338
|
+
describe: (column: C) => DescribedColumn | LeftOut,
|
|
339
|
+
): GeneratedModule {
|
|
340
|
+
const tables = new Map<string, C[]>()
|
|
230
341
|
for (const column of catalog) {
|
|
231
342
|
if (column.table_name.startsWith(FRAMEWORK_TABLE_PREFIX)) continue
|
|
232
343
|
for (const name of [column.table_name, column.column_name]) {
|
|
@@ -243,21 +354,49 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
|
|
|
243
354
|
const owners = new Map<string, string>()
|
|
244
355
|
const used = new Set<string>()
|
|
245
356
|
const interfaces: string[] = []
|
|
357
|
+
const described = new Map<C, DescribedColumn>()
|
|
358
|
+
const leftOut: LeftOutColumn[] = []
|
|
246
359
|
for (const table of names) {
|
|
247
360
|
const name = interfaceName(table)
|
|
248
361
|
const owner = owners.get(name)
|
|
249
362
|
if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
|
|
250
363
|
owners.set(name, table)
|
|
251
|
-
const
|
|
252
|
-
|
|
364
|
+
const kept: C[] = []
|
|
365
|
+
const fields: string[] = []
|
|
366
|
+
for (const column of tables.get(table) ?? []) {
|
|
367
|
+
const description = describe(column)
|
|
368
|
+
if ('leftOut' in description) {
|
|
369
|
+
const type = description.leftOut
|
|
370
|
+
leftOut.push({ table, column: column.column_name, type })
|
|
371
|
+
// 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`)
|
|
373
|
+
continue
|
|
374
|
+
}
|
|
375
|
+
kept.push(column)
|
|
376
|
+
described.set(column, description)
|
|
377
|
+
const rendered = columnType(description)
|
|
253
378
|
if (rendered.uses !== undefined) used.add(rendered.uses)
|
|
254
|
-
|
|
255
|
-
}
|
|
379
|
+
fields.push(`\t${column.column_name}: ${rendered.type}\n`)
|
|
380
|
+
}
|
|
381
|
+
if (kept.length === 0) {
|
|
382
|
+
throw new CodegenError(`table ${table} has only generated columns of types the data layer does not read, which codegen leaves out`)
|
|
383
|
+
}
|
|
384
|
+
tables.set(table, kept)
|
|
256
385
|
interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
|
|
257
386
|
}
|
|
387
|
+
const leftOutPaths = new Set(leftOut.map((column) => columnPath({ table_name: column.table, column_name: column.column })))
|
|
388
|
+
for (const key of foreignKeys) {
|
|
389
|
+
if (!tables.has(key.table_name) || !tables.has(key.referenced_table)) continue
|
|
390
|
+
const named = [
|
|
391
|
+
...key.columns.map((column) => columnPath({ table_name: key.table_name, column_name: column })),
|
|
392
|
+
...key.referenced_columns.map((column) => columnPath({ table_name: key.referenced_table, column_name: column })),
|
|
393
|
+
].find((path) => leftOutPaths.has(path))
|
|
394
|
+
if (named !== undefined) throw leftOutRefusal(named, `a foreign key of ${key.table_name} names it`)
|
|
395
|
+
}
|
|
258
396
|
const kyselyNames = ['ColumnType', 'Generated', 'GeneratedAlways'].filter((name) => used.has(name))
|
|
397
|
+
const json = [...described.values()].some((column) => column.list === 'json')
|
|
259
398
|
const imports = [
|
|
260
|
-
|
|
399
|
+
`import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
|
|
261
400
|
...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
|
|
262
401
|
]
|
|
263
402
|
const db = names.map((table) => `\t${table}: ${interfaceName(table)}\n`).join('')
|
|
@@ -271,14 +410,16 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
|
|
|
271
410
|
return `\t\tforeignKeys: [\n${rendered.join('')}\t\t],\n`
|
|
272
411
|
}
|
|
273
412
|
/**
|
|
274
|
-
* A table's columns
|
|
275
|
-
*
|
|
413
|
+
* A table's columns listed in `field`: the days, which the layer answers as `YYYY-MM-DD`, the timestamps, whose
|
|
414
|
+
* written text it checks, SQLite's booleans, which it reads from 0 or 1, and the JSON columns, whose written value
|
|
415
|
+
* it serializes. A table without one has no such field.
|
|
276
416
|
*/
|
|
277
|
-
const listOf = (table: string, field:
|
|
278
|
-
const listed = (tables.get(table) ?? []).filter((column) => column
|
|
417
|
+
const listOf = (table: string, field: DescribedColumn['list']): string => {
|
|
418
|
+
const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
|
|
279
419
|
return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
|
|
280
420
|
}
|
|
281
|
-
const datesOf = (table: string): string =>
|
|
421
|
+
const datesOf = (table: string): string =>
|
|
422
|
+
`${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}`
|
|
282
423
|
const columns = names
|
|
283
424
|
.map((table) =>
|
|
284
425
|
`\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
|
|
@@ -286,17 +427,18 @@ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: rea
|
|
|
286
427
|
}${datesOf(table)}\t},\n`
|
|
287
428
|
)
|
|
288
429
|
.join('')
|
|
289
|
-
|
|
430
|
+
const source = [
|
|
290
431
|
`${HEADER}\n`,
|
|
291
432
|
imports.join(''),
|
|
292
433
|
...interfaces,
|
|
293
434
|
`export interface DB {\n${db}}\n`,
|
|
294
435
|
`export const columns: TypedColumnList<DB> = {\n${columns}}\n`,
|
|
295
436
|
].join('\n')
|
|
437
|
+
return { source, leftOut }
|
|
296
438
|
}
|
|
297
439
|
|
|
298
440
|
/** 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<
|
|
441
|
+
export async function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule> {
|
|
300
442
|
const catalog = await introspectCatalog(url, schema, objects)
|
|
301
443
|
return renderSchema(catalog.columns, catalog.foreignKeys)
|
|
302
444
|
}
|