@fabrika/db 0.9.0-cloudflare.3 → 0.9.0-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-cloudflare.3",
3
+ "version": "0.9.0-dev.10",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -92,9 +92,9 @@
92
92
  "test": "bun test"
93
93
  },
94
94
  "dependencies": {
95
- "@fabrika/auth-core": "0.9.0-cloudflare.3",
96
- "@fabrika/platform": "0.9.0-cloudflare.3",
97
- "@fabrika/platform-node": "0.9.0-cloudflare.3",
95
+ "@fabrika/auth-core": "0.9.0-dev.10",
96
+ "@fabrika/platform": "0.9.0-dev.10",
97
+ "@fabrika/platform-node": "0.9.0-dev.10",
98
98
  "kysely": "0.29.6",
99
99
  "kysely-postgres-js": "5.0.1",
100
100
  "zod": "^3.25.76"
@@ -4,7 +4,19 @@
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 NamedColumn,
17
+ renderTables,
18
+ type ScalarType,
19
+ } from './codegen'
8
20
  import { execStatements } from './sqlite-bun'
9
21
  import { migrateSqlite, type SqliteMigrationBundle, type SqliteMigrationTarget } from './sqlite-migrate'
10
22
 
@@ -30,12 +42,17 @@ const DECLARED_TYPES: ReadonlyMap<string, { readonly scalar: ScalarType; readonl
30
42
  ['DATETIME', { scalar: { select: 'Date', write: 'Date | string' }, list: 'timestamps' }],
31
43
  ['DATE', { scalar: STRING, list: 'dates' }],
32
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' }],
33
47
  ])
34
48
 
35
49
  interface SqliteColumn extends NamedColumn {
36
50
  readonly declared: string
37
51
  readonly nullable: boolean
52
+ /** `always` is a column `GENERATED ALWAYS AS (…)` computes (`hidden` 2 or 3): SQLite has no identity column. */
38
53
  readonly generated: DescribedColumn['generated']
54
+ /** The column is in the primary key or in a unique index. */
55
+ readonly keyed: boolean
39
56
  }
40
57
 
41
58
  const tableSchema = z.object({ name: z.string(), type: z.string(), wr: z.number() })
@@ -63,14 +80,25 @@ function bunTarget(db: Database): SqliteMigrationTarget {
63
80
  }
64
81
  }
65
82
 
66
- function describeSqlite(column: SqliteColumn): DescribedColumn {
83
+ function describeSqlite(column: SqliteColumn): DescribedColumn | LeftOut {
67
84
  const base = column.declared.trim().toUpperCase().replace(/\s*\(.*\)$/s, '')
68
85
  const mapped = DECLARED_TYPES.get(base)
69
86
  if (mapped === undefined) {
87
+ const computed = column.generated === 'always'
88
+ if (computed && column.keyed) throw leftOutRefusal(columnPath(column), 'it is in the primary key or a unique key')
89
+ // A generated column without a declared type is one its author may mean to read: it is refused, not left out.
90
+ if (computed && base !== '') return { leftOut: column.declared.trim() }
91
+ if (base === 'JSON') {
92
+ throw new CodegenError(
93
+ `${
94
+ columnPath(column)
95
+ } has declared type '${column.declared}'; declare it JSONB, the name the data layer reads and binds as JSON, as Postgres's jsonb`,
96
+ )
97
+ }
70
98
  throw new CodegenError(
71
- `${column.table_name}.${column.column_name} has declared type '${column.declared}', which the data layer does not read or bind on SQLite (supported: ${
99
+ `${columnPath(column)} has declared type '${column.declared}', which the data layer does not read or bind on SQLite (supported: ${
72
100
  [...DECLARED_TYPES.keys()].join(', ')
73
- })`,
101
+ })${computed && base === '' ? '; declare the type of the generated column' : ''}`,
74
102
  )
75
103
  }
76
104
  return { scalar: mapped.scalar, nullable: column.nullable, generated: column.generated, list: mapped.list }
@@ -92,15 +120,22 @@ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: Forei
92
120
  if (table.type === 'virtual') throw new CodegenError(`table ${table.name} is a virtual table, which the data layer does not read`)
93
121
  const declared = z.array(columnSchema).parse(db.query('SELECT * FROM pragma_table_xinfo(?) ORDER BY cid').all(table.name))
94
122
  const keyColumns = declared.filter((column) => column.pk > 0)
123
+ const unique = new Set(
124
+ z.array(z.object({ name: z.string().nullable() })).parse(
125
+ db.query(`SELECT i.name FROM pragma_index_list(?1) l, pragma_index_info(l.name) i WHERE l."unique" = 1`).all(table.name),
126
+ ).map((column) => column.name),
127
+ )
95
128
  for (const column of declared) {
96
129
  // An INTEGER PRIMARY KEY of a rowid table is the rowid: never null, assigned when an insert omits it.
97
130
  const rowid = table.wr === 0 && keyColumns.length === 1 && column.pk === 1 && column.type.trim().toUpperCase() === 'INTEGER'
131
+ const computed = column.hidden === 2 || column.hidden === 3
98
132
  columns.push({
99
133
  table_name: table.name,
100
134
  column_name: column.name,
101
135
  declared: column.type,
102
136
  nullable: !rowid && column.notnull === 0,
103
- generated: column.hidden === 2 || column.hidden === 3 ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
137
+ generated: computed ? 'always' : rowid || column.dflt_value !== null ? 'default' : 'no',
138
+ keyed: column.pk > 0 || unique.has(column.name),
104
139
  })
105
140
  }
106
141
  const references = z.array(foreignKeySchema).parse(db.query('SELECT * FROM pragma_foreign_key_list(?) ORDER BY id DESC, seq').all(table.name))
@@ -133,13 +168,23 @@ function introspect(db: Database): { columns: SqliteColumn[]; foreignKeys: Forei
133
168
  * Applies `bundles` (the framework's `fabrika`, then the application's `app`) to a fresh in-memory database and renders
134
169
  * the module for `SCHEMA_FILE` from its application tables. Deterministic for given migrations.
135
170
  */
136
- export async function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<string> {
171
+ export function generateSqliteSchema(bundles: readonly SqliteMigrationBundle[]): Promise<GeneratedModule> {
172
+ return withMigratedSqlite(bundles, (db) => {
173
+ const { columns, foreignKeys } = introspect(db)
174
+ return renderTables(columns, foreignKeys, describeSqlite)
175
+ })
176
+ }
177
+
178
+ /**
179
+ * `read` of a fresh in-memory database with foreign keys enforced and `bundles` applied, as the Durable Object applies
180
+ * them; the database is closed after. `fabrika-check` plans the backup of an application's schema with it.
181
+ */
182
+ export async function withMigratedSqlite<T>(bundles: readonly SqliteMigrationBundle[], read: (db: Database) => T): Promise<T> {
137
183
  const db = new Database(':memory:')
138
184
  try {
139
185
  db.run('PRAGMA foreign_keys = ON')
140
186
  await migrateSqlite(bunTarget(db), bundles)
141
- const { columns, foreignKeys } = introspect(db)
142
- return renderTables(columns, foreignKeys, describeSqlite)
187
+ return read(db)
143
188
  } finally {
144
189
  db.close()
145
190
  }
package/src/codegen.ts CHANGED
@@ -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
- function scalarType(column: CatalogColumn): ScalarType {
190
- const where = `${column.table_name}.${column.column_name}`
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(`${where}: enum ${column.type_name} has no labels`)
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
- 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
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 {
@@ -211,8 +222,38 @@ export interface DescribedColumn {
211
222
  readonly scalar: ScalarType
212
223
  readonly nullable: boolean
213
224
  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
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[]
216
257
  }
217
258
 
218
259
  /** A foreign key as the renderer reads it: the columns of `table_name` that reference `referenced_table`. */
@@ -229,14 +270,34 @@ export interface NamedColumn {
229
270
  readonly column_name: string
230
271
  }
231
272
 
232
- function describePostgres(column: CatalogColumn): DescribedColumn {
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 {
233
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
+ }
234
293
  const list = column.type_type !== 'b'
235
294
  ? undefined
236
295
  : column.type_name === 'date'
237
296
  ? 'dates'
238
297
  : column.type_name === 'timestamp' || column.type_name === 'timestamptz'
239
298
  ? 'timestamps'
299
+ : column.type_name === 'jsonb'
300
+ ? 'json'
240
301
  : undefined
241
302
  return { scalar, nullable: column.nullable, generated: column.generated, list }
242
303
  }
@@ -257,22 +318,25 @@ function columnType(column: DescribedColumn): Rendered {
257
318
 
258
319
  /**
259
320
  * 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.
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.
262
323
  */
263
- export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): string {
324
+ export function renderSchema(catalog: readonly CatalogColumn[], foreignKeys: readonly CatalogForeignKey[] = []): GeneratedModule {
264
325
  return renderTables(catalog, foreignKeys, describePostgres)
265
326
  }
266
327
 
267
328
  /**
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.
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.
270
334
  */
271
335
  export function renderTables<C extends NamedColumn>(
272
336
  catalog: readonly C[],
273
337
  foreignKeys: readonly ForeignKeyColumns[],
274
- describe: (column: C) => DescribedColumn,
275
- ): string {
338
+ describe: (column: C) => DescribedColumn | LeftOut,
339
+ ): GeneratedModule {
276
340
  const tables = new Map<string, C[]>()
277
341
  for (const column of catalog) {
278
342
  if (column.table_name.startsWith(FRAMEWORK_TABLE_PREFIX)) continue
@@ -291,23 +355,48 @@ export function renderTables<C extends NamedColumn>(
291
355
  const used = new Set<string>()
292
356
  const interfaces: string[] = []
293
357
  const described = new Map<C, DescribedColumn>()
358
+ const leftOut: LeftOutColumn[] = []
294
359
  for (const table of names) {
295
360
  const name = interfaceName(table)
296
361
  const owner = owners.get(name)
297
362
  if (owner !== undefined) throw new CodegenError(`tables ${owner} and ${table} would both generate ${name}; rename one in a migration`)
298
363
  owners.set(name, table)
299
- const fields = (tables.get(table) ?? []).map((column) => {
364
+ const kept: C[] = []
365
+ const fields: string[] = []
366
+ for (const column of tables.get(table) ?? []) {
300
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)
301
376
  described.set(column, description)
302
377
  const rendered = columnType(description)
303
378
  if (rendered.uses !== undefined) used.add(rendered.uses)
304
- return `\t${column.column_name}: ${rendered.type}\n`
305
- })
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)
306
385
  interfaces.push(`export interface ${name} {\n${fields.join('')}}\n`)
307
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
+ }
308
396
  const kyselyNames = ['ColumnType', 'Generated', 'GeneratedAlways'].filter((name) => used.has(name))
397
+ const json = [...described.values()].some((column) => column.list === 'json')
309
398
  const imports = [
310
- "import type { TypedColumnList } from '@fabrika/db'\n",
399
+ `import type { ${json ? 'JsonColumnValue, ' : ''}TypedColumnList } from '@fabrika/db'\n`,
311
400
  ...(kyselyNames.length === 0 ? [] : [`import type { ${kyselyNames.join(', ')} } from 'kysely'\n`]),
312
401
  ]
313
402
  const db = names.map((table) => `\t${table}: ${interfaceName(table)}\n`).join('')
@@ -322,13 +411,15 @@ export function renderTables<C extends NamedColumn>(
322
411
  }
323
412
  /**
324
413
  * 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.
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.
326
416
  */
327
417
  const listOf = (table: string, field: DescribedColumn['list']): string => {
328
418
  const listed = (tables.get(table) ?? []).filter((column) => described.get(column)?.list === field)
329
419
  return listed.length === 0 ? '' : `\t\t${field}: [${listed.map((column) => quote(column.column_name)).join(', ')}],\n`
330
420
  }
331
- const datesOf = (table: string): string => `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}`
421
+ const datesOf = (table: string): string =>
422
+ `${listOf(table, 'dates')}${listOf(table, 'timestamps')}${listOf(table, 'booleans')}${listOf(table, 'json')}`
332
423
  const columns = names
333
424
  .map((table) =>
334
425
  `\t'${table}': {\n\t\tcolumns: [\n${(tables.get(table) ?? []).map((column) => `\t\t\t'${column.column_name}',\n`).join('')}\t\t],\n${
@@ -336,17 +427,18 @@ export function renderTables<C extends NamedColumn>(
336
427
  }${datesOf(table)}\t},\n`
337
428
  )
338
429
  .join('')
339
- return [
430
+ const source = [
340
431
  `${HEADER}\n`,
341
432
  imports.join(''),
342
433
  ...interfaces,
343
434
  `export interface DB {\n${db}}\n`,
344
435
  `export const columns: TypedColumnList<DB> = {\n${columns}}\n`,
345
436
  ].join('\n')
437
+ return { source, leftOut }
346
438
  }
347
439
 
348
440
  /** 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> {
441
+ export async function generateSchema(url: string, schema: string, objects: readonly DatabaseObject[]): Promise<GeneratedModule> {
350
442
  const catalog = await introspectCatalog(url, schema, objects)
351
443
  return renderSchema(catalog.columns, catalog.foreignKeys)
352
444
  }
@@ -59,6 +59,8 @@ export interface TableShape {
59
59
  readonly joinable: Readonly<Record<string, JoinShape>>
60
60
  /** The `date` columns, which a read answers as `YYYY-MM-DD` text. */
61
61
  readonly dates: NameSet
62
+ /** The JSON columns, which a query selects but never compares or orders by. */
63
+ readonly json: NameSet
62
64
  }
63
65
 
64
66
  export interface JoinShape {
@@ -88,14 +90,22 @@ export interface SelectState {
88
90
 
89
91
  type Comparable<V> = Exclude<V, null | undefined>
90
92
  type Columns<Row> = keyof Row & string
93
+ /** The columns a condition or an order may name: every column but a JSON one, whose read type is `unknown`. */
94
+ export type ComparableColumn<Row> = { [K in Columns<Row>]: unknown extends Row[K] ? never : K }[Columns<Row>]
91
95
  type StringColumn<Row> = { [K in Columns<Row>]: Comparable<Row[K]> extends string ? K : never }[Columns<Row>]
92
- type NullableColumn<Row> = { [K in Columns<Row>]: null extends Row[K] ? K : never }[Columns<Row>]
96
+ type NullableColumn<Row> = { [K in ComparableColumn<Row>]: null extends Row[K] ? K : never }[ComparableColumn<Row>]
93
97
 
98
+ /**
99
+ * A `[column, operator, value]` condition on `Row`'s columns. A null test (`is`, `is not`) takes a nullable column only;
100
+ * the runtime knows no column's nullability, so an untyped condition that tests a column never null runs and matches no
101
+ * row (`is`) or every row (`is not`).
102
+ */
94
103
  export type ConditionTuple<Row> =
95
104
  | {
96
- [K in Columns<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
97
- }[Columns<Row>]
105
+ [K in ComparableColumn<Row>]: readonly [K, ComparisonOperator, Comparable<Row[K]>] | readonly [K, ListOperator, readonly Comparable<Row[K]>[]]
106
+ }[ComparableColumn<Row>]
98
107
  | { [K in StringColumn<Row>]: readonly [K, PatternOperator | 'contains', string] }[StringColumn<Row>]
108
+ | { [K in NullableColumn<Row>]: readonly [K, NullOperator, null] }[NullableColumn<Row>]
99
109
 
100
110
  type Prefixed<C extends string, J> = { [K in keyof J & string as `${C}.${K}`]: J[K] }
101
111
  export type NoColumns = Record<never, never>
@@ -137,8 +147,12 @@ export class ScopedSelect<Row, Selected, Children> {
137
147
  return this.#next({ columns: names })
138
148
  }
139
149
 
140
- where<C extends Columns<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
141
- where<C extends Columns<Row>>(column: C, operator: ListOperator, values: readonly Comparable<Row[C]>[]): ScopedSelect<Row, Selected, Children>
150
+ where<C extends ComparableColumn<Row>>(column: C, operator: ComparisonOperator, value: Comparable<Row[C]>): ScopedSelect<Row, Selected, Children>
151
+ where<C extends ComparableColumn<Row>>(
152
+ column: C,
153
+ operator: ListOperator,
154
+ values: readonly Comparable<Row[C]>[],
155
+ ): ScopedSelect<Row, Selected, Children>
142
156
  where<C extends StringColumn<Row>>(column: C, operator: PatternOperator, pattern: string): ScopedSelect<Row, Selected, Children>
143
157
  where<C extends NullableColumn<Row>>(column: C, operator: NullOperator, value: null): ScopedSelect<Row, Selected, Children>
144
158
  where(column: string, operator: string, value: unknown): ScopedSelect<Row, Selected, Children> {
@@ -166,11 +180,11 @@ export class ScopedSelect<Row, Selected, Children> {
166
180
  return this.#withCondition(this.#parseCondition(column, 'contains', text))
167
181
  }
168
182
 
169
- orderBy(column: Columns<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
183
+ orderBy(column: ComparableColumn<Row>, direction: 'asc' | 'desc' = 'asc'): ScopedSelect<Row, Selected, Children> {
170
184
  if (direction !== 'asc' && direction !== 'desc') {
171
185
  throw new QueryRefusedError('list_page', `orderBy direction must be 'asc' or 'desc'`)
172
186
  }
173
- return this.#next({ orderBy: [...this.#state.orderBy, { column: this.#column(column), direction }] })
187
+ return this.#next({ orderBy: [...this.#state.orderBy, { column: comparableColumnOf(this.#shape, column, 'orders by'), direction }] })
174
188
  }
175
189
 
176
190
  limit(limit: number): ScopedSelect<Row, Selected, Children> {
@@ -233,9 +247,21 @@ export function columnOf(shape: TableShape, name: unknown): string {
233
247
  return name
234
248
  }
235
249
 
250
+ /** A column the shape lets a query compare, order or aggregate by: `columnOf`, and never a JSON column. */
251
+ export function comparableColumnOf(shape: TableShape, name: unknown, use: string): string {
252
+ const column = columnOf(shape, name)
253
+ if (inSet(shape.json, column)) {
254
+ throw new QueryRefusedError(
255
+ 'invalid_argument',
256
+ `${column} of ${shape.table} is a JSON column, which the data layer never ${use}; read a path of it with ctx.sql (->>)`,
257
+ )
258
+ }
259
+ return column
260
+ }
261
+
236
262
  /** One `[column, operator, value]` condition over a caller's values, checked before anything reads it further. */
237
263
  export function parseCondition(shape: TableShape, column: unknown, operator: unknown, value: unknown): Compare | Contains {
238
- const name = columnOf(shape, column)
264
+ const name = comparableColumnOf(shape, column, 'compares')
239
265
  if (operator === 'contains') {
240
266
  if (typeof value !== 'string') {
241
267
  throw new QueryRefusedError('invalid_argument', 'contains takes a string')
package/src/errors.ts CHANGED
@@ -29,11 +29,13 @@ export class CapabilityError extends Error {
29
29
 
30
30
  /**
31
31
  * Why the layer refused, as a closed catalog: a server log names the reason and its fixed text, never the message,
32
- * which can quote a value the request sent.
32
+ * which can quote a value the request sent. Each text is one string literal, however long: a concatenation keeps the
33
+ * whole catalog in an SPA bundle that imports this module (`web/__tests__/bundle.test.ts`).
33
34
  */
34
35
  export const QUERY_REFUSALS = {
35
36
  invalid_argument: 'a data-layer call took an argument of another shape than its type declares',
36
- invalid_value: 'a value cannot be bound: an invalid or out-of-range date, or a non-finite number',
37
+ invalid_value:
38
+ 'a value cannot be bound: undefined, a function, symbol or object of a kind the database does not bind, a list item other than a string or finite number, a date or timestamp that is neither a valid Date nor well-formed text or lies out of range, a non-finite number, or on SQLite a bigint outside the safe integer range',
37
39
  invalid_name: 'a configured name (application, schema, table or file column) breaks its naming rule',
38
40
  unknown_column: 'a column the table does not declare, or one this operation may not set',
39
41
  unknown_table: 'a table src/db/tables.ts does not declare, or one no store, join or locator reaches',
@@ -3,7 +3,7 @@
3
3
  // and claims, locks and stamps the file in the write's own transaction. The file's row is `fabrika_files`
4
4
  // (`stored-files.ts`); the column is a foreign key to it, so a file some row references is never deleted.
5
5
 
6
- import { defineValue, ownDescriptor, ownKeys } from './builtins'
6
+ import { defineValue, hasOwn, inSet, type NameSet, nameSet, ownDescriptor, ownKeys } from './builtins'
7
7
  import { runFixedStatement, type Session } from './database'
8
8
  import type { Primitive } from './description'
9
9
  import { NotFoundError, QueryRefusedError } from './errors'
@@ -24,17 +24,41 @@ export interface FileBinding {
24
24
  scans(kind: string): boolean
25
25
  }
26
26
 
27
- /** Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's read action. */
28
- function readsFile(model: TableModel, column: string, action: string): boolean {
29
- const own = Object.hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
30
- return own === undefined ? model.actions.read.includes(action) : own === action
27
+ /**
28
+ * Whether a reference read with `action` lets its holder serve, open and copy the file: the table's or the column's
29
+ * read action, or a table read action among `held`, the actions a job holds over the whole application. A column with
30
+ * its own read action is answered only under that action (`visibleFor`), so `held` never widens it.
31
+ */
32
+ function readsFile(model: TableModel, column: string, action: string, held: NameSet): boolean {
33
+ const own = hasOwn(model.columnReads, column) ? model.columnReads[column] : undefined
34
+ if (own !== undefined) {
35
+ return own === action
36
+ }
37
+ const reads = model.actions.read
38
+ for (let index = 0; index < reads.length; index++) {
39
+ const read = reads[index]
40
+ if (read === action || inSet(held, read)) {
41
+ return true
42
+ }
43
+ }
44
+ return false
31
45
  }
32
46
 
47
+ const NONE_HELD: NameSet = nameSet([])
48
+
33
49
  /**
34
50
  * Puts a file reference in each file column of `rows`, read with `action` in `session`: one statement loads every
35
- * file's metadata. Without a binding (a store's own runner) the columns keep their ids.
51
+ * file's metadata. Without a binding (a store's own runner) the columns keep their ids. `held` (a queue claim's) adds
52
+ * the actions the site holds over the whole application: a reference is readable when one of them reads the table.
36
53
  */
37
- export async function answerFiles<R>(model: TableModel, binding: FileBinding | undefined, session: Session, rows: R[], action: string): Promise<R[]> {
54
+ export async function answerFiles<R>(
55
+ model: TableModel,
56
+ binding: FileBinding | undefined,
57
+ session: Session,
58
+ rows: R[],
59
+ action: string,
60
+ held: NameSet = NONE_HELD,
61
+ ): Promise<R[]> {
38
62
  const columns = ownKeys(model.files)
39
63
  if (binding === undefined || columns.length === 0 || rows.length === 0) {
40
64
  return rows
@@ -62,7 +86,7 @@ export async function answerFiles<R>(model: TableModel, binding: FileBinding | u
62
86
  if (meta === undefined) {
63
87
  throw new QueryRefusedError('unexpected_row', `${model.name}.${column} references a file that is not stored`)
64
88
  }
65
- defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action)))
89
+ defineValue(row, column, fileReference(meta, binding.holder, readsFile(model, column, action, held)))
66
90
  }
67
91
  }
68
92
  return rows
package/src/index.ts CHANGED
@@ -45,6 +45,7 @@ export {
45
45
  type QueryRefusal,
46
46
  QueryRefusedError,
47
47
  } from './errors'
48
+ export type { JsonColumnValue, JsonValue } from './json'
48
49
  export type {
49
50
  AnyDbIndex,
50
51
  ChildRows,