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

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 +154 -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 +122 -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 +13 -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/nodes.ts CHANGED
@@ -38,6 +38,7 @@ import {
38
38
  WhereNode,
39
39
  } from 'kysely'
40
40
  import { inSet, type NameSet, nameSet, namesOf } from './builtins'
41
+ import type { SqlDialect } from './database'
41
42
  import type { Compare, Condition, Contains, JoinState, Primitive, SelectState } from './description'
42
43
  import { QueryRefusedError } from './errors'
43
44
 
@@ -49,31 +50,55 @@ export function equals(table: string, name: string, value: Primitive): Operation
49
50
  return BinaryOperationNode.create(column(table, name), OperatorNode.create('='), ValueNode.create(value))
50
51
  }
51
52
 
53
+ // The scope predicates are built through these, so they read their nodes by index, never through an iterator or a method.
52
54
  export function allOf(nodes: readonly OperationNode[]): OperationNode {
53
- const [first, ...rest] = nodes
54
- if (first === undefined) {
55
+ let joined = nodes[0]
56
+ if (joined === undefined) {
55
57
  throw new QueryRefusedError('statement_shape', 'an empty conjunction')
56
58
  }
57
- return rest.reduce<OperationNode>((left, right) => AndNode.create(left, right), first)
59
+ for (let index = 1; index < nodes.length; index++) {
60
+ const node = nodes[index]
61
+ if (node !== undefined) {
62
+ joined = AndNode.create(joined, node)
63
+ }
64
+ }
65
+ return joined
58
66
  }
59
67
 
60
68
  /** One node, or the OR of several in a parenthesis: inside an AND, `a and b or c` would read as `(a and b) or c`. */
61
69
  export function anyOf(nodes: readonly OperationNode[]): OperationNode {
62
- const [first, ...rest] = nodes
63
- if (first === undefined) {
70
+ let joined = nodes[0]
71
+ if (joined === undefined) {
64
72
  throw new QueryRefusedError('statement_shape', 'an empty disjunction')
65
73
  }
66
- return rest.length === 0 ? first : ParensNode.create(rest.reduce<OperationNode>((left, right) => OrNode.create(left, right), first))
74
+ for (let index = 1; index < nodes.length; index++) {
75
+ const node = nodes[index]
76
+ if (node !== undefined) {
77
+ joined = OrNode.create(joined, node)
78
+ }
79
+ }
80
+ return nodes.length === 1 ? joined : ParensNode.create(joined)
67
81
  }
68
82
 
69
83
  export function inList(table: string, name: string, values: readonly string[]): OperationNode {
70
84
  return BinaryOperationNode.create(
71
85
  column(table, name),
72
86
  OperatorNode.create('in'),
73
- ValueListNode.create(values.map((value) => ValueNode.create(value))),
87
+ ValueListNode.create(valueNodes(values)),
74
88
  )
75
89
  }
76
90
 
91
+ function valueNodes(values: readonly string[]): ValueNode[] {
92
+ const nodes: ValueNode[] = []
93
+ for (let index = 0; index < values.length; index++) {
94
+ const value = values[index]
95
+ if (value !== undefined) {
96
+ nodes[nodes.length] = ValueNode.create(value)
97
+ }
98
+ }
99
+ return nodes
100
+ }
101
+
77
102
  /** The scope of a `Within` that is not limited to scope values. */
78
103
  export function everything(): OperationNode {
79
104
  return ValueNode.createImmediate(true)
@@ -167,6 +192,15 @@ function joinedSelections(join: JoinState): SelectionNode[] {
167
192
  return columns.map((name) => SelectionNode.create(AliasNode.create(column(child, name), IdentifierNode.create(`${child}.${name}`))))
168
193
  }
169
194
 
195
+ /**
196
+ * One order term. Postgres sorts nulls last ascending and first descending; SQLite the other way, so on SQLite the term
197
+ * states Postgres's order and a keyset page (`orm.ts`) reads the same rows after its cursor on both.
198
+ */
199
+ function orderItem(table: string, order: SelectState['orderBy'][number], dialect: SqlDialect): OrderByItemNode {
200
+ const item = OrderByItemNode.create(column(table, order.column), RawNode.createWithSql(order.direction))
201
+ return dialect === 'postgres' ? item : Object.freeze({ ...item, nulls: order.direction === 'asc' ? 'last' : 'first' })
202
+ }
203
+
170
204
  /** `after` is a keyset page's position, ANDed to the caller's conditions inside their parenthesis. */
171
205
  export function selectNode(
172
206
  state: SelectState,
@@ -174,12 +208,13 @@ export function selectNode(
174
208
  scope: OperationNode,
175
209
  after?: OperationNode,
176
210
  days: NameSet = NO_DAYS,
211
+ dialect: SqlDialect = 'postgres',
177
212
  ): SelectQueryNode {
178
213
  const table = state.table
179
214
  const columns = state.columns ?? visible
180
215
  const conditions = conditionsNode(table, state.conditions)
181
216
  const filter = after === undefined ? conditions : conditions === undefined ? after : AndNode.create(conditions, ParensNode.create(after))
182
- const orderBy = state.orderBy.map((order) => OrderByItemNode.create(column(table, order.column), RawNode.createWithSql(order.direction)))
217
+ const orderBy = state.orderBy.map((order) => orderItem(table, order, dialect))
183
218
  const node: SelectQueryNode = {
184
219
  kind: 'SelectQueryNode',
185
220
  from: FromNode.create([TableNode.create(table)]),
@@ -352,6 +387,7 @@ export function claimNode(
352
387
  due: { readonly due: string; readonly attempts: string; readonly now: Date; readonly maxAttempts: number },
353
388
  scope: OperationNode,
354
389
  days: NameSet,
390
+ dialect: SqlDialect = 'postgres',
355
391
  ): SelectQueryNode {
356
392
  const table = state.table
357
393
  const waiting = allOf([
@@ -359,10 +395,29 @@ export function claimNode(
359
395
  BinaryOperationNode.create(column(table, due.due), OperatorNode.create('<='), ValueNode.create(due.now)),
360
396
  BinaryOperationNode.create(column(table, due.attempts), OperatorNode.create('<'), ValueNode.create(due.maxAttempts)),
361
397
  ])
362
- const node = selectNode(state, columns, scope, waiting, days)
398
+ const node = selectNode(state, columns, scope, waiting, days, dialect)
363
399
  return Object.freeze({ ...node, endModifiers: [SelectModifierNode.create('ForUpdate'), SelectModifierNode.create('SkipLocked')] })
364
400
  }
365
401
 
402
+ /**
403
+ * When the same claim next finds a row: `select <due> from table where (<conditions> and (<due> > $now and <attempts> <
404
+ * $max)) and scope order by <due> limit 1`, with `state` the claim's conditions ordered by `<due>`, limited to one.
405
+ */
406
+ export function nextClaimNode(
407
+ state: SelectState,
408
+ due: { readonly due: string; readonly attempts: string; readonly now: Date; readonly maxAttempts: number },
409
+ scope: OperationNode,
410
+ days: NameSet,
411
+ dialect: SqlDialect = 'postgres',
412
+ ): SelectQueryNode {
413
+ const table = state.table
414
+ const later = allOf([
415
+ BinaryOperationNode.create(column(table, due.due), OperatorNode.create('>'), ValueNode.create(due.now)),
416
+ BinaryOperationNode.create(column(table, due.attempts), OperatorNode.create('<'), ValueNode.create(due.maxAttempts)),
417
+ ])
418
+ return selectNode(state, [due.due], scope, later, days, dialect)
419
+ }
420
+
366
421
  /** `select <columns> from table where scope for update`: a mutation's precondition read of its own target. */
367
422
  export function lockedSelectNode(table: string, columns: readonly string[], scope: OperationNode, days: NameSet = NO_DAYS): SelectQueryNode {
368
423
  const node: SelectQueryNode = {
package/src/orm-types.ts CHANGED
@@ -686,8 +686,8 @@ type RefFragment<Ix extends AnyDbIndex, D extends string, A extends string> = {
686
686
  }[TableName<Ix>]
687
687
 
688
688
  /**
689
- * What a `Within` writes on a `'write'` site: the target of an UPDATE or DELETE whose action it holds, a column's own
690
- * write action included (the statement's SET is checked against its columns at run time).
689
+ * What a `Within` writes on a `'write'` site: the table of a fragment of `use: 'update'` or `'delete'` whose action it
690
+ * holds, a column's own write action included (the statement's columns are the approver's to review, not checked).
691
691
  */
692
692
  type WithinWrites<E extends IndexedTable, M extends 'read' | 'write'> = M extends 'write'
693
693
  ? E['actions']['update'] | E['actions']['delete'] | (keyof E['writes'] & string)
package/src/orm.ts CHANGED
@@ -3,6 +3,7 @@
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'
8
9
  import { freeze, hasOwn, inSet, isSafeInteger, nameSet, namesOf, ownDescriptor, ownKeys, ownNames, parseList, setOwn } from './builtins'
@@ -12,6 +13,7 @@ import { columnOf, type Compare, type Contains, parseCondition, type Primitive,
12
13
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
13
14
  import { answerFiles, type FileBinding } from './file-columns'
14
15
  import { databaseNow } from './job-leases'
16
+ import { rearmClaim } from './job-wakes'
15
17
  import { linksPredicate, linkValues } from './links'
16
18
  import {
17
19
  aggregateNode,
@@ -24,6 +26,7 @@ import {
24
26
  everything,
25
27
  inList,
26
28
  lockedSelectNode,
29
+ nextClaimNode,
27
30
  scopedWhere,
28
31
  selectNode,
29
32
  updateNode,
@@ -41,11 +44,14 @@ import {
41
44
  appListPredicate,
42
45
  appRecordPredicate,
43
46
  appRowPredicate,
47
+ boundTerms,
48
+ boundValues,
44
49
  childObjectPredicate,
45
50
  childScope,
46
51
  claimedRowPredicate,
47
52
  claimScope,
48
53
  type DataLayerRuntime,
54
+ dialectOf,
49
55
  heldAction,
50
56
  insertPrepared,
51
57
  insertRow,
@@ -60,6 +66,7 @@ import {
60
66
  reachPredicate,
61
67
  readValues,
62
68
  removeRow,
69
+ rowColumnsOf,
63
70
  type Runner,
64
71
  runtimeOf,
65
72
  scopedApplicationRead,
@@ -72,7 +79,7 @@ import {
72
79
  updatingRef,
73
80
  versionArgument,
74
81
  } from './store'
75
- import { answerDays, timestampInput } from './temporal'
82
+ import { answerRows, timestampInput } from './temporal'
76
83
 
77
84
  /** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
78
85
  export const DEFAULT_LIST_LIMIT = 50
@@ -158,22 +165,19 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
158
165
  direct: () => parts.newSession(parts.runtime()),
159
166
  transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
160
167
  handles: (site: DataSite) => handlesOf(parts, site),
161
- sql: (site: SqlSite) =>
162
- sqlTag(
168
+ sql: (site: SqlSite) => {
169
+ const database = parts.runtime().database
170
+ return sqlTag(
163
171
  site,
164
- parts.runtime().database.schema,
165
- (capability, table, use, assigned) => {
172
+ database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
173
+ (capability, table, use) => {
166
174
  if (!hasOwn(parts.models, table)) {
167
175
  throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
168
176
  }
169
- return scopeTerms(parts.contextOf(table), capability, use, assigned)
177
+ return scopeTerms(parts.contextOf(table), capability, use)
170
178
  },
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
- }
175
- },
176
- ),
179
+ )
180
+ },
177
181
  })
178
182
  }
179
183
 
@@ -331,7 +335,7 @@ function targetRow(
331
335
  const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
332
336
  const session = await run.read()
333
337
  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)
338
+ const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
335
339
  if (row === undefined) {
336
340
  throw new NotFoundError(`${context.model.name} not found`)
337
341
  }
@@ -590,7 +594,7 @@ function applicationRows(
590
594
  const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
591
595
  const session = await run.read()
592
596
  const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
593
- const [row] = answerDays(table, model.dates, rows)
597
+ const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
594
598
  if (row === undefined) {
595
599
  throw new NotFoundError(`${table} not found`)
596
600
  }
@@ -701,6 +705,8 @@ function publicApplicationRows(
701
705
  const DEFAULT_TICK_MS = 60_000
702
706
  /** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
703
707
  const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
708
+ /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
709
+ const CLAIM_REARM_MIN_MS = 1_000
704
710
 
705
711
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
706
712
  function backoffMs(tickMs: number, attempts: number): number {
@@ -711,6 +717,15 @@ function backoffMs(tickMs: number, attempts: number): number {
711
717
  return Math.min(backoff, MAX_BACKOFF_MS)
712
718
  }
713
719
 
720
+ /** A queue row's due time as the layer answers it. */
721
+ function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
722
+ const due = row[column]
723
+ if (!(due instanceof Date)) {
724
+ throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
725
+ }
726
+ return due
727
+ }
728
+
714
729
  /** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
715
730
  function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
716
731
  if (site.kind === 'query') {
@@ -752,24 +767,22 @@ async function claimRows(
752
767
  }
753
768
  const limit = limitOf(options['limit'])
754
769
  const visible = visibleFor(model, grant.action)
755
- const conditions = conditionsOf(actionShape(model, visible), options['where'])
770
+ const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
756
771
  if (scope === undefined) {
757
772
  return []
758
773
  }
774
+ const dialect = dialectOf(context)
759
775
  const key = keyOf(model)
760
776
  const chain = model.chain.map((link) => link.column)
761
777
  const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
762
778
  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) => {
779
+ const byDue = { column: queue.due, direction: 'asc' as const }
780
+ const order = [byDue, { column: key, direction: 'asc' as const }]
781
+ const runtime = parts.runtime()
782
+ const leased = await parts.fenced(runtime, async (session) => {
765
783
  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 },
770
- scope,
771
- model.dates,
772
- )
784
+ const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
785
+ const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
773
786
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
774
787
  const byAttempts = new Map<number, string[]>()
775
788
  for (const row of rows) {
@@ -785,7 +798,7 @@ async function claimRows(
785
798
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
786
799
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
787
800
  const updated = await session.run<Readonly<Record<string, unknown>>>(
788
- updateNode(table, changes, version, scopedWhere(inList(table, key, ids), scope), answer(context)),
801
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
789
802
  { root: 'UpdateQueryNode', table, joins: {}, scope },
790
803
  )
791
804
  for (const row of updated) {
@@ -797,7 +810,24 @@ async function claimRows(
797
810
  claimed.set(id, { version: next, attempts: attempts + 1, due })
798
811
  }
799
812
  }
800
- return { rows: await answerFiles(model, site.files, session, answerDays(table, model.dates, rows), grant.action), claimed }
813
+ // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
814
+ const fence = runtime.capabilities.fence()
815
+ if (fence !== null && rows.length > 0) {
816
+ // A full claim left rows behind: due at once.
817
+ let rearm: Date | null = new Date(now.getTime() + 1)
818
+ if (rows.length < limit) {
819
+ const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
820
+ const [row] = answerRows(
821
+ dialect,
822
+ table,
823
+ rowColumnsOf(model),
824
+ await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
825
+ )
826
+ rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
827
+ }
828
+ await rearmClaim(runtime, session, fence, rearm)
829
+ }
830
+ return { rows: await answerFiles(model, site.files, session, answerRows(dialect, table, rowColumnsOf(model), rows), grant.action), claimed }
801
831
  })
802
832
  return leased.rows.map((row) => {
803
833
  const id = String(row[key])
@@ -957,10 +987,11 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
957
987
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
958
988
  get: bound(site, async (id: unknown) => {
959
989
  const scope = everything()
960
- const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates)
990
+ const dialect = dialectOf(context)
991
+ const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
961
992
  const session = await run.read()
962
993
  const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
963
- const [row] = answerDays(table, model.dates, rows)
994
+ const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
964
995
  if (row === undefined) {
965
996
  throw new NotFoundError(`${table} not found`)
966
997
  }
@@ -1003,7 +1034,7 @@ async function insertUnscoped(context: TableContext, run: Runner, principal: str
1003
1034
  )
1004
1035
  }
1005
1036
  }
1006
- row.set(keyOf(model), Bun.randomUUIDv7())
1037
+ row.set(keyOf(model), uuidv7())
1007
1038
  if (model.version !== undefined) {
1008
1039
  row.set(model.version, 1)
1009
1040
  }
@@ -1045,7 +1076,8 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
1045
1076
  return read
1046
1077
  }
1047
1078
 
1048
- function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[] {
1079
+ /** A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). */
1080
+ function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] {
1049
1081
  if (where === undefined) {
1050
1082
  return []
1051
1083
  }
@@ -1059,7 +1091,7 @@ function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[]
1059
1091
  if (conditions === undefined) {
1060
1092
  throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
1061
1093
  }
1062
- return conditions
1094
+ return boundTerms(context, context.model, conditions)
1063
1095
  }
1064
1096
 
1065
1097
  function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[]): OrderColumn[] {
@@ -1202,15 +1234,16 @@ async function listRows(
1202
1234
  const table = context.model.name
1203
1235
  const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
1204
1236
  const shape = actionShape(context.model, visible)
1205
- const conditions = conditionsOf(shape, options['where'])
1237
+ const conditions = conditionsOf(context, shape, options['where'])
1206
1238
  const order = orderOf(shape, options['orderBy'], tiebreak)
1207
1239
  const limit = limitOf(options['limit'])
1208
1240
  const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1209
1241
  if (scope === undefined) {
1210
1242
  return { items: [], next: null }
1211
1243
  }
1244
+ const dialect = dialectOf(context)
1212
1245
  const node = withCursorColumns(
1213
- selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates),
1246
+ selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
1214
1247
  table,
1215
1248
  order.map((term) => term.column),
1216
1249
  )
@@ -1221,7 +1254,7 @@ async function listRows(
1221
1254
  joins: {},
1222
1255
  scope,
1223
1256
  })
1224
- const page = answerDays(table, context.model.dates, rows.slice(0, limit))
1257
+ const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1225
1258
  const last = page[page.length - 1]
1226
1259
  const items = page.map((row) => withoutCursor(row, order))
1227
1260
  return {
@@ -1239,7 +1272,7 @@ async function countRows(
1239
1272
  ): Promise<number> {
1240
1273
  const table = context.model.name
1241
1274
  const options = readOptions(input, ['where'], 'count')
1242
- const conditions = conditionsOf(actionShape(context.model, visible), options['where'])
1275
+ const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
1243
1276
  if (scope === undefined) {
1244
1277
  return 0
1245
1278
  }
package/src/policy.ts CHANGED
@@ -160,6 +160,8 @@ export interface TableColumns<Col extends string = string, Table extends string
160
160
  readonly dates?: readonly Col[]
161
161
  /** The `timestamp` and `timestamptz` columns, which a write takes as a `Date` or strict ISO 8601 text; absent when none. */
162
162
  readonly timestamps?: readonly Col[]
163
+ /** On SQLite, the columns declared `BOOLEAN`, stored as 0 or 1 and read as a boolean; absent when none. */
164
+ readonly booleans?: readonly Col[]
163
165
  }
164
166
 
165
167
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -221,6 +223,8 @@ export interface TableModel {
221
223
  readonly dates: NameSet
222
224
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
223
225
  readonly timestamps: NameSet
226
+ /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
227
+ readonly booleans: NameSet
224
228
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
225
229
  readonly foreignKeys: readonly ForeignKey[]
226
230
  /**
@@ -342,7 +346,7 @@ function parseVocabulary(input: unknown): VocabularyModel {
342
346
  return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
343
347
  }
344
348
 
345
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps'])
349
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans'])
346
350
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
347
351
  const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
348
352
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
@@ -524,6 +528,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
524
528
  }
525
529
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
526
530
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
531
+ const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
527
532
  const queue = queueInput === undefined
528
533
  ? undefined
529
534
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -551,6 +556,7 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
551
556
  columnWrites: freeze(columnWrites),
552
557
  dates,
553
558
  timestamps,
559
+ booleans,
554
560
  foreignKeys,
555
561
  }
556
562
  }
@@ -673,7 +679,7 @@ function parseQueue(
673
679
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
674
680
  }
675
681
 
676
- /** The column list's `date` (`dates`) or timestamp (`timestamps`) columns, each one of the table's. */
682
+ /** The column list's `date` (`dates`), timestamp (`timestamps`) or boolean (`booleans`) columns, each one of the table's. */
677
683
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
678
684
  if (input === undefined) {
679
685
  return nameSet([])
@@ -0,0 +1,26 @@
1
+ import { SQL } from 'bun'
2
+ import { PostgresJSDialect } from 'kysely-postgres-js'
3
+ import { Database } from './database'
4
+ import { QueryRefusedError } from './errors'
5
+ import { isPlainIdentifier } from './identifier'
6
+
7
+ export interface PostgresOptions {
8
+ readonly url: string
9
+ /** The application's schema (`app_<id>`), set as the connection's `search_path`. */
10
+ readonly schema: string
11
+ readonly max?: number
12
+ }
13
+
14
+ /**
15
+ * Over `Bun.SQL` with `prepare: false`: Bun otherwise keeps one prepared statement per distinct SQL text per
16
+ * connection, and `in` lists of different lengths make that grow without bound.
17
+ */
18
+ export function openPostgres(options: PostgresOptions): Database {
19
+ if (!isPlainIdentifier(options.schema)) {
20
+ throw new QueryRefusedError('invalid_name', 'the schema must match ^[a-z_][a-z0-9_]*$')
21
+ }
22
+ const pool = new SQL({ url: options.url, adapter: 'postgres', prepare: false, max: options.max ?? 10, connection: { search_path: options.schema } })
23
+ return Database.fromDialect(new PostgresJSDialect({ postgres: pool }), { schema: options.schema })
24
+ }
25
+ // Application modules load after this one: a replaced opener would receive the database URL.
26
+ Object.freeze(openPostgres)
package/src/registry.ts CHANGED
@@ -6,6 +6,7 @@ import type { Admissions } from './admissions'
6
6
  import type { Session } from './database'
7
7
  import type { WebhookTables } from './framework-tables'
8
8
  import type { JobLeases } from './job-leases'
9
+ import type { JobWakes } from './job-wakes'
9
10
  import type { DataAccess } from './orm'
10
11
  import type { DataLayerRuntime, TableContext, TableProbe } from './store'
11
12
  import type { StoredFiles } from './stored-files'
@@ -20,15 +21,23 @@ export type Locator = (dimension: string, id: string, using?: Session) => Promis
20
21
  export interface FrameworkTables {
21
22
  readonly webhooks: WebhookTables
22
23
  readonly jobs: JobLeases
24
+ /** A job's durable pending work (`fabrika_wakes`), which follows its lease, and the scheduler's next wake over both. */
25
+ readonly wakes: JobWakes
23
26
  /** A procedure's admission buckets, the challenge tokens it accepted and its byte budget. */
24
27
  readonly admissions: Admissions
25
28
  /** Every stored file (`fabrika_files`): staged before its object, claimed at its first reference, swept unreferenced. */
26
29
  readonly files: StoredFiles
27
30
  }
28
31
 
32
+ /** A connection of the layer and its locator. Only its holder can `release` it, which lets the layer be bound again. */
33
+ export interface ProvisionalBinding {
34
+ readonly locate: Locator
35
+ release(): void
36
+ }
37
+
29
38
  export interface FrameworkSide {
30
- /** Connects the layer once and answers its locator; a second call throws. */
31
- bind(runtime: DataLayerRuntime): Locator
39
+ /** Connects the layer once and answers its binding; a call while one is connected throws. */
40
+ bind(runtime: DataLayerRuntime): ProvisionalBinding
32
41
  readonly framework: FrameworkTables
33
42
  /** The untyped handle over one table that `@fabrika/db/testing` hands the isolation tests. */
34
43
  probe(table: string): TableProbe