@fabrika/db 0.9.0-dev.2 → 0.9.0-dev.20

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 (80) hide show
  1. package/package.json +35 -4
  2. package/src/admissions.ts +78 -12
  3. package/src/application-rows.ts +108 -0
  4. package/src/authority.ts +560 -0
  5. package/src/builtins.ts +21 -0
  6. package/src/capability.ts +56 -2
  7. package/src/codegen-sqlite.ts +194 -0
  8. package/src/codegen.ts +229 -40
  9. package/src/condition-nodes.ts +119 -0
  10. package/src/conditions.ts +683 -0
  11. package/src/database.ts +227 -61
  12. package/src/description.ts +37 -8
  13. package/src/errors.ts +6 -4
  14. package/src/file-columns.ts +56 -11
  15. package/src/framework-tables.ts +28 -8
  16. package/src/framework.ts +14 -5
  17. package/src/guard.ts +373 -15
  18. package/src/index.ts +13 -1
  19. package/src/job-leases.ts +212 -55
  20. package/src/job-wakes.ts +450 -0
  21. package/src/json.ts +124 -0
  22. package/src/links.ts +8 -1
  23. package/src/migrations-sqlite.ts +163 -0
  24. package/src/migrations.ts +25 -0
  25. package/src/nodes.ts +84 -14
  26. package/src/orm-types.ts +124 -45
  27. package/src/orm.ts +283 -133
  28. package/src/policy.ts +1851 -119
  29. package/src/postgres.ts +26 -0
  30. package/src/registry.ts +52 -3
  31. package/src/sql.ts +247 -476
  32. package/src/sqlite-bun.ts +149 -0
  33. package/src/sqlite-migrate.ts +242 -0
  34. package/src/sqlite.ts +269 -0
  35. package/src/store.ts +2290 -239
  36. package/src/stored-files.ts +188 -52
  37. package/src/tables.ts +164 -3
  38. package/src/temporal.ts +122 -9
  39. package/src/testing-shared.ts +1348 -0
  40. package/src/testing-sqlite.ts +685 -0
  41. package/src/testing.ts +310 -494
  42. package/src/vocabulary-tables.ts +124 -18
  43. package/types/src/application-rows.d.ts +58 -0
  44. package/types/src/authority.d.ts +147 -0
  45. package/types/src/builtins.d.ts +2 -0
  46. package/types/src/capability.d.ts +55 -2
  47. package/types/src/codegen-sqlite.d.ts +13 -0
  48. package/types/src/codegen.d.ts +79 -5
  49. package/types/src/condition-nodes.d.ts +9 -0
  50. package/types/src/conditions.d.ts +151 -0
  51. package/types/src/database.d.ts +81 -20
  52. package/types/src/description.d.ts +26 -8
  53. package/types/src/errors.d.ts +5 -4
  54. package/types/src/file-columns.d.ts +6 -4
  55. package/types/src/framework.d.ts +11 -5
  56. package/types/src/guard.d.ts +24 -0
  57. package/types/src/index.d.ts +4 -3
  58. package/types/src/job-leases.d.ts +34 -5
  59. package/types/src/job-wakes.d.ts +101 -0
  60. package/types/src/json.d.ts +18 -0
  61. package/types/src/migrations-sqlite.d.ts +4 -0
  62. package/types/src/migrations.d.ts +1 -0
  63. package/types/src/nodes.d.ts +17 -2
  64. package/types/src/orm-types.d.ts +91 -42
  65. package/types/src/orm.d.ts +10 -0
  66. package/types/src/policy.d.ts +332 -6
  67. package/types/src/postgres.d.ts +12 -0
  68. package/types/src/registry.d.ts +37 -3
  69. package/types/src/sql.d.ts +29 -21
  70. package/types/src/sqlite-bun.d.ts +21 -0
  71. package/types/src/sqlite-migrate.d.ts +28 -0
  72. package/types/src/sqlite.d.ts +24 -0
  73. package/types/src/store.d.ts +143 -34
  74. package/types/src/stored-files.d.ts +6 -2
  75. package/types/src/tables.d.ts +17 -1
  76. package/types/src/temporal.d.ts +24 -0
  77. package/types/src/testing-shared.d.ts +290 -0
  78. package/types/src/testing-sqlite.d.ts +37 -0
  79. package/types/src/testing.d.ts +2 -93
  80. package/types/src/vocabulary-tables.d.ts +141 -17
package/src/orm.ts CHANGED
@@ -3,16 +3,27 @@
3
3
  // is that invocation, then refuses what the site may not do with the message its types give, then runs the store's
4
4
  // own checks of kind, dimension and action against the capability.
5
5
 
6
+ import { uuidv7 } from '@fabrika/platform'
6
7
  import type { OperationNode } from 'kysely'
7
8
  import { BinaryOperationNode, OperatorNode, ValueNode } from 'kysely'
9
+ import { refScope } from './authority'
8
10
  import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
9
11
  import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
10
12
  import type { InvocationTransaction, Session } from './database'
11
- import { columnOf, type Compare, type Contains, parseCondition, type Primitive, type SelectState, type TableShape } from './description'
13
+ import {
14
+ columnOf,
15
+ comparableColumnOf,
16
+ type Compare,
17
+ type Contains,
18
+ parseCondition,
19
+ type Primitive,
20
+ type SelectState,
21
+ type TableShape,
22
+ } from './description'
12
23
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
13
24
  import { answerFiles, type FileBinding } from './file-columns'
14
25
  import { databaseNow } from './job-leases'
15
- import { linksPredicate, linkValues } from './links'
26
+ import { rearmClaim } from './job-wakes'
16
27
  import {
17
28
  aggregateNode,
18
29
  allOf,
@@ -24,28 +35,48 @@ import {
24
35
  everything,
25
36
  inList,
26
37
  lockedSelectNode,
38
+ nextClaimNode,
27
39
  scopedWhere,
28
40
  selectNode,
29
41
  updateNode,
30
42
  withCursorColumns,
31
43
  } from './nodes'
32
44
  import type { DataKind, TargetForm, UnscopedMode } from './orm-types'
33
- import { modelOf, namesAction, type TableModels, updatableBy, visibleFor } from './policy'
45
+ import {
46
+ accessTablesOf,
47
+ delegates,
48
+ modelOf,
49
+ namesAction,
50
+ type ReadReach,
51
+ soleReach,
52
+ type TableModels,
53
+ updatableBy,
54
+ visibleFor,
55
+ visibleThrough,
56
+ } from './policy'
34
57
  import { type SqlSite, type SqlTag, sqlTag } from './sql'
35
58
  import {
36
59
  actionShape,
37
60
  aggregateRows,
38
61
  type AggregateSpec,
39
62
  answer,
63
+ appGetScope,
40
64
  appKeyPredicate,
65
+ appKeyScope,
41
66
  appListPredicate,
42
- appRecordPredicate,
67
+ appListRead,
68
+ type AppRead,
69
+ appRecordRead,
43
70
  appRowPredicate,
71
+ appUpdate,
72
+ boundTerms,
73
+ boundValues,
44
74
  childObjectPredicate,
45
75
  childScope,
46
76
  claimedRowPredicate,
47
77
  claimScope,
48
78
  type DataLayerRuntime,
79
+ dialectOf,
49
80
  heldAction,
50
81
  insertPrepared,
51
82
  insertRow,
@@ -56,10 +87,11 @@ import {
56
87
  prepareApplicationInsert,
57
88
  prepareChildInsert,
58
89
  prepareDimensionInsert,
59
- reachColumn,
90
+ reachedBy,
60
91
  reachPredicate,
61
92
  readValues,
62
93
  removeRow,
94
+ rowColumnsOf,
63
95
  type Runner,
64
96
  runtimeOf,
65
97
  scopedApplicationRead,
@@ -68,11 +100,10 @@ import {
68
100
  selfLinks,
69
101
  type TableContext,
70
102
  updateRow,
71
- updatingApp,
72
103
  updatingRef,
73
104
  versionArgument,
74
105
  } from './store'
75
- import { answerDays, timestampInput } from './temporal'
106
+ import { answerRows, timestampInput } from './temporal'
76
107
 
77
108
  /** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
78
109
  export const DEFAULT_LIST_LIMIT = 50
@@ -102,6 +133,11 @@ export interface DataSite {
102
133
  * only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
103
134
  */
104
135
  readonly files?: FileBinding
136
+ /**
137
+ * The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
138
+ * answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
139
+ */
140
+ readonly holds?: readonly string[]
105
141
  /** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
106
142
  readonly carried?: ReadonlySet<string>
107
143
  /** Throws unless the work running now is the invocation these handles were made for. */
@@ -158,22 +194,20 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
158
194
  direct: () => parts.newSession(parts.runtime()),
159
195
  transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
160
196
  handles: (site: DataSite) => handlesOf(parts, site),
161
- sql: (site: SqlSite) =>
162
- sqlTag(
197
+ sql: (site: SqlSite) => {
198
+ const database = parts.runtime().database
199
+ return sqlTag(
163
200
  site,
164
- parts.runtime().database.schema,
165
- (capability, table, use, assigned) => {
201
+ database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
202
+ (capability, table, use) => {
166
203
  if (!hasOwn(parts.models, table)) {
167
204
  throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
168
205
  }
169
- return scopeTerms(parts.contextOf(table), capability, use, assigned)
170
- },
171
- (table) => {
172
- if (modelOf(parts.models, table)?.scope.mode === 'reference') {
173
- throw new QueryRefusedError('read_only', `ctx.sql: ${table} is a reference table, which no statement writes: its rows come from a migration`)
174
- }
206
+ return scopeTerms(parts.contextOf(table), capability, use)
175
207
  },
176
- ),
208
+ accessTablesOf(parts.models),
209
+ )
210
+ },
177
211
  })
178
212
  }
179
213
 
@@ -309,7 +343,7 @@ function unownedTarget(site: DataSite, dimension: string): Record<string, unknow
309
343
 
310
344
  /** The predicate of the target object, over the whole chain its `Ref` carries. */
311
345
  function targetPredicate(context: TableContext, grant: RefGrant): OperationNode {
312
- return linksPredicate(context.model.name, linkValues(context.model.name, selfLinks(context.model), grant))
346
+ return refScope(context, context.model, selfLinks(context.model), grant, new Date())
313
347
  }
314
348
 
315
349
  function targetRow(
@@ -323,19 +357,26 @@ function targetRow(
323
357
  const onOnly = (operation: string) => `${operation} acts on one object: declare access with on`
324
358
  const get = bound(site, async () => {
325
359
  const grant = namedRef(context, capability, dimension)
326
- return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), grant.action)
360
+ return selectOne(context, run, targetPredicate(context, grant), visibleFor(context.model, grant.action), soleReach(grant.action))
327
361
  })
328
362
  const lock = bound(site, async () => {
329
363
  const grant = namedRef(context, capability, dimension)
330
364
  const scope = targetPredicate(context, grant)
331
365
  const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
332
366
  const session = await run.read()
333
- const rows = await session.run(node, { root: 'SelectQueryNode', table: context.model.name, joins: {}, scope, lock: 'update' })
334
- const [row] = answerDays(context.model.name, context.model.dates, rows)
367
+ const rows = await session.run(node, {
368
+ root: 'SelectQueryNode',
369
+ table: context.model.name,
370
+ joins: {},
371
+ scope,
372
+ lock: 'update',
373
+ subqueries: context.subqueries,
374
+ })
375
+ const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
335
376
  if (row === undefined) {
336
377
  throw new NotFoundError(`${context.model.name} not found`)
337
378
  }
338
- await answerFiles(context.model, run.files, session, [row], grant.action)
379
+ await answerFiles(context.model, run.files, session, [row], soleReach(grant.action))
339
380
  return row
340
381
  })
341
382
  const getForUpdate = site.kind === 'job'
@@ -368,15 +409,14 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
368
409
  return freeze({
369
410
  list: bound(site, async (options?: unknown) => {
370
411
  const grant = namedRef(context, capability, parent)
371
- return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], grant.action)
412
+ return listRows(context, run, parentPredicate(context, grant), visibleFor(context.model, grant.action), options, [key], soleReach(grant.action))
372
413
  }),
373
414
  get: bound(site, async (id: unknown) => {
374
415
  const grant = namedRef(context, capability, parent)
375
416
  if (typeof id !== 'string' || id.length === 0) {
376
417
  throw new QueryRefusedError('row_address', `a ${context.model.name} row is addressed by its ${key}, a non-empty string`)
377
418
  }
378
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
379
- return selectOne(context, run, scope, visibleFor(context.model, grant.action), grant.action)
419
+ return selectOne(context, run, parentPredicate(context, grant, id), visibleFor(context.model, grant.action), soleReach(grant.action))
380
420
  }),
381
421
  insert: writing(
382
422
  site,
@@ -389,8 +429,7 @@ function childRows(context: TableContext, site: DataSite, run: Runner, capabilit
389
429
  }
390
430
  const grant = updatingRef(context, capability, parent)
391
431
  const changes = readValues(values, updatableBy(context.model, grant.action), 'update', context.model)
392
- const scope = allOf([equals(context.model.name, key, id), parentPredicate(context, grant)])
393
- return updateRow(context, run, { scope }, changes, versionArgument(context, options))
432
+ return updateRow(context, run, { scope: parentPredicate(context, grant, id) }, changes, versionArgument(context, options))
394
433
  }),
395
434
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
396
435
  await removeRow(context, run, { scope: childObjectPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -403,8 +442,8 @@ function containedRows(context: TableContext, site: DataSite, run: Runner, capab
403
442
  return freeze({
404
443
  list: bound(site, async (options?: unknown) => {
405
444
  const grant = namedRef(context, capability, dimension)
406
- const scope = linksPredicate(context.model.name, linkValues(context.model.name, context.model.chain, grant))
407
- return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], grant.action)
445
+ const scope = refScope(context, context.model, context.model.chain, grant, new Date())
446
+ return listRows(context, run, scope, visibleFor(context.model, grant.action), options, [keyOf(context.model)], soleReach(grant.action))
408
447
  }),
409
448
  insert: writing(
410
449
  site,
@@ -435,9 +474,9 @@ function withinTables(parts: DataLayerParts, site: DataSite, run: Runner, capabi
435
474
  for (let index = 0; index < tables.length; index++) {
436
475
  const model = modelOf(parts.models, tables[index] ?? '')
437
476
  const listable = model?.scope.mode === 'dimension' || model?.scope.mode === 'child'
438
- if (model !== undefined && listable && reachColumn(model, grant.dimension) !== undefined) {
439
- const context = parts.contextOf(model.name)
440
- setOwn(handle, model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
477
+ const context = model !== undefined && listable ? parts.contextOf(model.name) : undefined
478
+ if (context !== undefined && reachedBy(context, grant.dimension)) {
479
+ setOwn(handle, context.model.name, listedRows(parts, context, site, run, capability, () => reachPredicate(context, capability)))
441
480
  }
442
481
  }
443
482
  return freeze(handle)
@@ -461,7 +500,7 @@ function listedRows(
461
500
  claim: claiming(parts, context, site, capability),
462
501
  list: bound(site, async (options?: unknown) => {
463
502
  const predicate = scope()
464
- return listRows(context, run, predicate, visible(), options, key, heldAction(context, capability))
503
+ return listRows(context, run, predicate, visible(), options, key, soleReach(heldAction(context, capability)))
465
504
  }),
466
505
  count: bound(site, async (options?: unknown) => {
467
506
  const predicate = scope()
@@ -491,31 +530,33 @@ function applicationTables(parts: DataLayerParts, site: DataSite, run: Runner, c
491
530
  const rows = applicationRows(parts, context, site, run, capability)
492
531
  setOwn(handle, model.name, site.public === true ? publicApplicationRows(context, site, run, capability, rows) : freeze(rows))
493
532
  } else if (site.public !== true && (model.scope.mode === 'dimension' || model.scope.mode === 'child')) {
494
- setOwn(handle, model.name, appRecordRows(context, site, run, capability, grant.action))
533
+ setOwn(handle, model.name, appRecordRows(context, site, run, capability))
495
534
  }
496
535
  }
497
536
  return freeze(handle)
498
537
  }
499
538
 
500
539
  /**
501
- * A dimension or child table under an `app` capability of `action`, read-only and every row, with the columns that
502
- * action reads (`visibleFor`): listed and aggregated with its read action or an action of its `appRead`, counted with
540
+ * A dimension or child table under an `app` capability, read-only and every row, with the columns its reaching actions
541
+ * read alone (`visibleThrough`): listed and aggregated with its read action or an action of its `appRead`, counted with
503
542
  * those or an action of its `appCount`.
504
543
  */
505
- function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown, action: string): object {
506
- const visible = visibleFor(context.model, action)
507
- const shape = actionShape(context.model, visible)
508
- const key = [keyOf(context.model)]
544
+ function appRecordRows(context: TableContext, site: DataSite, run: Runner, capability: unknown): object {
545
+ const model = context.model
546
+ const key = [keyOf(model)]
509
547
  return freeze({
510
- list: bound(
511
- site,
512
- async (options?: unknown) => listRows(context, run, appRecordPredicate(context, capability, 'rows'), visible, options, key, action),
513
- ),
514
- count: bound(site, async (options?: unknown) => countRows(context, run, appRecordPredicate(context, capability, 'counts'), visible, options)),
515
- aggregate: bound(
516
- site,
517
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appRecordPredicate(context, capability, 'rows'), shape, spec),
518
- ),
548
+ list: bound(site, async (options?: unknown) => {
549
+ const { predicate, reach } = appRecordRead(context, capability, 'rows')
550
+ return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
551
+ }),
552
+ count: bound(site, async (options?: unknown) => {
553
+ const { predicate, reach } = appRecordRead(context, capability, 'counts')
554
+ return countRows(context, run, predicate, visibleThrough(model, reach), options)
555
+ }),
556
+ aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
557
+ const { predicate, reach } = appRecordRead(context, capability, 'rows')
558
+ return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
559
+ }),
519
560
  })
520
561
  }
521
562
 
@@ -539,30 +580,54 @@ function scopedApplicationRows(context: TableContext, site: DataSite, run: Runne
539
580
  const key = [keyOf(model)]
540
581
  const scope = () => scopedApplicationRead(context, capability)
541
582
  return freeze({
542
- list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, heldAction(context, capability))),
583
+ list: bound(site, async (options?: unknown) => listRows(context, run, scope(), visible, options, key, soleReach(heldAction(context, capability)))),
543
584
  count: bound(site, async (options?: unknown) => countRows(context, run, scope(), visible, options)),
544
585
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, scope(), context.shape, spec)),
545
- get: bound(site, async (id: unknown) => {
546
- scope()
547
- return selectOne(context, run, appKeyPredicate(model, id), visible, heldAction(context, capability))
548
- }),
586
+ get: bound(
587
+ site,
588
+ async (id: unknown) =>
589
+ selectOne(
590
+ context,
591
+ run,
592
+ scopedApplicationRead(context, capability, appKeyPredicate(model, id)),
593
+ visible,
594
+ soleReach(heldAction(context, capability)),
595
+ ),
596
+ ),
549
597
  })
550
598
  }
551
599
 
552
- /** An `app` capability whose action the application table names: it reads one row with the columns of its action. */
553
- function namedApp(context: TableContext, capability: unknown): string {
600
+ /**
601
+ * The row `key` names, for an `app` capability with an action the application table names, or any but a public
602
+ * procedure's on a table read with `'any'`: within the conditions of the actions it holds that the table names, any one
603
+ * admitting the row, and with the columns they read alone (`visibleThrough`).
604
+ */
605
+ function namedAppRead(context: TableContext, capability: unknown, key: unknown): AppRead {
554
606
  const grant = runtimeOf(context.connection).capabilities.resolve(capability)
555
- const table = context.model.name
607
+ const model = context.model
608
+ const table = model.name
556
609
  if (grant.kind !== 'app') {
557
610
  throw new CapabilityError('wrong_capability', `a read of ${table} here needs the capability of an app endpoint, got ${describeGrant(grant)}`)
558
611
  }
559
- if (!namesAction(context.model, grant.action)) {
612
+ if (model.actions.readAny) {
613
+ // Refuses a public procedure's grant, which reads no table read with 'any'.
614
+ appListPredicate(context, capability)
615
+ return { predicate: appGetScope(model, grant.actions, key), reach: freeze({ actions: grant.actions, narrowed: false }) }
616
+ }
617
+ const named: string[] = []
618
+ for (let index = 0; index < grant.actions.length; index++) {
619
+ const action = grant.actions[index]
620
+ if (action !== undefined && namesAction(model, action)) {
621
+ named[named.length] = action
622
+ }
623
+ }
624
+ if (named.length === 0) {
560
625
  throw new CapabilityError(
561
626
  'wrong_action',
562
- `${table} does not name the action '${grant.action}': read it from an app endpoint whose action ${table} names`,
627
+ `${table} does not name the action '${grant.actions.join("', '")}': read it from an app endpoint whose action ${table} names`,
563
628
  )
564
629
  }
565
- return grant.action
630
+ return { predicate: appGetScope(model, named, key), reach: freeze({ actions: named, narrowed: true }) }
566
631
  }
567
632
 
568
633
  /**
@@ -578,39 +643,39 @@ function applicationRows(
578
643
  ): Readonly<Record<string, unknown>> {
579
644
  const model = context.model
580
645
  const table = model.name
581
- const visible = () => visibleFor(model, heldAction(context, capability))
582
646
  const key = [keyOf(model)]
583
647
  const getForUpdate = site.kind === 'job'
584
648
  ? refused(site, 'read_only', 'a job writes inside ctx.transaction((tx) => …): use tx.db there')
585
649
  : site.kind === 'query'
586
650
  ? refused(site, 'read_only', 'getForUpdate locks the row, so it runs only in a mutation: declare the endpoint with r.mutation')
587
651
  : bound(site, async (id: unknown) => {
588
- const scope = appKeyPredicate(model, id)
589
- const action = namedApp(context, capability)
590
- const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
652
+ const { predicate: scope, reach } = namedAppRead(context, capability, id)
653
+ const node = lockedSelectNode(table, visibleThrough(model, reach), scope, model.dates)
591
654
  const session = await run.read()
592
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
593
- const [row] = answerDays(table, model.dates, rows)
655
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update', subqueries: context.subqueries })
656
+ const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
594
657
  if (row === undefined) {
595
658
  throw new NotFoundError(`${table} not found`)
596
659
  }
597
- await answerFiles(model, run.files, session, [row], action)
660
+ await answerFiles(model, run.files, session, [row], reach)
598
661
  return row
599
662
  })
600
663
  return {
601
- list: bound(
602
- site,
603
- async (options?: unknown) =>
604
- listRows(context, run, appListPredicate(context, capability), visible(), options, key, heldAction(context, capability)),
605
- ),
606
- count: bound(site, async (options?: unknown) => countRows(context, run, appListPredicate(context, capability), visible(), options)),
607
- aggregate: bound(
608
- site,
609
- async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, appListPredicate(context, capability), actionShape(model, visible()), spec),
610
- ),
664
+ list: bound(site, async (options?: unknown) => {
665
+ const { predicate, reach } = appListRead(context, capability)
666
+ return listRows(context, run, predicate, visibleThrough(model, reach), options, key, reach)
667
+ }),
668
+ count: bound(site, async (options?: unknown) => {
669
+ const { predicate, reach } = appListRead(context, capability)
670
+ return countRows(context, run, predicate, visibleThrough(model, reach), options)
671
+ }),
672
+ aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => {
673
+ const { predicate, reach } = appListRead(context, capability)
674
+ return aggregateRows(context, run, predicate, actionShape(model, visibleThrough(model, reach)), spec)
675
+ }),
611
676
  get: bound(site, async (id: unknown) => {
612
- const action = namedApp(context, capability)
613
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
677
+ const { predicate, reach } = namedAppRead(context, capability, id)
678
+ return selectOne(context, run, predicate, visibleThrough(model, reach), reach)
614
679
  }),
615
680
  getForUpdate,
616
681
  claim: claiming(parts, context, site, capability),
@@ -620,9 +685,8 @@ function applicationRows(
620
685
  async (values: unknown, options?: unknown) => insertPrepared(context, run, prepareApplicationInsert(context, capability, values, options)),
621
686
  ),
622
687
  update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
623
- const grant = updatingApp(context, capability)
624
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
625
- return updateRow(context, run, { scope: appKeyPredicate(model, id) }, changes, versionArgument(context, options))
688
+ const { scope, changes } = appUpdate(context, capability, id, values)
689
+ return updateRow(context, run, { scope }, changes, versionArgument(context, options))
626
690
  }),
627
691
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
628
692
  await removeRow(context, run, { scope: appRowPredicate(context, capability, id, 'delete') }, versionArgument(context, options))
@@ -664,21 +728,14 @@ function publicApplicationRows(
664
728
  get: bound(site, async (id: unknown) => {
665
729
  appListPredicate(context, capability)
666
730
  const action = heldAction(context, capability)
667
- return selectOne(context, run, appKeyPredicate(model, id), visibleFor(model, action), action)
731
+ return selectOne(context, run, appKeyScope(model, [action], id), visibleFor(model, action), soleReach(action))
668
732
  }),
669
733
  getForUpdate: refusal('lock'),
670
734
  claim: refusal('claim'),
671
735
  update: writing(site, 'update', async (id: unknown, values: unknown, ...options: unknown[]) => {
672
736
  tokenRow('update', id)
673
- const grant = updatingApp(context, capability)
674
- const changes = readValues(values, updatableBy(model, grant.action), 'update', model)
675
- const saved = await updateRow<Readonly<Record<string, unknown>>>(
676
- context,
677
- run,
678
- { scope: appKeyPredicate(model, id) },
679
- changes,
680
- versionArgument(context, options),
681
- )
737
+ const { scope, changes } = appUpdate(context, capability, id, values)
738
+ const saved = await updateRow<Readonly<Record<string, unknown>>>(context, run, { scope }, changes, versionArgument(context, options))
682
739
  return freeze({ version: saved['version'] })
683
740
  }),
684
741
  remove: writing(site, 'remove', async (id: unknown, ...options: unknown[]) => {
@@ -701,6 +758,19 @@ function publicApplicationRows(
701
758
  const DEFAULT_TICK_MS = 60_000
702
759
  /** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
703
760
  const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
761
+ /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
762
+ const CLAIM_REARM_MIN_MS = 1_000
763
+
764
+ /**
765
+ * When a claim that leased rows re-arms its job, by the claim's own clock `now`: at once after a full claim, else
766
+ * at the next due row it would take but no sooner than a second after it, or never when it would take none.
767
+ */
768
+ export function claimRearmAt(now: Date, full: boolean, next: Date | null): Date | null {
769
+ if (full) {
770
+ return new Date(now.getTime() + 1)
771
+ }
772
+ return next === null ? null : new Date(Math.max(next.getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
773
+ }
704
774
 
705
775
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
706
776
  function backoffMs(tickMs: number, attempts: number): number {
@@ -711,6 +781,15 @@ function backoffMs(tickMs: number, attempts: number): number {
711
781
  return Math.min(backoff, MAX_BACKOFF_MS)
712
782
  }
713
783
 
784
+ /** A queue row's due time as the layer answers it. */
785
+ function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
786
+ const due = row[column]
787
+ if (!(due instanceof Date)) {
788
+ throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
789
+ }
790
+ return due
791
+ }
792
+
714
793
  /** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
715
794
  function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
716
795
  if (site.kind === 'query') {
@@ -726,6 +805,13 @@ function claiming(parts: DataLayerParts, context: TableContext, site: DataSite,
726
805
  return bound(site, (options?: unknown) => claimRows(parts, context, site, capability, options))
727
806
  }
728
807
 
808
+ /**
809
+ * How many claimed ids one lease update names. SQLite in a Durable Object binds at most 100 parameters a statement; its
810
+ * compiler now binds an `in` list of texts (the ids, a Within's values) as one JSON parameter, so this only bounds a
811
+ * statement's size. Every chunk runs in the claim's one fenced transaction.
812
+ */
813
+ const CLAIM_UPDATE_IDS = 50
814
+
729
815
  /**
730
816
  * Leases up to `limit` due rows in a transaction of its own, fenced by the job attempt's lease: each claimed row's
731
817
  * attempts grow by one and its `due` moves by the backoff, so a failure or a crash leaves it due again later. Answers
@@ -740,7 +826,7 @@ async function claimRows(
740
826
  ): Promise<readonly Readonly<Record<string, unknown>>[]> {
741
827
  const model = context.model
742
828
  const table = model.name
743
- const { grant, scope } = claimScope(context, capability)
829
+ const { grant, action, scope } = claimScope(context, capability)
744
830
  const queue = model.queue
745
831
  const version = model.version
746
832
  if (queue === undefined || version === undefined) {
@@ -751,26 +837,31 @@ async function claimRows(
751
837
  throw new QueryRefusedError('list_page', 'claim takes { limit }: attempts count claims, so claim only what the run will reach')
752
838
  }
753
839
  const limit = limitOf(options['limit'])
754
- const visible = visibleFor(model, grant.action)
755
- const conditions = conditionsOf(actionShape(model, visible), options['where'])
840
+ const visible = visibleFor(model, action)
841
+ const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
756
842
  if (scope === undefined) {
757
843
  return []
758
844
  }
845
+ const dialect = dialectOf(context)
759
846
  const key = keyOf(model)
760
847
  const chain = model.chain.map((link) => link.column)
761
848
  const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
762
849
  const tickMs = site.tickMs ?? DEFAULT_TICK_MS
763
- const order = [{ column: queue.due, direction: 'asc' as const }, { column: key, direction: 'asc' as const }]
764
- const leased = await parts.fenced(parts.runtime(), async (session) => {
850
+ const byDue = { column: queue.due, direction: 'asc' as const }
851
+ const order = [byDue, { column: key, direction: 'asc' as const }]
852
+ const runtime = parts.runtime()
853
+ const leased = await parts.fenced(runtime, async (session) => {
765
854
  const now = await databaseNow(session)
766
- const node = claimNode(
767
- rowState(table, conditions, order, limit),
768
- selected,
769
- { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts },
855
+ const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
856
+ const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
857
+ const rows = await session.run<Readonly<Record<string, unknown>>>(node, {
858
+ root: 'SelectQueryNode',
859
+ table,
860
+ joins: {},
770
861
  scope,
771
- model.dates,
772
- )
773
- const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
862
+ lock: 'claim',
863
+ subqueries: context.subqueries,
864
+ })
774
865
  const byAttempts = new Map<number, string[]>()
775
866
  for (const row of rows) {
776
867
  const attempts = row[queue.attempts]
@@ -784,20 +875,56 @@ async function claimRows(
784
875
  for (const [attempts, ids] of byAttempts) {
785
876
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
786
877
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
787
- const updated = await session.run<Readonly<Record<string, unknown>>>(
788
- updateNode(table, changes, version, scopedWhere(inList(table, key, ids), scope), answer(context)),
789
- { root: 'UpdateQueryNode', table, joins: {}, scope },
790
- )
791
- for (const row of updated) {
792
- const id = row['id']
793
- const next = row['version']
794
- if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
795
- throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
878
+ for (let start = 0; start < ids.length; start += CLAIM_UPDATE_IDS) {
879
+ const chunk = ids.slice(start, start + CLAIM_UPDATE_IDS)
880
+ const updated = await session.run<Readonly<Record<string, unknown>>>(
881
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, chunk), scope), answer(context)),
882
+ { root: 'UpdateQueryNode', table, joins: {}, scope, subqueries: context.subqueries },
883
+ )
884
+ for (const row of updated) {
885
+ const id = row['id']
886
+ const next = row['version']
887
+ if (typeof id !== 'string' || typeof next !== 'number' || !isSafeInteger(next)) {
888
+ throw new QueryRefusedError('unexpected_row', `${table}.${version} came back as ${typeof next}; a version column is INTEGER`)
889
+ }
890
+ claimed.set(id, { version: next, attempts: attempts + 1, due })
796
891
  }
797
- claimed.set(id, { version: next, attempts: attempts + 1, due })
798
892
  }
799
893
  }
800
- return { rows: await answerFiles(model, site.files, session, answerDays(table, model.dates, rows), grant.action), claimed }
894
+ // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
895
+ const fence = runtime.capabilities.fence()
896
+ if (fence !== null && rows.length > 0) {
897
+ const full = rows.length >= limit
898
+ let next: Date | null = null
899
+ if (!full) {
900
+ const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
901
+ const [row] = answerRows(
902
+ dialect,
903
+ table,
904
+ rowColumnsOf(model),
905
+ await session.run<Readonly<Record<string, unknown>>>(later, {
906
+ root: 'SelectQueryNode',
907
+ table,
908
+ joins: {},
909
+ scope,
910
+ subqueries: context.subqueries,
911
+ }),
912
+ )
913
+ next = row === undefined ? null : dueOf(row, table, queue.due)
914
+ }
915
+ await rearmClaim(runtime, session, fence, claimRearmAt(now, full, next))
916
+ }
917
+ return {
918
+ rows: await answerFiles(
919
+ model,
920
+ site.files,
921
+ session,
922
+ answerRows(dialect, table, rowColumnsOf(model), rows),
923
+ soleReach(action),
924
+ nameSet(site.holds ?? []),
925
+ ),
926
+ claimed,
927
+ }
801
928
  })
802
929
  return leased.rows.map((row) => {
803
930
  const id = String(row[key])
@@ -809,7 +936,7 @@ async function claimRows(
809
936
  for (const name of chain) {
810
937
  links.set(name, String(row[name]))
811
938
  }
812
- const ref = runtimeOf(context.connection).capabilities.row({ table, action: grant.action, principal: grant.principal, id, chain: links })
939
+ const ref = runtimeOf(context.connection).capabilities.row({ table, action, principal: grant.principal, id, chain: links })
813
940
  const answered: Record<string, unknown> = {}
814
941
  for (const name of visible) {
815
942
  setOwn(answered, name, row[name])
@@ -942,6 +1069,17 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
942
1069
  return equals(table, keyOf(model), id)
943
1070
  }
944
1071
  const write = <A extends unknown[], R>(operation: 'insert' | 'update' | 'remove', method: (...args: A) => Promise<R>) => {
1072
+ if (model.view) {
1073
+ return refused(site, 'read_only', `${table} is a view, which no handler writes`)
1074
+ }
1075
+ // A row that hands out access is placed by its writer; an unscoped write would delegate without the writer's bound.
1076
+ if (delegates(model) || context.writers.length > 0) {
1077
+ return refused(
1078
+ site,
1079
+ 'undeclared_reach',
1080
+ `${table} hands out access, so it is written through a capability only, never unscoped`,
1081
+ )
1082
+ }
945
1083
  if (mode === 'read') {
946
1084
  const verb = operation === 'remove' ? 'remove' : operation
947
1085
  return refused(site, 'undeclared_reach', `${table} is declared unscoped: 'read', so ${verb} needs unscoped: { ${table}: 'write' }`)
@@ -951,20 +1089,21 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
951
1089
  return freeze({
952
1090
  list: bound(
953
1091
  site,
954
- async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, unscopedRead),
1092
+ async (options?: unknown) => listRows(context, run, everything(), visible, options, keyed ? [keyOf(model)] : visible, soleReach(unscopedRead)),
955
1093
  ),
956
1094
  count: bound(site, async (options?: unknown) => countRows(context, run, everything(), visible, options)),
957
1095
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
958
1096
  get: bound(site, async (id: unknown) => {
959
1097
  const scope = everything()
960
- const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates)
1098
+ const dialect = dialectOf(context)
1099
+ const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
961
1100
  const session = await run.read()
962
- const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
963
- const [row] = answerDays(table, model.dates, rows)
1101
+ const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, subqueries: context.subqueries })
1102
+ const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
964
1103
  if (row === undefined) {
965
1104
  throw new NotFoundError(`${table} not found`)
966
1105
  }
967
- await answerFiles(model, run.files, session, [row], unscopedRead)
1106
+ await answerFiles(model, run.files, session, [row], soleReach(unscopedRead))
968
1107
  return row
969
1108
  }),
970
1109
  insert: write('insert', async (values: unknown) => insertUnscoped(context, run, site.principal, values)),
@@ -1003,7 +1142,7 @@ async function insertUnscoped(context: TableContext, run: Runner, principal: str
1003
1142
  )
1004
1143
  }
1005
1144
  }
1006
- row.set(keyOf(model), Bun.randomUUIDv7())
1145
+ row.set(keyOf(model), uuidv7())
1007
1146
  if (model.version !== undefined) {
1008
1147
  row.set(model.version, 1)
1009
1148
  }
@@ -1045,7 +1184,8 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
1045
1184
  return read
1046
1185
  }
1047
1186
 
1048
- function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[] {
1187
+ /** A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). */
1188
+ function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] {
1049
1189
  if (where === undefined) {
1050
1190
  return []
1051
1191
  }
@@ -1059,7 +1199,7 @@ function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[]
1059
1199
  if (conditions === undefined) {
1060
1200
  throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
1061
1201
  }
1062
- return conditions
1202
+ return boundTerms(context, context.model, conditions)
1063
1203
  }
1064
1204
 
1065
1205
  function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[]): OrderColumn[] {
@@ -1069,7 +1209,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
1069
1209
  if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
1070
1210
  throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
1071
1211
  }
1072
- return { column: columnOf(shape, parts[0]), direction }
1212
+ return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
1073
1213
  })
1074
1214
  if (terms === undefined) {
1075
1215
  throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
@@ -1197,20 +1337,21 @@ async function listRows(
1197
1337
  visible: readonly string[],
1198
1338
  input: unknown,
1199
1339
  tiebreak: readonly string[],
1200
- action?: string,
1340
+ reach?: ReadReach,
1201
1341
  ): Promise<{ readonly items: Readonly<Record<string, unknown>>[]; readonly next: string | null }> {
1202
1342
  const table = context.model.name
1203
1343
  const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
1204
1344
  const shape = actionShape(context.model, visible)
1205
- const conditions = conditionsOf(shape, options['where'])
1345
+ const conditions = conditionsOf(context, shape, options['where'])
1206
1346
  const order = orderOf(shape, options['orderBy'], tiebreak)
1207
1347
  const limit = limitOf(options['limit'])
1208
1348
  const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1209
1349
  if (scope === undefined) {
1210
1350
  return { items: [], next: null }
1211
1351
  }
1352
+ const dialect = dialectOf(context)
1212
1353
  const node = withCursorColumns(
1213
- selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates),
1354
+ selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
1214
1355
  table,
1215
1356
  order.map((term) => term.column),
1216
1357
  )
@@ -1220,12 +1361,14 @@ async function listRows(
1220
1361
  table,
1221
1362
  joins: {},
1222
1363
  scope,
1364
+ subqueries: context.subqueries,
1365
+ through: context.through,
1223
1366
  })
1224
- const page = answerDays(table, context.model.dates, rows.slice(0, limit))
1367
+ const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1225
1368
  const last = page[page.length - 1]
1226
1369
  const items = page.map((row) => withoutCursor(row, order))
1227
1370
  return {
1228
- items: action === undefined ? items : await answerFiles(context.model, run.files, session, items, action),
1371
+ items: reach === undefined ? items : await answerFiles(context.model, run.files, session, items, reach),
1229
1372
  next: rows.length > limit && last !== undefined ? encodeCursor(last, order) : null,
1230
1373
  }
1231
1374
  }
@@ -1239,12 +1382,19 @@ async function countRows(
1239
1382
  ): Promise<number> {
1240
1383
  const table = context.model.name
1241
1384
  const options = readOptions(input, ['where'], 'count')
1242
- const conditions = conditionsOf(actionShape(context.model, visible), options['where'])
1385
+ const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
1243
1386
  if (scope === undefined) {
1244
1387
  return 0
1245
1388
  }
1246
1389
  const node = aggregateNode(table, { groupBy: [], count: true, sum: [], min: [], max: [] }, conditions, scope)
1247
- const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope })
1390
+ const [row] = await (await run.read()).run<Readonly<Record<string, unknown>>>(node, {
1391
+ root: 'SelectQueryNode',
1392
+ table,
1393
+ joins: {},
1394
+ scope,
1395
+ subqueries: context.subqueries,
1396
+ through: context.through,
1397
+ })
1248
1398
  const count = row === undefined ? '0' : row['count']
1249
1399
  return typeof count === 'string' || typeof count === 'number' ? Number(count) : 0
1250
1400
  }