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

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 (63) hide show
  1. package/package.json +34 -3
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/capability.ts +5 -0
  5. package/src/codegen-sqlite.ts +146 -0
  6. package/src/codegen.ts +59 -9
  7. package/src/database.ts +227 -61
  8. package/src/errors.ts +2 -2
  9. package/src/file-columns.ts +4 -1
  10. package/src/framework-tables.ts +28 -8
  11. package/src/framework.ts +14 -5
  12. package/src/guard.ts +8 -0
  13. package/src/index.ts +9 -1
  14. package/src/job-leases.ts +210 -54
  15. package/src/job-wakes.ts +450 -0
  16. package/src/links.ts +8 -1
  17. package/src/migrations-sqlite.ts +163 -0
  18. package/src/migrations.ts +25 -0
  19. package/src/nodes.ts +64 -9
  20. package/src/orm-types.ts +2 -2
  21. package/src/orm.ts +68 -35
  22. package/src/policy.ts +8 -2
  23. package/src/postgres.ts +26 -0
  24. package/src/registry.ts +11 -2
  25. package/src/sql.ts +216 -473
  26. package/src/sqlite-bun.ts +149 -0
  27. package/src/sqlite-migrate.ts +242 -0
  28. package/src/sqlite.ts +224 -0
  29. package/src/store.ts +362 -93
  30. package/src/stored-files.ts +188 -52
  31. package/src/tables.ts +16 -0
  32. package/src/temporal.ts +115 -9
  33. package/src/testing-shared.ts +733 -0
  34. package/src/testing-sqlite.ts +513 -0
  35. package/src/testing.ts +169 -482
  36. package/types/src/application-rows.d.ts +58 -0
  37. package/types/src/capability.d.ts +5 -0
  38. package/types/src/codegen-sqlite.d.ts +6 -0
  39. package/types/src/codegen.d.ts +30 -0
  40. package/types/src/database.d.ts +81 -20
  41. package/types/src/errors.d.ts +2 -2
  42. package/types/src/framework.d.ts +11 -5
  43. package/types/src/index.d.ts +1 -1
  44. package/types/src/job-leases.d.ts +32 -4
  45. package/types/src/job-wakes.d.ts +101 -0
  46. package/types/src/migrations-sqlite.d.ts +4 -0
  47. package/types/src/migrations.d.ts +1 -0
  48. package/types/src/nodes.d.ts +13 -2
  49. package/types/src/orm-types.d.ts +2 -2
  50. package/types/src/policy.d.ts +4 -0
  51. package/types/src/postgres.d.ts +12 -0
  52. package/types/src/registry.d.ts +10 -2
  53. package/types/src/sql.d.ts +29 -21
  54. package/types/src/sqlite-bun.d.ts +21 -0
  55. package/types/src/sqlite-migrate.d.ts +28 -0
  56. package/types/src/sqlite.d.ts +24 -0
  57. package/types/src/store.d.ts +26 -9
  58. package/types/src/stored-files.d.ts +6 -2
  59. package/types/src/tables.d.ts +10 -0
  60. package/types/src/temporal.d.ts +21 -0
  61. package/types/src/testing-shared.d.ts +201 -0
  62. package/types/src/testing-sqlite.d.ts +22 -0
  63. package/types/src/testing.d.ts +2 -93
package/src/store.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { uuidv7 } from '@fabrika/platform'
1
2
  import { BinaryOperationNode, type OperationNode, OperatorNode, type ReturningNode, ValueNode } from 'kysely'
2
3
  import { admissions } from './admissions'
3
4
  import {
@@ -31,8 +32,11 @@ import {
31
32
  type Within,
32
33
  type WithinGrant,
33
34
  } from './capability'
34
- import { type Database, InvocationTransaction, type Session, sessionOf } from './database'
35
+ import { type Database, InvocationTransaction, type Session, sessionOf, type SqlDialect } from './database'
35
36
  import {
37
+ type Compare,
38
+ type Condition,
39
+ type Contains,
36
40
  finishSelect,
37
41
  isPrimitive,
38
42
  type JoinShape,
@@ -49,7 +53,8 @@ import { fileReference } from './file-references'
49
53
  import { webhookTables } from './framework-tables'
50
54
  import type { ForeignKeyPair, GuardContext, RootKind } from './guard'
51
55
  import { fencedTransaction, jobLeases } from './job-leases'
52
- import { linksPredicate, linkValues } from './links'
56
+ import { jobWakes, leaseProjection } from './job-wakes'
57
+ import { linksPredicate, type LinkValue, linkValues } from './links'
53
58
  import {
54
59
  acknowledgement,
55
60
  acknowledgementNode,
@@ -93,23 +98,27 @@ import {
93
98
  type TableModels,
94
99
  tableModels,
95
100
  type Tables,
96
- updatableBy,
97
101
  updateActions,
98
102
  type UpdateValues,
99
103
  type VersionArguments,
100
104
  visibleFor,
101
105
  } from './policy'
102
- import { frameworkSideOf, type Locator, register } from './registry'
106
+ import { frameworkSideOf, type ProvisionalBinding, register } from './registry'
103
107
  import type { ScopeTerms, ScopeTest, ScopeUse } from './sql'
104
108
  import { storedFiles, storedFilesMetadata } from './stored-files'
105
109
  import { type TablePolicies, tablePolicies } from './tables'
106
- import { answerDays, dayInput, timestampInput } from './temporal'
110
+ import { answerRows, dayInput, type RowColumns, storedTimestamp, timestampInput } from './temporal'
107
111
 
108
112
  export interface DataLayerRuntime {
109
113
  readonly database: Database
110
114
  readonly capabilities: CapabilityAuthority
111
115
  /** Whether the request running now may only read (an export's); its every statement then runs `READ ONLY`. */
112
116
  readonly readOnly?: () => boolean
117
+ /**
118
+ * Runs inside the transaction of every change of a job's wakes or lease, after the change: the Cloudflare driver arms
119
+ * the alarm from `wakes.next(transaction)` there, so the alarm commits with the change. A throw rolls the change back.
120
+ */
121
+ readonly projectWakes?: (transaction: Session) => Promise<void>
113
122
  }
114
123
 
115
124
  /** Empty until the framework connects the layer at boot; every table handle of one `scoped` call shares it. */
@@ -124,9 +133,86 @@ export interface TableContext {
124
133
  readonly destination: TableModel | undefined
125
134
  readonly shape: TableShape
126
135
  readonly joins: Readonly<Record<string, readonly ForeignKeyPair[]>>
136
+ /** The model of each child a select may join, by its table name. */
137
+ readonly children: Readonly<Record<string, TableModel>>
127
138
  readonly connection: Connection
128
139
  }
129
140
 
141
+ /** The dialect of the database the layer is bound to: what a read answers and a write binds depends on it. */
142
+ export function dialectOf(context: TableContext): SqlDialect {
143
+ return runtimeOf(context.connection).database.dialect
144
+ }
145
+
146
+ /** The columns of `model`'s own rows that a read answers in a form of its own (`answerRows`). */
147
+ export function rowColumnsOf(model: TableModel): RowColumns {
148
+ return { days: model.dates, timestamps: model.timestamps, booleans: model.booleans }
149
+ }
150
+
151
+ /** A timestamp's bound value on SQLite: its stored UTC text. Postgres takes a `Date` or ISO text as it is. */
152
+ function boundTimestamp(model: TableModel, column: string, value: Primitive): Primitive {
153
+ if (typeof value !== 'string' && !(value instanceof Date)) {
154
+ throw new QueryRefusedError('invalid_value', `${model.name}.${column} takes a Date or ISO 8601 text with Z or an offset`)
155
+ }
156
+ return storedTimestamp(value, `${model.name}.${column}`)
157
+ }
158
+
159
+ /** The values a write binds: on SQLite each timestamp as its stored UTC text, so text order is time order. */
160
+ export function boundValues(context: TableContext, values: ReadonlyMap<string, Primitive | null>): ReadonlyMap<string, Primitive | null> {
161
+ const model = context.model
162
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
163
+ return values
164
+ }
165
+ const bound = new Map<string, Primitive | null>()
166
+ for (const [name, value] of values) {
167
+ bound.set(name, value === null || !inSet(model.timestamps, name) ? value : boundTimestamp(model, name, value))
168
+ }
169
+ return bound
170
+ }
171
+
172
+ /** A term's values as they are bound: on SQLite, one over a timestamp of `model` compares stored UTC text. */
173
+ function boundTerm(model: TableModel, term: Compare | Contains): Compare | Contains {
174
+ const value = term.kind === 'compare' ? term.value : null
175
+ if (term.kind !== 'compare' || value === null || !inSet(model.timestamps, term.column)) {
176
+ return term
177
+ }
178
+ const bind = (item: Primitive): Primitive => boundTimestamp(model, term.column, item)
179
+ return { ...term, value: isList(value) ? value.map(bind) : bind(value) }
180
+ }
181
+
182
+ function isList(value: Primitive | readonly Primitive[]): value is readonly Primitive[] {
183
+ return isArray(value)
184
+ }
185
+
186
+ /** A list's terms over `model`'s columns, as `boundTerm` binds each. */
187
+ export function boundTerms(context: TableContext, model: TableModel, terms: readonly (Compare | Contains)[]): readonly (Compare | Contains)[] {
188
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
189
+ return terms
190
+ }
191
+ return terms.map((term) => boundTerm(model, term))
192
+ }
193
+
194
+ /** A description's conditions over `model`'s columns, an OR group's terms included, as `boundTerm` binds each. */
195
+ function boundConditions(context: TableContext, model: TableModel, conditions: readonly Condition[]): readonly Condition[] {
196
+ if (dialectOf(context) === 'postgres' || ownKeys(model.timestamps).length === 0) {
197
+ return conditions
198
+ }
199
+ return conditions.map((condition) =>
200
+ condition.kind === 'any' ? { ...condition, conditions: condition.conditions.map((term) => boundTerm(model, term)) } : boundTerm(model, condition)
201
+ )
202
+ }
203
+
204
+ /** A select's conditions, its joined children's included, as they are bound. */
205
+ function boundState(context: TableContext, state: SelectState): SelectState {
206
+ if (dialectOf(context) === 'postgres') {
207
+ return state
208
+ }
209
+ const joins = state.joins.map((join) => {
210
+ const child = ownEntry(context.children, join.join.shape.table)
211
+ return child === undefined ? join : { ...join, select: { ...join.select, conditions: boundConditions(context, child, join.select.conditions) } }
212
+ })
213
+ return { ...state, conditions: boundConditions(context, context.model, state.conditions), joins }
214
+ }
215
+
130
216
  export function runtimeOf(connection: Connection): DataLayerRuntime {
131
217
  const runtime = connection.runtime
132
218
  if (runtime === undefined) {
@@ -227,6 +313,76 @@ function linksAbove(model: TableModel, dimension: string): readonly Container[]
227
313
  return []
228
314
  }
229
315
 
316
+ /**
317
+ * The links of a row that lie inside the `Within`'s own dimension: the object itself for a dimension table, and the
318
+ * chain links nearer than `dimension`. A grant on one of them admits the row as a single-object read admits it.
319
+ */
320
+ function linksBelow(model: TableModel, dimension: string): readonly Container[] {
321
+ const links = model.scope.mode === 'dimension' ? selfLinks(model) : model.chain
322
+ const below: Container[] = []
323
+ for (let index = 0; index < links.length; index++) {
324
+ const link = links[index]
325
+ if (link === undefined || link.dimension === dimension) {
326
+ return below
327
+ }
328
+ below[below.length] = link
329
+ }
330
+ return []
331
+ }
332
+
333
+ /**
334
+ * One `<column> in (values)` per contained grant on a link of the row inside the `Within`'s dimension. A grant on a
335
+ * dimension the table carries no link of admits none of its rows; one on the `Within`'s dimension or above it is refused.
336
+ */
337
+ function containedTests(model: TableModel, grant: WithinGrant): { readonly column: string; readonly values: readonly string[] }[] {
338
+ const below = linksBelow(model, grant.dimension)
339
+ const above = linksAbove(model, grant.dimension)
340
+ const tests: { readonly column: string; readonly values: readonly string[] }[] = []
341
+ for (let index = 0; index < grant.contained.length; index++) {
342
+ const contained = grant.contained[index]
343
+ if (contained === undefined) {
344
+ continue
345
+ }
346
+ if (contained.dimension === grant.dimension || linkOf(above, contained.dimension) !== undefined) {
347
+ throw new CapabilityError(
348
+ 'unenforceable',
349
+ `the Within of ${grant.dimension} carries a grant on ${contained.dimension}, which does not lie inside ${grant.dimension} in ${model.name}`,
350
+ )
351
+ }
352
+ const link = linkOf(below, contained.dimension)
353
+ if (link !== undefined && contained.values.length > 0) {
354
+ tests[tests.length] = { column: link.column, values: contained.values }
355
+ }
356
+ }
357
+ return tests
358
+ }
359
+
360
+ /** The link of `dimension` among `links`, by an index loop: no array method an application could replace. */
361
+ function linkOf(links: readonly Container[], dimension: string): Container | undefined {
362
+ for (let index = 0; index < links.length; index++) {
363
+ const link = links[index]
364
+ if (link !== undefined && link.dimension === dimension) {
365
+ return link
366
+ }
367
+ }
368
+ return undefined
369
+ }
370
+
371
+ /** Every scope value a `Within` carries: its own, its containers' and its contained dimensions'. */
372
+ function withinCount(grant: WithinGrant): number {
373
+ if (grant.values === 'all') {
374
+ return 0
375
+ }
376
+ let count = grant.values.length
377
+ for (let index = 0; index < grant.containers.length; index++) {
378
+ count += grant.containers[index]?.values.length ?? 0
379
+ }
380
+ for (let index = 0; index < grant.contained.length; index++) {
381
+ count += grant.contained[index]?.values.length ?? 0
382
+ }
383
+ return count
384
+ }
385
+
230
386
  /**
231
387
  * `column in (values) or <container column> in (container values) …`, one disjunct per container dimension, so
232
388
  * the statement itself judges each row by the chain it carries now. Undefined for an empty `Within`: the caller
@@ -238,7 +394,7 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
238
394
  }
239
395
  const above = linksAbove(model, grant.dimension)
240
396
  const predicates: OperationNode[] = []
241
- let count = grant.values.length
397
+ const count = withinCount(grant)
242
398
  if (grant.values.length > 0) {
243
399
  predicates[predicates.length] = inList(model.name, column, grant.values)
244
400
  }
@@ -247,23 +403,24 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
247
403
  if (container === undefined) {
248
404
  continue
249
405
  }
250
- let link: Container | undefined
251
- for (let position = 0; position < above.length; position++) {
252
- if (above[position]?.dimension === container.dimension) {
253
- link = above[position]
254
- }
255
- }
406
+ const link = linkOf(above, container.dimension)
256
407
  if (link === undefined) {
257
408
  throw new CapabilityError(
258
409
  'unenforceable',
259
410
  `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${model.name} carries no column for above ${grant.dimension}; the layer cannot enforce it`,
260
411
  )
261
412
  }
262
- count += container.values.length
263
413
  if (container.values.length > 0) {
264
414
  predicates[predicates.length] = inList(model.name, link.column, container.values)
265
415
  }
266
416
  }
417
+ const contained = containedTests(model, grant)
418
+ for (let index = 0; index < contained.length; index++) {
419
+ const test = contained[index]
420
+ if (test !== undefined) {
421
+ predicates[predicates.length] = inList(model.name, test.column, test.values)
422
+ }
423
+ }
267
424
  if (count > MAX_WITHIN_VALUES) {
268
425
  throw new CapabilityError('within_size', `a Within carries at most ${MAX_WITHIN_VALUES} scope values; this one carries ${count}`)
269
426
  }
@@ -273,7 +430,14 @@ function withinPredicate(model: TableModel, column: string, grant: WithinGrant):
273
430
  /** The object a Ref of the model's own dimension names, with every link of its chain. */
274
431
  export function selfLinks(model: TableModel): readonly Container[] {
275
432
  const scope = dimensionScope(model)
276
- return [{ dimension: scope.dimension, column: scope.key }, ...model.chain]
433
+ const links: Container[] = [{ dimension: scope.dimension, column: scope.key }]
434
+ for (let index = 0; index < model.chain.length; index++) {
435
+ const link = model.chain[index]
436
+ if (link !== undefined) {
437
+ links[links.length] = link
438
+ }
439
+ }
440
+ return links
277
441
  }
278
442
 
279
443
  /** This object, over the whole chain the Ref carries. */
@@ -348,12 +512,12 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
348
512
  }
349
513
 
350
514
  /**
351
- * A fragment on an UPDATE or DELETE target: the capability's action is that operation's, and an application table is
352
- * written by an `app` capability only, a dimension or child table never by one. An UPDATE may instead hold a column's
353
- * own write action when every column it assigns declares that action (`updatingRef`'s rule); `assigned` is
354
- * `undefined` before the statement is known, and then any such action is taken.
515
+ * A fragment its author marks as an UPDATE or DELETE target: the capability's action is that operation's, and an
516
+ * application table is written by an `app` capability only, a dimension or child table never by one. An UPDATE may
517
+ * instead hold a column's own write action; which columns the statement sets is the author's and the approver's to
518
+ * keep to that action's (`updatableBy`), as the statement is not read for it.
355
519
  */
356
- function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete', assigned: readonly string[] | undefined): void {
520
+ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'update' | 'delete'): void {
357
521
  const model = context.model
358
522
  const statement = `${use === 'update' ? 'UPDATE' : 'DELETE'} of ${model.name}`
359
523
  if (grant.kind === 'app' && model.scope.mode !== 'app') {
@@ -380,42 +544,26 @@ function checkWriteTarget(context: TableContext, grant: CapabilityGrant, use: 'u
380
544
  if (columnWrites.length > 0) needs[needs.length] = `a column's own write action (${columnWrites.join(', ')})`
381
545
  throw new CapabilityError('wrong_action', `${statement} needs ${needs.join(' or ')}; the capability holds ${grant.action}`)
382
546
  }
383
- if (assigned === undefined) {
384
- return
385
- }
386
- const written = updatableBy(model, grant.action)
387
- const outside: string[] = assigned.length === 0 ? ['no column it can name'] : []
388
- for (let index = 0; index < assigned.length; index++) {
389
- const column = assigned[index]
390
- if (column !== undefined && !inSet(written, column)) outside[outside.length] = column
391
- }
392
- if (outside.length > 0) {
393
- throw new CapabilityError(
394
- 'wrong_action',
395
- `${statement} assigns ${
396
- outside.join(', ')
397
- }, which ${grant.action} does not write: a column's own write action scopes an UPDATE of its columns only`,
398
- )
399
- }
400
547
  }
401
548
 
402
549
  /**
403
550
  * `ctx.sql.scope`'s predicate: what the handles of `capability` match in the table for `use`, as column tests. A
404
551
  * fragment that reads (`'read'`) needs an action the handles read the table with: any action it names for a `Ref`,
405
552
  * its read action for a `Within`, an action `ctx.db.app` lists it for with an `app` capability, and its read action
406
- * for a scoped site's read of an application table. A fragment on the statement's UPDATE or DELETE target needs that
407
- * operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's column
408
- * and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container grant on
409
- * its own column, or every row for `all`); an `app` capability, and a scoped read of an application table, every row.
553
+ * for a scoped site's read of an application table. A fragment its author marks `use: 'update'` or `'delete'` needs
554
+ * that operation's own action, and an `app` capability writes application tables only. A `Ref` matches its object's
555
+ * column and every link of the chain it carries; a `Within` matches like `ctx.db.within` (its values, each container
556
+ * grant on its own column, or every row for `all`); an `app` capability, and a scoped read of an application table,
557
+ * every row.
410
558
  */
411
- export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse, assigned?: readonly string[]): ScopeTerms {
559
+ export function scopeTerms(context: TableContext, capability: unknown, use: ScopeUse): ScopeTerms {
412
560
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
413
561
  const model = context.model
414
562
  if (grant.kind === 'row') {
415
563
  throw new CapabilityError('wrong_capability', `ctx.sql.scope takes a Ref, a Within or an app capability, got ${describeGrant(grant)}`)
416
564
  }
417
565
  if (use !== 'read') {
418
- checkWriteTarget(context, grant, use, assigned)
566
+ checkWriteTarget(context, grant, use)
419
567
  }
420
568
  if (grant.kind === 'app') {
421
569
  if (use === 'read') {
@@ -443,7 +591,22 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
443
591
  if (use === 'read' && !namesAction(model, grant.action)) {
444
592
  throw new CapabilityError('wrong_action', `${model.name} does not name the action ${grant.action}: a Ref reads it with an action it names`)
445
593
  }
446
- return [linkValues(model.name, links.slice(start), grant).map(({ link, value }) => ({ column: link.column, value }))]
594
+ const reached: Container[] = []
595
+ for (let index = start; index < links.length; index++) {
596
+ const link = links[index]
597
+ if (link !== undefined) {
598
+ reached[reached.length] = link
599
+ }
600
+ }
601
+ const values = linkValues(model.name, reached, grant)
602
+ const tests: ScopeTest[] = []
603
+ for (let index = 0; index < values.length; index++) {
604
+ const entry = values[index]
605
+ if (entry !== undefined) {
606
+ tests[tests.length] = { column: entry.link.column, value: entry.value }
607
+ }
608
+ }
609
+ return [tests]
447
610
  }
448
611
  const column = reachColumn(model, grant.dimension)
449
612
  if (column === undefined) {
@@ -463,21 +626,31 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
463
626
  }
464
627
  const above = linksAbove(model, grant.dimension)
465
628
  const groups: ScopeTest[][] = []
466
- let count = grant.values.length
629
+ const count = withinCount(grant)
467
630
  if (grant.values.length > 0) {
468
- groups.push([{ column, value: grant.values }])
631
+ groups[groups.length] = [{ column, value: grant.values }]
469
632
  }
470
- for (const container of grant.containers) {
471
- const link = above.find((candidate) => candidate.dimension === container.dimension)
633
+ for (let index = 0; index < grant.containers.length; index++) {
634
+ const container = grant.containers[index]
635
+ if (container === undefined) {
636
+ continue
637
+ }
638
+ const link = linkOf(above, container.dimension)
472
639
  if (link === undefined) {
473
640
  throw new CapabilityError(
474
641
  'unenforceable',
475
642
  `the Within of ${grant.dimension} reaches through ${container.dimension}, which ${model.name} carries no column for above ${grant.dimension}; the layer cannot enforce it`,
476
643
  )
477
644
  }
478
- count += container.values.length
479
645
  if (container.values.length > 0) {
480
- groups.push([{ column: link.column, value: container.values }])
646
+ groups[groups.length] = [{ column: link.column, value: container.values }]
647
+ }
648
+ }
649
+ const contained = containedTests(model, grant)
650
+ for (let index = 0; index < contained.length; index++) {
651
+ const test = contained[index]
652
+ if (test !== undefined) {
653
+ groups[groups.length] = [{ column: test.column, value: test.values }]
481
654
  }
482
655
  }
483
656
  if (count > MAX_WITHIN_VALUES) {
@@ -895,29 +1068,39 @@ async function selectRows<S>(
895
1068
  if (scope === undefined) {
896
1069
  return []
897
1070
  }
898
- const node = selectNode(state, visible, scope, undefined, context.model.dates)
1071
+ const dialect = dialectOf(context)
1072
+ const node = selectNode(boundState(context, state), visible, scope, undefined, context.model.dates, dialect)
899
1073
  const rows = await (await run.read()).run<S>(node, guard(context, 'SelectQueryNode', scope))
900
- return answerDays(context.model.name, joinedDays(context.model.dates, state), rows)
1074
+ return answerRows(dialect, context.model.name, joinedColumns(context, state), rows)
901
1075
  }
902
1076
 
903
- /** The `date` columns of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
904
- function joinedDays(own: NameSet, state: SelectState): NameSet {
1077
+ /** The column sets of a select's rows: the table's own, and each joined child's under its `<child>.<column>` alias. */
1078
+ function joinedColumns(context: TableContext, state: SelectState): RowColumns {
1079
+ const own = rowColumnsOf(context.model)
905
1080
  if (state.joins.length === 0) {
906
1081
  return own
907
1082
  }
908
- const names: string[] = []
909
- const ownDates = namesOf(own)
910
- for (let index = 0; index < ownDates.length; index++) {
911
- names[names.length] = ownDates[index] ?? ''
912
- }
913
- for (let index = 0; index < state.joins.length; index++) {
914
- const shape = state.joins[index]?.join.shape
915
- const dates = shape === undefined ? [] : namesOf(shape.dates)
916
- for (let position = 0; position < dates.length; position++) {
917
- names[names.length] = `${shape?.table}.${dates[position]}`
1083
+ const joined = (pick: (columns: RowColumns) => NameSet): NameSet => {
1084
+ const names: string[] = []
1085
+ const owned = namesOf(pick(own))
1086
+ for (let index = 0; index < owned.length; index++) {
1087
+ names[names.length] = owned[index] ?? ''
1088
+ }
1089
+ for (let index = 0; index < state.joins.length; index++) {
1090
+ const table = state.joins[index]?.join.shape.table ?? ''
1091
+ const child = ownEntry(context.children, table)
1092
+ const columns = child === undefined ? [] : namesOf(pick(rowColumnsOf(child)))
1093
+ for (let position = 0; position < columns.length; position++) {
1094
+ names[names.length] = `${table}.${columns[position]}`
1095
+ }
918
1096
  }
1097
+ return nameSet(names)
1098
+ }
1099
+ return {
1100
+ days: joined((columns) => columns.days),
1101
+ timestamps: joined((columns) => columns.timestamps),
1102
+ booleans: joined((columns) => columns.booleans),
919
1103
  }
920
- return nameSet(names)
921
1104
  }
922
1105
 
923
1106
  /**
@@ -933,10 +1116,11 @@ export async function selectOne<O>(
933
1116
  ): Promise<O> {
934
1117
  const start = startSelect(context.shape)
935
1118
  const state = finishSelect(start, start)
936
- const node = selectNode(state, visible, scope, undefined, context.model.dates)
1119
+ const dialect = dialectOf(context)
1120
+ const node = selectNode(state, visible, scope, undefined, context.model.dates, dialect)
937
1121
  const session = await run.read()
938
1122
  const rows = await session.run<O>(node, guard(context, 'SelectQueryNode', scope))
939
- const [row] = answerDays(context.model.name, context.model.dates, rows)
1123
+ const [row] = answerRows(dialect, context.model.name, rowColumnsOf(context.model), rows)
940
1124
  if (row === undefined) {
941
1125
  throw new NotFoundError(`${context.model.name} not found`)
942
1126
  }
@@ -1027,9 +1211,10 @@ async function lockDestination(transaction: Session, context: TableContext, gran
1027
1211
  export async function insertRow<O>(
1028
1212
  context: TableContext,
1029
1213
  run: Runner,
1030
- values: ReadonlyMap<string, Primitive | null>,
1214
+ given: ReadonlyMap<string, Primitive | null>,
1031
1215
  destination: RefGrant | undefined,
1032
1216
  ): Promise<O> {
1217
+ const values = boundValues(context, given)
1033
1218
  return run.write(async (transaction) => {
1034
1219
  if (destination !== undefined) {
1035
1220
  await lockDestination(transaction, context, destination)
@@ -1172,10 +1357,12 @@ async function insertOnConflict(
1172
1357
  context: TableContext,
1173
1358
  run: Runner,
1174
1359
  transaction: Session,
1175
- values: ReadonlyMap<string, Primitive | null>,
1360
+ given: ReadonlyMap<string, Primitive | null>,
1176
1361
  conflict: OnConflict,
1177
1362
  ): Promise<Readonly<Record<string, unknown>>> {
1178
1363
  const model = context.model
1364
+ const values = boundValues(context, given)
1365
+ const updates = boundValues(context, conflict.updates)
1179
1366
  const matches: OperationNode[] = []
1180
1367
  for (let index = 0; index < conflict.columns.length; index++) {
1181
1368
  const name = conflict.columns[index] ?? ''
@@ -1201,17 +1388,17 @@ async function insertOnConflict(
1201
1388
  return { inserted: false }
1202
1389
  }
1203
1390
  const where = scopedWhere(allOf(matches), scope)
1204
- const unchanged = conflict.updates.size === 0
1391
+ const unchanged = updates.size === 0
1205
1392
  const update = unchanged
1206
1393
  ? acknowledgementNode(model.name, keyOf(model), model.version, where)
1207
- : updateNode(model.name, conflict.updates, model.version, where, answer(context))
1394
+ : updateNode(model.name, updates, model.version, where, answer(context))
1208
1395
  const [updated] = await transaction.run<Readonly<Record<string, unknown>>>(
1209
1396
  update,
1210
1397
  guard(context, unchanged ? 'SelectQueryNode' : 'UpdateQueryNode', scope),
1211
1398
  )
1212
1399
  if (updated !== undefined) {
1213
1400
  checkVersion(context, updated)
1214
- await referenceUpdated(context, run, transaction, conflict.updates, updated)
1401
+ await referenceUpdated(context, run, transaction, updates, updated)
1215
1402
  return { ...updated, inserted: false }
1216
1403
  }
1217
1404
  }
@@ -1264,11 +1451,12 @@ export async function updateRow<O>(
1264
1451
  context: TableContext,
1265
1452
  run: Runner,
1266
1453
  target: Addressed,
1267
- changes: ReadonlyMap<string, Primitive | null>,
1454
+ given: ReadonlyMap<string, Primitive | null>,
1268
1455
  expectedVersion: OperationNode | undefined,
1269
1456
  destination?: RefGrant,
1270
1457
  ): Promise<O> {
1271
1458
  const { name: table, version } = context.model
1459
+ const changes = boundValues(context, given)
1272
1460
  const where = scopedWhere(conditionsWith(target, expectedVersion), target.scope)
1273
1461
  const unchanged = changes.size === 0
1274
1462
  const node = unchanged
@@ -1389,18 +1577,26 @@ export async function aggregateRows<Row, O>(
1389
1577
  if (scope === undefined) {
1390
1578
  return []
1391
1579
  }
1392
- const node = aggregateNode(context.model.name, columns, filter?.conditions ?? [], scope, context.model.dates)
1580
+ const dialect = dialectOf(context)
1581
+ const conditions = boundConditions(context, context.model, filter?.conditions ?? [])
1582
+ const node = aggregateNode(context.model.name, columns, conditions, scope, context.model.dates)
1393
1583
  const rows = await (await run.read()).run<O>(node, guard(context, 'SelectQueryNode', scope))
1394
- return answerDays(context.model.name, aggregateDays(context.model.dates, columns), rows)
1584
+ const own = rowColumnsOf(context.model)
1585
+ const answered = answerRows(dialect, context.model.name, {
1586
+ days: aggregated(own.days, columns),
1587
+ timestamps: aggregated(own.timestamps, columns),
1588
+ booleans: aggregated(own.booleans, columns),
1589
+ }, rows)
1590
+ return dialect === 'postgres' ? answered : sqliteAggregates(context.model.name, columns, answered)
1395
1591
  }
1396
1592
 
1397
- /** The `date` columns of an aggregate's rows: a grouped one by its name, and its `min_` and `max_`. */
1398
- function aggregateDays(dates: NameSet, columns: AggregateColumns): NameSet {
1593
+ /** The columns of `set` among an aggregate's: a grouped one by its name, and its `min_` and `max_`. */
1594
+ function aggregated(set: NameSet, columns: AggregateColumns): NameSet {
1399
1595
  const names: string[] = []
1400
1596
  const add = (prefix: string, list: readonly string[]) => {
1401
1597
  for (let index = 0; index < list.length; index++) {
1402
1598
  const name = list[index] ?? ''
1403
- if (inSet(dates, name)) {
1599
+ if (inSet(set, name)) {
1404
1600
  names[names.length] = `${prefix}${name}`
1405
1601
  }
1406
1602
  }
@@ -1411,6 +1607,37 @@ function aggregateDays(dates: NameSet, columns: AggregateColumns): NameSet {
1411
1607
  return nameSet(names)
1412
1608
  }
1413
1609
 
1610
+ /**
1611
+ * An aggregate's numbers as Postgres's driver answers them: `count` as bigint text, and an integral `sum` as text too
1612
+ * (Postgres sums an integer as bigint or numeric). SQLite answers both as numbers, and a whole sum of a REAL column is
1613
+ * text here where Postgres's float8 sum is a number; `AggregateRow` types a sum as either.
1614
+ */
1615
+ function sqliteAggregates<O>(table: string, columns: AggregateColumns, rows: O[]): O[] {
1616
+ const integral = (where: string, value: unknown): unknown => {
1617
+ if (typeof value !== 'number' || !Number.isInteger(value)) {
1618
+ return value
1619
+ }
1620
+ if (!isSafeInteger(value)) {
1621
+ throw new QueryRefusedError('unexpected_row', `${where} came back as an integer past the safe range, which a number cannot hold exactly`)
1622
+ }
1623
+ return String(value)
1624
+ }
1625
+ for (let index = 0; index < rows.length; index++) {
1626
+ const row = rows[index]
1627
+ if (typeof row !== 'object' || row === null) {
1628
+ continue
1629
+ }
1630
+ if (columns.count) {
1631
+ defineValue(row, 'count', integral(`${table}.count`, ownDescriptor(row, 'count')?.value))
1632
+ }
1633
+ for (let position = 0; position < columns.sum.length; position++) {
1634
+ const name = `sum_${columns.sum[position] ?? ''}`
1635
+ defineValue(row, name, integral(`${table}.${name}`, ownDescriptor(row, name)?.value))
1636
+ }
1637
+ }
1638
+ return rows
1639
+ }
1640
+
1414
1641
  /** An insert's row, stamped from its capability, the destination it locks, and what it does on a conflict. */
1415
1642
  export interface PreparedInsert {
1416
1643
  readonly row: Map<string, Primitive | null>
@@ -1433,10 +1660,8 @@ export function prepareDimensionInsert(context: TableContext, target: unknown, v
1433
1660
  stampInsert(context, grant, row, scope.key, grant.id)
1434
1661
  return { row, destination: undefined, conflict }
1435
1662
  }
1436
- stampInsert(context, grant, row, scope.key, Bun.randomUUIDv7())
1437
- for (const { link, value } of linkValues(context.model.name, context.model.chain, grant)) {
1438
- row.set(link.column, value)
1439
- }
1663
+ stampInsert(context, grant, row, scope.key, uuidv7())
1664
+ stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1440
1665
  return { row, destination: grant, conflict }
1441
1666
  }
1442
1667
 
@@ -1445,7 +1670,7 @@ export function prepareApplicationInsert(context: TableContext, capability: unkn
1445
1670
  const grant = appGrant(context, capability, 'insert')
1446
1671
  const row = readValues(values, context.model.insert, 'insert', context.model)
1447
1672
  const conflict = onConflictOf(context, options, grant.action, row)
1448
- stampInsert(context, grant, row, keyOf(context.model), Bun.randomUUIDv7())
1673
+ stampInsert(context, grant, row, keyOf(context.model), uuidv7())
1449
1674
  return { row, destination: undefined, conflict }
1450
1675
  }
1451
1676
 
@@ -1455,13 +1680,21 @@ export function prepareChildInsert(context: TableContext, parent: unknown, value
1455
1680
  const grant = refGrant(context, parent, scope.parent.dimension, 'insert')
1456
1681
  const row = readValues(values, context.model.insert, 'insert', context.model)
1457
1682
  const conflict = onConflictOf(context, options, grant.action, row)
1458
- stampInsert(context, grant, row, scope.key, Bun.randomUUIDv7())
1459
- for (const { link, value } of linkValues(context.model.name, context.model.chain, grant)) {
1460
- row.set(link.column, value)
1461
- }
1683
+ stampInsert(context, grant, row, scope.key, uuidv7())
1684
+ stampChain(row, linkValues(context.model.name, context.model.chain, grant))
1462
1685
  return { row, destination: grant, conflict }
1463
1686
  }
1464
1687
 
1688
+ /** Writes each chain column the destination `Ref` settles into an insert's row. */
1689
+ function stampChain(row: Map<string, Primitive | null>, values: readonly LinkValue[]): void {
1690
+ for (let index = 0; index < values.length; index++) {
1691
+ const entry = values[index]
1692
+ if (entry !== undefined) {
1693
+ row.set(entry.link.column, entry.value)
1694
+ }
1695
+ }
1696
+ }
1697
+
1465
1698
  /** A prepared insert, with its conflict handling when the caller named one. */
1466
1699
  export function insertPrepared(context: TableContext, run: Runner, prepared: PreparedInsert): Promise<Readonly<Record<string, unknown>>> {
1467
1700
  const conflict = prepared.conflict
@@ -1565,9 +1798,17 @@ export class DimensionTable<DB, P, T extends string> {
1565
1798
  const scope = objectPredicate(context, ref, 'delete')
1566
1799
  const target = refGrant(context, to, container.dimension, 'insert')
1567
1800
  const values = linkValues(context.model.name, context.model.chain, target)
1568
- const changes = new Map<string, Primitive | null>(values.map(({ link, value }) => [link.column, value]))
1801
+ const changes = new Map<string, Primitive | null>()
1802
+ stampChain(changes, values)
1803
+ const chain: Record<string, string> = {}
1804
+ for (let index = 0; index < values.length; index++) {
1805
+ const entry = values[index]
1806
+ if (entry !== undefined) {
1807
+ setOwn(chain, entry.link.dimension, entry.value)
1808
+ }
1809
+ }
1569
1810
  const acknowledged = await updateRow<Acknowledgement<P, T>>(context, storeRunner(context), addressed(scope), changes, undefined, target)
1570
- return { ...acknowledged, chain: Object.fromEntries(values.map(({ link, value }) => [link.dimension, value])) }
1811
+ return { ...acknowledged, chain }
1571
1812
  }
1572
1813
 
1573
1814
  async aggregate<const S extends AggregateSpec<Row<DB, P, T>>>(
@@ -1900,8 +2141,23 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1900
2141
  setOwn(joins, child, join.on)
1901
2142
  }
1902
2143
  }
2144
+ const childModels: Record<string, TableModel> = {}
2145
+ for (let index = 0; index < children.length; index++) {
2146
+ const child = modelOf(models, children[index] ?? '')
2147
+ if (child !== undefined) {
2148
+ setOwn(childModels, child.name, child)
2149
+ }
2150
+ }
1903
2151
  const shape = shapeOf(model, joinable)
1904
- return freeze({ model, parent, destination: destinationOf(models, model, parent), shape, joins: freeze(joins), connection })
2152
+ return freeze({
2153
+ model,
2154
+ parent,
2155
+ destination: destinationOf(models, model, parent),
2156
+ shape,
2157
+ joins: freeze(joins),
2158
+ children: freeze(childModels),
2159
+ connection,
2160
+ })
1905
2161
  }
1906
2162
 
1907
2163
  const database: ScopedDatabase<DB, P> = Object.freeze({ tables: tablePolicies(tables) })
@@ -1917,17 +2173,30 @@ export function scoped<DB, P>(tables: Tables<DB, P>): ScopedDatabase<DB, P> {
1917
2173
  }
1918
2174
  return probeOf(contextFor(table, mode))
1919
2175
  },
1920
- bind(runtime: DataLayerRuntime): Locator {
2176
+ bind(runtime: DataLayerRuntime): ProvisionalBinding {
1921
2177
  if (connection.runtime !== undefined) {
1922
2178
  throw new CapabilityError('layer_unbound', 'the data layer is already connected; only the framework connects it, once, at boot')
1923
2179
  }
1924
- const bound: DataLayerRuntime = freeze({ database: runtime.database, capabilities: runtime.capabilities, readOnly: runtime.readOnly })
2180
+ const bound: DataLayerRuntime = freeze({
2181
+ database: runtime.database,
2182
+ capabilities: runtime.capabilities,
2183
+ readOnly: runtime.readOnly,
2184
+ projectWakes: runtime.projectWakes,
2185
+ })
1925
2186
  connection.runtime = bound
1926
- return async (dimension, id, using) => locateObject(models, bound, dimension, id, using)
2187
+ return freeze({
2188
+ locate: async (dimension: string, id: string, using?: Session) => locateObject(models, bound, dimension, id, using),
2189
+ release() {
2190
+ if (connection.runtime === bound) {
2191
+ connection.runtime = undefined
2192
+ }
2193
+ },
2194
+ })
1927
2195
  },
1928
2196
  framework: freeze({
1929
2197
  webhooks: webhookTables(() => runtimeOf(connection)),
1930
- jobs: jobLeases(() => runtimeOf(connection)),
2198
+ jobs: jobLeases(() => runtimeOf(connection), leaseProjection(() => runtimeOf(connection))),
2199
+ wakes: jobWakes(() => runtimeOf(connection)),
1931
2200
  admissions: admissions(() => runtimeOf(connection)),
1932
2201
  files: storedFiles(() => runtimeOf(connection)),
1933
2202
  }),