@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/src/json.ts ADDED
@@ -0,0 +1,124 @@
1
+ // JSON columns at the layer's boundary: `jsonb` on Postgres, a column declared `JSONB` on SQLite (the column list's
2
+ // `json`). A write takes a JSON value, checked and serialized here, and binds its text as one parameter: Postgres reads
3
+ // an untyped text parameter into `jsonb`, SQLite stores the text. A read answers the parsed value: `Bun.SQL` decodes
4
+ // `jsonb` itself, and `sqliteJson` parses SQLite's text. JS `null` is SQL NULL in both directions, so a top-level JSON
5
+ // `null` written by `ctx.sql` reads as `null` too. A JSON column is never compared, ordered, grouped or aggregated by
6
+ // the layer; a path condition is `ctx.sql`'s (`->>`).
7
+
8
+ import { hasOwn, isArray, OBJECT_PROTOTYPE, ownDescriptor, ownNames, ownSymbols, parseList, prototypeOf } from './builtins'
9
+ import { QueryRefusedError } from './errors'
10
+
11
+ const stringify = JSON.stringify
12
+ const parse = JSON.parse
13
+ const isFinite = Number.isFinite
14
+
15
+ /** A JSON value: what `JSON.parse` answers. An object member that is `undefined` is left out, as `JSON.stringify` does. */
16
+ export type JsonValue = string | number | boolean | null | readonly JsonValue[] | { readonly [key: string]: JsonValue | undefined }
17
+
18
+ /** What a JSON column takes: a JSON value other than a top-level `null`, which the layer writes as SQL NULL. */
19
+ export type JsonColumnValue = Exclude<JsonValue, null>
20
+
21
+ /** How deep a written value may nest; deeper is refused, and so is a value that contains itself. */
22
+ export const MAX_JSON_DEPTH = 64
23
+
24
+ function refusal(where: string, detail: string): QueryRefusedError {
25
+ return new QueryRefusedError('invalid_value', `${where} takes a JSON value (${detail})`)
26
+ }
27
+
28
+ /** Half of a surrogate pair, which Postgres refuses in `jsonb` text and SQLite would store. */
29
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/
30
+ const NUL = String.fromCharCode(0)
31
+
32
+ function text(value: string, where: string): string {
33
+ if (value.includes(NUL) || LONE_SURROGATE.test(value)) {
34
+ throw refusal(where, 'a string or key holds no NUL character and no lone surrogate')
35
+ }
36
+ return stringify(value)
37
+ }
38
+
39
+ function written(value: unknown, where: string, depth: number): string {
40
+ if (typeof value === 'string') {
41
+ return text(value, where)
42
+ }
43
+ if (value === null || typeof value === 'boolean') {
44
+ return stringify(value)
45
+ }
46
+ if (typeof value === 'number') {
47
+ if (!isFinite(value)) {
48
+ throw refusal(where, 'a number is finite')
49
+ }
50
+ return stringify(value)
51
+ }
52
+ if (typeof value !== 'object') {
53
+ throw refusal(where, `${typeof value} is not JSON`)
54
+ }
55
+ if (depth >= MAX_JSON_DEPTH) {
56
+ throw refusal(where, `nested at most ${MAX_JSON_DEPTH} deep, and never containing itself`)
57
+ }
58
+ if (isArray(value)) {
59
+ const items = parseList(value, (item) => {
60
+ if (item === undefined) {
61
+ throw refusal(where, 'an array holds no undefined')
62
+ }
63
+ return written(item, where, depth + 1)
64
+ })
65
+ if (items === undefined) {
66
+ throw refusal(where, 'an array is a plain array without holes or accessors')
67
+ }
68
+ let serialized = '['
69
+ for (let index = 0; index < items.length; index++) {
70
+ serialized += `${index === 0 ? '' : ','}${items[index] ?? ''}`
71
+ }
72
+ return `${serialized}]`
73
+ }
74
+ const prototype: unknown = prototypeOf(value)
75
+ if (prototype !== OBJECT_PROTOTYPE && prototype !== null) {
76
+ throw refusal(where, 'an object is a plain object, not an instance of a class such as a Date or a Map')
77
+ }
78
+ if (ownSymbols(value).length > 0) {
79
+ throw refusal(where, 'an object has string keys only')
80
+ }
81
+ const keys = ownNames(value)
82
+ let serialized = '{'
83
+ let first = true
84
+ for (let index = 0; index < keys.length; index++) {
85
+ const key = keys[index] ?? ''
86
+ const descriptor = ownDescriptor(value, key)
87
+ if (descriptor === undefined || !hasOwn(descriptor, 'value')) {
88
+ throw refusal(where, `${key} is an accessor`)
89
+ }
90
+ const member: unknown = descriptor.value
91
+ if (member === undefined) {
92
+ continue
93
+ }
94
+ serialized += `${first ? '' : ','}${text(key, where)}:${written(member, where, depth + 1)}`
95
+ first = false
96
+ }
97
+ return `${serialized}}`
98
+ }
99
+
100
+ /**
101
+ * A written JSON column value as the text the layer binds: plain objects and arrays, strings, finite numbers, booleans
102
+ * and nested `null`, read through own data properties only, so no `toJSON`, getter or method of the value runs.
103
+ */
104
+ export function jsonInput(value: unknown, where: string): string {
105
+ return written(value, where, 0)
106
+ }
107
+
108
+ /**
109
+ * A SQLite JSON column's stored value as Postgres's driver answers `jsonb`: its text parsed. A `JSONB` column has
110
+ * NUMERIC affinity, so a written number comes back as a number, which is that JSON value already.
111
+ */
112
+ export function sqliteJson(value: unknown, where: string): unknown {
113
+ if (typeof value === 'number') {
114
+ return value
115
+ }
116
+ if (typeof value === 'string') {
117
+ try {
118
+ return parse(value)
119
+ } catch {
120
+ // Fall through: the text is not JSON, which no write of the layer stores.
121
+ }
122
+ }
123
+ throw new QueryRefusedError('unexpected_row', `${where} came back as something other than JSON text, the form a JSON column is stored in on SQLite`)
124
+ }
package/src/orm-types.ts CHANGED
@@ -4,7 +4,7 @@
4
4
 
5
5
  import type { Selectable, Updateable } from 'kysely'
6
6
  import type { RowRef } from './capability'
7
- import type { ConditionTuple } from './description'
7
+ import type { ComparableColumn, ConditionTuple } from './description'
8
8
  import type { FileReference } from './file-references'
9
9
  import type {
10
10
  ActionOf,
@@ -240,7 +240,7 @@ type InsertValuesOf<E extends IndexedTable> = { [C in keyof E['insert']]: E['ins
240
240
 
241
241
  /** `onConflict` of an insert: the columns of a unique index the migrations create, and what a conflict does. */
242
242
  export interface InsertConflict<E extends IndexedTable, M extends 'nothing' | 'update'> {
243
- readonly onConflict: { readonly columns: readonly (keyof E['row'] & string)[]; readonly do: M }
243
+ readonly onConflict: { readonly columns: readonly ComparableColumn<E['row']>[]; readonly do: M }
244
244
  }
245
245
 
246
246
  /**
@@ -336,7 +336,7 @@ export interface ListPage<Row> {
336
336
  readonly next: string | null
337
337
  }
338
338
 
339
- export type OrderTerm<Row> = { [C in keyof Row & string]: readonly [C, 'asc' | 'desc'] }[keyof Row & string]
339
+ export type OrderTerm<Row> = { [C in ComparableColumn<Row>]: readonly [C, 'asc' | 'desc'] }[ComparableColumn<Row>]
340
340
 
341
341
  export interface ListOptions<Row> {
342
342
  readonly where?: readonly ConditionTuple<Row>[]
package/src/orm.ts CHANGED
@@ -9,7 +9,16 @@ import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
9
  import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
10
10
  import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
11
11
  import type { InvocationTransaction, Session } from './database'
12
- import { columnOf, type Compare, type Contains, parseCondition, type Primitive, type SelectState, type TableShape } from './description'
12
+ import {
13
+ columnOf,
14
+ comparableColumnOf,
15
+ type Compare,
16
+ type Contains,
17
+ parseCondition,
18
+ type Primitive,
19
+ type SelectState,
20
+ type TableShape,
21
+ } from './description'
13
22
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
14
23
  import { answerFiles, type FileBinding } from './file-columns'
15
24
  import { databaseNow } from './job-leases'
@@ -109,6 +118,11 @@ export interface DataSite {
109
118
  * only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
110
119
  */
111
120
  readonly files?: FileBinding
121
+ /**
122
+ * The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
123
+ * answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
124
+ */
125
+ readonly holds?: readonly string[]
112
126
  /** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
113
127
  readonly carried?: ReadonlySet<string>
114
128
  /** Throws unless the work running now is the invocation these handles were made for. */
@@ -827,7 +841,17 @@ async function claimRows(
827
841
  }
828
842
  await rearmClaim(runtime, session, fence, rearm)
829
843
  }
830
- return { rows: await answerFiles(model, site.files, session, answerRows(dialect, table, rowColumnsOf(model), rows), grant.action), claimed }
844
+ return {
845
+ rows: await answerFiles(
846
+ model,
847
+ site.files,
848
+ session,
849
+ answerRows(dialect, table, rowColumnsOf(model), rows),
850
+ grant.action,
851
+ nameSet(site.holds ?? []),
852
+ ),
853
+ claimed,
854
+ }
831
855
  })
832
856
  return leased.rows.map((row) => {
833
857
  const id = String(row[key])
@@ -1101,7 +1125,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
1101
1125
  if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
1102
1126
  throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
1103
1127
  }
1104
- return { column: columnOf(shape, parts[0]), direction }
1128
+ return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
1105
1129
  })
1106
1130
  if (terms === undefined) {
1107
1131
  throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
package/src/policy.ts CHANGED
@@ -162,6 +162,8 @@ export interface TableColumns<Col extends string = string, Table extends string
162
162
  readonly timestamps?: readonly Col[]
163
163
  /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
164
164
  readonly booleans?: readonly Col[]
165
+ /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
166
+ readonly json?: readonly Col[]
165
167
  }
166
168
 
167
169
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -225,6 +227,8 @@ export interface TableModel {
225
227
  readonly timestamps: NameSet
226
228
  /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
227
229
  readonly booleans: NameSet
230
+ /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
231
+ readonly json: NameSet
228
232
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
229
233
  readonly foreignKeys: readonly ForeignKey[]
230
234
  /**
@@ -346,7 +350,7 @@ function parseVocabulary(input: unknown): VocabularyModel {
346
350
  return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
347
351
  }
348
352
 
349
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans'])
353
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json'])
350
354
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
351
355
  const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
352
356
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
@@ -529,6 +533,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
529
533
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
530
534
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
531
535
  const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
536
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
532
537
  const queue = queueInput === undefined
533
538
  ? undefined
534
539
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -557,6 +562,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
557
562
  dates,
558
563
  timestamps,
559
564
  booleans,
565
+ json,
560
566
  foreignKeys,
561
567
  }
562
568
  }
@@ -679,7 +685,7 @@ function parseQueue(
679
685
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
680
686
  }
681
687
 
682
- /** The column list's `date` (`dates`), timestamp (`timestamps`) or boolean (`booleans`) columns, each one of the table's. */
688
+ /** The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`) or JSON (`json`) columns, each one of the table's. */
683
689
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
684
690
  if (input === undefined) {
685
691
  return nameSet([])
@@ -993,6 +999,9 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
993
999
  if (hasOwn(table.columnWrites, stamp.column)) {
994
1000
  throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
995
1001
  }
1002
+ if (inSet(table.json, stamp.column)) {
1003
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
1004
+ }
996
1005
  }
997
1006
  }
998
1007
 
package/src/sql.ts CHANGED
@@ -6,14 +6,16 @@
6
6
  // approver's to review, since the `sql:` declaration marks the site for a closer look (ADR-0012, ADR-0050).
7
7
 
8
8
  import {
9
- dmlForeignSchema,
9
+ CTE_FORM,
10
10
  frameworkReference,
11
11
  lexSql,
12
12
  lexSqlite,
13
13
  nameReferences,
14
14
  nestedStatement,
15
15
  parenthesizedTarget,
16
- refusedFunctionCall,
16
+ ReadSql,
17
+ referencedForeignSchema,
18
+ refusedCall,
17
19
  type SqlToken,
18
20
  statementKind,
19
21
  statementsOf,
@@ -285,7 +287,14 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
285
287
  }
286
288
  return statementText(parts, markerOf(database))
287
289
  }
288
- const nested = nestedStatement(tokens) ?? parenthesizedTarget(tokens)
290
+ const read = ReadSql.query(tokens)
291
+ if (read.ctes.unread !== undefined) {
292
+ refuse(
293
+ 'sql_statement',
294
+ `the WITH at line ${read.ctes.unread} begins a CTE list that cannot be read; write each CTE as ${CTE_FORM}, a CYCLE mark a constant and never an interpolated value`,
295
+ )
296
+ }
297
+ const nested = nestedStatement(read) ?? parenthesizedTarget(tokens)
289
298
  if (nested !== undefined) {
290
299
  refuse('sql_statement', `${nested.statement} at line ${nested.line} is refused inside another statement`)
291
300
  }
@@ -296,16 +305,17 @@ export function classifySql(parts: readonly string[], mode: SqlMode, database: S
296
305
  if (unicodeIdentifier(tokens) !== undefined) {
297
306
  refuse('sql_name', 'a U&"…" name is refused: write the name plainly')
298
307
  }
299
- for (const reference of nameReferences(tokens)) {
308
+ const references = nameReferences(read)
309
+ for (const reference of references) {
300
310
  if (reference.role !== 'call' && reference.name.startsWith('pg_')) {
301
311
  refuse('sql_name', `'${reference.name}' at line ${reference.line} is a catalog name; ctx.sql reaches only the application's own tables`)
302
312
  }
303
313
  }
304
- const foreign = dmlForeignSchema(tokens, database.schema)
314
+ const foreign = referencedForeignSchema(references, database.schema)
305
315
  if (foreign !== undefined) {
306
316
  refuse('sql_name', `the schema '${foreign}' is outside the application's; write its tables' names unqualified`)
307
317
  }
308
- const call = refusedFunctionCall(tokens, database.schema, NO_DECLARED_FUNCTIONS)
318
+ const call = refusedCall(references, database.schema, NO_DECLARED_FUNCTIONS)
309
319
  if (call !== undefined) {
310
320
  refuse(
311
321
  'sql_function',
package/src/store.ts CHANGED
@@ -34,6 +34,8 @@ import {
34
34
  } from './capability'
35
35
  import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
36
36
  import {
37
+ type ComparableColumn,
38
+ comparableColumnOf,
37
39
  type Compare,
38
40
  type Condition,
39
41
  type Contains,
@@ -54,6 +56,7 @@ import { webhookTables } from './framework-tables'
54
56
  import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
55
57
  import { fencedTransaction, jobLeases } from './job-leases'
56
58
  import { jobWakes, leaseProjection } from './job-wakes'
59
+ import { jsonInput } from './json'
57
60
  import { linksPredicate, type LinkValue, linkValues } from './links'
58
61
  import {
59
62
  acknowledgement,
@@ -145,7 +148,7 @@ export function dialectOf(context: TableContext): SqlDialect {
145
148
 
146
149
  /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
147
150
  export function rowColumnsOf(model: TableModel): RowColumns {
148
- return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans }
151
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans, json: model.json }
149
152
  }
150
153
 
151
154
  /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
@@ -1003,6 +1006,10 @@ export function readValues(values: unknown, allowed: NameSet, what: 'insert' | '
1003
1006
  copied.set(key, fileValue(model, key, value))
1004
1007
  continue
1005
1008
  }
1009
+ if (inSet(model.json, key)) {
1010
+ copied.set(key, value === null ? null : jsonInput(value, `${table}.${key}`))
1011
+ continue
1012
+ }
1006
1013
  if (value !== null && !isPrimitive(value)) {
1007
1014
  throw new QueryRefusedError('invalid_argument', `${table}.${key} takes a plain value (string, number, bigint, boolean, Date or null)`)
1008
1015
  }
@@ -1100,6 +1107,7 @@ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1100
1107
  days: joined((columns) => columns.days),
1101
1108
  timestamps: joined((columns) => columns.timestamps),
1102
1109
  booleans: joined((columns) => columns.booleans),
1110
+ json: joined((columns) => columns.json),
1103
1111
  }
1104
1112
  }
1105
1113
 
@@ -1266,6 +1274,10 @@ export function onConflictOf(
1266
1274
  if (!inSet(model.columns, name)) {
1267
1275
  throw new QueryRefusedError('on_conflict', `onConflict names ${String(name)}, which is not a column of ${model.name}`)
1268
1276
  }
1277
+ if (inSet(model.json, name)) {
1278
+ // jsonb compares by value and SQLite's text by spelling: the two dialects would disagree about a conflict.
1279
+ throw new QueryRefusedError('on_conflict', `onConflict names ${name}, a JSON column of ${model.name}, which the data layer never compares`)
1280
+ }
1269
1281
  return name
1270
1282
  })
1271
1283
  if (columns === undefined || columns.length === 0) {
@@ -1491,11 +1503,11 @@ type Columns<Row> = keyof Row & string
1491
1503
  type NumericColumn<Row> = { [K in Columns<Row>]: Exclude<Row[K], null> extends number | bigint | string ? K : never }[Columns<Row>]
1492
1504
 
1493
1505
  export interface AggregateSpec<Row> {
1494
- readonly groupBy?: readonly Columns<Row>[]
1506
+ readonly groupBy?: readonly ComparableColumn<Row>[]
1495
1507
  readonly count?: boolean
1496
1508
  readonly sum?: readonly NumericColumn<Row>[]
1497
- readonly min?: readonly Columns<Row>[]
1498
- readonly max?: readonly Columns<Row>[]
1509
+ readonly min?: readonly ComparableColumn<Row>[]
1510
+ readonly max?: readonly ComparableColumn<Row>[]
1499
1511
  readonly where?: (q: ScopedSelect<Row, Row, NoColumns>) => ScopedSelect<Row, unknown, NoColumns>
1500
1512
  }
1501
1513
 
@@ -1532,7 +1544,7 @@ function aggregateColumns(table: string, shape: TableShape, spec: AggregateInput
1532
1544
  if (!inSet(shape.visible, name)) {
1533
1545
  throw new QueryRefusedError('unknown_column', `${String(name)} is not a column of ${table} (columns: ${namesOf(shape.visible).join(', ')})`)
1534
1546
  }
1535
- return name
1547
+ return comparableColumnOf(shape, name, 'aggregates')
1536
1548
  })
1537
1549
  if (names === undefined) {
1538
1550
  throw new QueryRefusedError('invalid_argument', `aggregate ${field} takes a plain array of column names`)
@@ -1586,6 +1598,7 @@ export async function aggregateRows<Row, O>(
1586
1598
  days: aggregated(own.days, columns),
1587
1599
  timestamps: aggregated(own.timestamps, columns),
1588
1600
  booleans: aggregated(own.booleans, columns),
1601
+ json: nameSet([]),
1589
1602
  }, rows)
1590
1603
  return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
1591
1604
  }
@@ -1962,7 +1975,7 @@ function probeOf(context: TableContext): TableProbe {
1962
1975
  )
1963
1976
  },
1964
1977
  group: async (capability: unknown, columns: readonly string[]) =>
1965
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(
1978
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(
1966
1979
  context,
1967
1980
  run,
1968
1981
  list(capability, 'rows'),
@@ -2034,7 +2047,7 @@ function appProbeOf(context: TableContext): TableProbe {
2034
2047
  },
2035
2048
  count,
2036
2049
  group: async (capability: unknown, columns: readonly string[]) =>
2037
- aggregateRows<Readonly<Record<string, unknown>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
2050
+ aggregateRows<Readonly<Record<string, Primitive | null>>, Readonly<Record<string, unknown>>>(context, run, every(capability), context.shape, {
2038
2051
  groupBy: columns,
2039
2052
  count: true,
2040
2053
  }),
@@ -2068,11 +2081,11 @@ function destinationOf(models: TableModels, model: TableModel, parent: TableMode
2068
2081
 
2069
2082
  /** What a select or an aggregate of a capability that reads `visible` may name: those columns, and no join. */
2070
2083
  export function actionShape(model: TableModel, visible: readonly string[]): TableShape {
2071
- return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates })
2084
+ return freeze({ table: model.name, visible: nameSet(visible), joinable: freeze({}), dates: model.dates, json: model.json })
2072
2085
  }
2073
2086
 
2074
2087
  function shapeOf(model: TableModel, joinable: Readonly<Record<string, JoinShape>>): TableShape {
2075
- return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates })
2088
+ return freeze({ table: model.name, visible: nameSet(model.visible), joinable, dates: model.dates, json: model.json })
2076
2089
  }
2077
2090
 
2078
2091
  function joinShapes(models: TableModels, parent: TableModel): Readonly<Record<string, JoinShape>> {
package/src/temporal.ts CHANGED
@@ -12,6 +12,7 @@
12
12
  import { defineValue, inSet, type NameSet, ownDescriptor, ownKeys } from './builtins'
13
13
  import type { SqlDialect } from './database'
14
14
  import { QueryRefusedError } from './errors'
15
+ import { sqliteJson } from './json'
15
16
 
16
17
  /** The text Postgres prints for a day in 0001–9999 under its default `DateStyle` (ISO). */
17
18
  const DAY_TEXT = /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/
@@ -144,6 +145,8 @@ export interface RowColumns {
144
145
  readonly timestamps: NameSet
145
146
  /** Booleans: `true` or `false` (SQLite answers 1 or 0). */
146
147
  readonly booleans: NameSet
148
+ /** JSON columns: the parsed value (SQLite answers its text). */
149
+ readonly json: NameSet
147
150
  }
148
151
 
149
152
  function unexpected(where: string, expected: string): QueryRefusedError {
@@ -167,12 +170,16 @@ function sqliteValue(columns: RowColumns, where: string, key: string, value: unk
167
170
  }
168
171
  return value === 1
169
172
  }
173
+ if (inSet(columns.json, key)) {
174
+ return sqliteJson(value, where)
175
+ }
170
176
  return typeof value === 'string' && inSet(columns.days, key) ? dayText(value, where) : value
171
177
  }
172
178
 
173
179
  /**
174
180
  * Every row of a read as the layer answers it, in place: each day as `YYYY-MM-DD` text, and on SQLite each timestamp as
175
- * a `Date` and each boolean as `true` or `false`, so a handler reads the same values on both dialects.
181
+ * a `Date`, each boolean as `true` or `false` and each JSON column as its parsed value, so a handler reads the same
182
+ * values on both dialects.
176
183
  */
177
184
  export function answerRows<R>(dialect: SqlDialect, table: string, columns: RowColumns, rows: R[]): R[] {
178
185
  if (dialect === 'postgres') {