@fabrika/db 0.9.0-dev.1 → 0.9.0-dev.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/package.json +44 -12
  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 +191 -0
  6. package/src/codegen.ts +170 -28
  7. package/src/database.ts +227 -61
  8. package/src/description.ts +34 -8
  9. package/src/errors.ts +6 -4
  10. package/src/file-columns.ts +36 -9
  11. package/src/framework-tables.ts +28 -8
  12. package/src/framework.ts +14 -5
  13. package/src/guard.ts +8 -0
  14. package/src/index.ts +10 -1
  15. package/src/job-leases.ts +210 -54
  16. package/src/job-wakes.ts +450 -0
  17. package/src/json.ts +124 -0
  18. package/src/links.ts +8 -1
  19. package/src/migrations-sqlite.ts +163 -0
  20. package/src/migrations.ts +25 -0
  21. package/src/nodes.ts +64 -9
  22. package/src/orm-types.ts +5 -5
  23. package/src/orm.ts +94 -37
  24. package/src/policy.ts +17 -2
  25. package/src/postgres.ts +26 -0
  26. package/src/registry.ts +11 -2
  27. package/src/sql.ts +230 -477
  28. package/src/sqlite-bun.ts +149 -0
  29. package/src/sqlite-migrate.ts +242 -0
  30. package/src/sqlite.ts +224 -0
  31. package/src/store.ts +385 -103
  32. package/src/stored-files.ts +188 -52
  33. package/src/tables.ts +16 -0
  34. package/src/temporal.ts +122 -9
  35. package/src/testing-shared.ts +878 -0
  36. package/src/testing-sqlite.ts +570 -0
  37. package/src/testing.ts +255 -482
  38. package/types/src/admissions.d.ts +21 -0
  39. package/types/src/application-rows.d.ts +58 -0
  40. package/types/src/builtins.d.ts +42 -0
  41. package/types/src/capability.d.ts +119 -0
  42. package/types/src/codegen-sqlite.d.ts +13 -0
  43. package/types/src/codegen.d.ts +113 -0
  44. package/types/src/database.d.ts +185 -0
  45. package/types/src/description.d.ts +124 -0
  46. package/types/src/errors.d.ts +98 -0
  47. package/types/src/file-columns.d.ts +39 -0
  48. package/types/src/file-references.d.ts +27 -0
  49. package/types/src/framework-tables.d.ts +59 -0
  50. package/types/src/framework.d.ts +38 -0
  51. package/types/src/guard.d.ts +23 -0
  52. package/types/src/identifier.d.ts +4 -0
  53. package/types/src/index.d.ts +11 -0
  54. package/types/src/job-leases.d.ts +112 -0
  55. package/types/src/job-wakes.d.ts +101 -0
  56. package/types/src/json.d.ts +18 -0
  57. package/types/src/links.d.ts +13 -0
  58. package/types/src/migrations-sqlite.d.ts +4 -0
  59. package/types/src/migrations.d.ts +26 -0
  60. package/types/src/nodes.d.ts +73 -0
  61. package/types/src/orm-types.d.ts +638 -0
  62. package/types/src/orm.d.ts +82 -0
  63. package/types/src/policy.d.ts +358 -0
  64. package/types/src/postgres.d.ts +12 -0
  65. package/types/src/production.d.ts +5 -0
  66. package/types/src/registry.d.ts +43 -0
  67. package/types/src/sql.d.ts +67 -0
  68. package/types/src/sqlite-bun.d.ts +21 -0
  69. package/types/src/sqlite-migrate.d.ts +28 -0
  70. package/types/src/sqlite.d.ts +24 -0
  71. package/types/src/store.d.ts +351 -0
  72. package/types/src/stored-files.d.ts +102 -0
  73. package/types/src/tables.d.ts +21 -0
  74. package/types/src/temporal.d.ts +36 -0
  75. package/types/src/testing-shared.d.ts +250 -0
  76. package/types/src/testing-sqlite.d.ts +22 -0
  77. package/types/src/testing.d.ts +35 -0
  78. package/types/src/vocabulary-tables.d.ts +225 -0
package/src/orm.ts CHANGED
@@ -3,15 +3,26 @@
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'
9
10
  import { type CapabilityGrant, describeGrant, type RefGrant } from './capability'
10
11
  import type { InvocationTransaction, Session } from './database'
11
- import { columnOf, type Compare, type Contains, parseCondition, type Primitive, type SelectState, type TableShape } from './description'
12
+ import {
13
+ columnOf,
14
+ comparableColumnOf,
15
+ type Compare,
16
+ type Contains,
17
+ parseCondition,
18
+ type Primitive,
19
+ type SelectState,
20
+ type TableShape,
21
+ } from './description'
12
22
  import { CapabilityError, NotFoundError, type QueryRefusal, QueryRefusedError } from './errors'
13
23
  import { answerFiles, type FileBinding } from './file-columns'
14
24
  import { databaseNow } from './job-leases'
25
+ import { rearmClaim } from './job-wakes'
15
26
  import { linksPredicate, linkValues } from './links'
16
27
  import {
17
28
  aggregateNode,
@@ -24,6 +35,7 @@ import {
24
35
  everything,
25
36
  inList,
26
37
  lockedSelectNode,
38
+ nextClaimNode,
27
39
  scopedWhere,
28
40
  selectNode,
29
41
  updateNode,
@@ -41,11 +53,14 @@ import {
41
53
  appListPredicate,
42
54
  appRecordPredicate,
43
55
  appRowPredicate,
56
+ boundTerms,
57
+ boundValues,
44
58
  childObjectPredicate,
45
59
  childScope,
46
60
  claimedRowPredicate,
47
61
  claimScope,
48
62
  type DataLayerRuntime,
63
+ dialectOf,
49
64
  heldAction,
50
65
  insertPrepared,
51
66
  insertRow,
@@ -60,6 +75,7 @@ import {
60
75
  reachPredicate,
61
76
  readValues,
62
77
  removeRow,
78
+ rowColumnsOf,
63
79
  type Runner,
64
80
  runtimeOf,
65
81
  scopedApplicationRead,
@@ -72,7 +88,7 @@ import {
72
88
  updatingRef,
73
89
  versionArgument,
74
90
  } from './store'
75
- import { answerDays, timestampInput } from './temporal'
91
+ import { answerRows, timestampInput } from './temporal'
76
92
 
77
93
  /** A list page holds this many rows unless the caller asks for fewer, and never more than `MAX_LIST_LIMIT`. */
78
94
  export const DEFAULT_LIST_LIMIT = 50
@@ -102,6 +118,11 @@ export interface DataSite {
102
118
  * only one it holds. Absent where the framework serves no file; the columns then read as ids and refuse every write.
103
119
  */
104
120
  readonly files?: FileBinding
121
+ /**
122
+ * The actions a job holds over the whole application: those it declares that its key's token carries. A queue claim
123
+ * answers a file reference its holder may open when one of them reads the table, as a re-read of the row would.
124
+ */
125
+ readonly holds?: readonly string[]
105
126
  /** The texts the verified signed tokens of a public procedure's request carry: the row ids it may update or remove. */
106
127
  readonly carried?: ReadonlySet<string>
107
128
  /** Throws unless the work running now is the invocation these handles were made for. */
@@ -158,22 +179,19 @@ export function dataAccess(parts: DataLayerParts): DataAccess {
158
179
  direct: () => parts.newSession(parts.runtime()),
159
180
  transaction: <T>(work: (session: Session) => Promise<T>) => parts.fenced(parts.runtime(), work),
160
181
  handles: (site: DataSite) => handlesOf(parts, site),
161
- sql: (site: SqlSite) =>
162
- sqlTag(
182
+ sql: (site: SqlSite) => {
183
+ const database = parts.runtime().database
184
+ return sqlTag(
163
185
  site,
164
- parts.runtime().database.schema,
165
- (capability, table, use, assigned) => {
186
+ database.dialect === 'postgres' ? { dialect: 'postgres', schema: database.schema ?? '' } : { dialect: 'sqlite' },
187
+ (capability, table, use) => {
166
188
  if (!hasOwn(parts.models, table)) {
167
189
  throw new QueryRefusedError('unknown_table', `ctx.sql.scope: ${table} is not a table of src/db/tables.ts`)
168
190
  }
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
- }
191
+ return scopeTerms(parts.contextOf(table), capability, use)
175
192
  },
176
- ),
193
+ )
194
+ },
177
195
  })
178
196
  }
179
197
 
@@ -331,7 +349,7 @@ function targetRow(
331
349
  const node = lockedSelectNode(context.model.name, visibleFor(context.model, grant.action), scope, context.model.dates)
332
350
  const session = await run.read()
333
351
  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)
352
+ const [row] = answerRows(dialectOf(context), context.model.name, rowColumnsOf(context.model), rows)
335
353
  if (row === undefined) {
336
354
  throw new NotFoundError(`${context.model.name} not found`)
337
355
  }
@@ -590,7 +608,7 @@ function applicationRows(
590
608
  const node = lockedSelectNode(table, visibleFor(model, action), scope, model.dates)
591
609
  const session = await run.read()
592
610
  const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'update' })
593
- const [row] = answerDays(table, model.dates, rows)
611
+ const [row] = answerRows(dialectOf(context), table, rowColumnsOf(model), rows)
594
612
  if (row === undefined) {
595
613
  throw new NotFoundError(`${table} not found`)
596
614
  }
@@ -701,6 +719,8 @@ function publicApplicationRows(
701
719
  const DEFAULT_TICK_MS = 60_000
702
720
  /** The longest backoff: past it the doubling stops, so a row with many attempts is still due within a month. */
703
721
  const MAX_BACKOFF_MS = 30 * 24 * 60 * 60_000
722
+ /** A claim re-arms its job no sooner than this after it ran, unless it took its full limit. */
723
+ const CLAIM_REARM_MIN_MS = 1_000
704
724
 
705
725
  /** The backoff after a row's `attempts`-th claim: one tick, doubling with each further claim. */
706
726
  function backoffMs(tickMs: number, attempts: number): number {
@@ -711,6 +731,15 @@ function backoffMs(tickMs: number, attempts: number): number {
711
731
  return Math.min(backoff, MAX_BACKOFF_MS)
712
732
  }
713
733
 
734
+ /** A queue row's due time as the layer answers it. */
735
+ function dueOf(row: Readonly<Record<string, unknown>>, table: string, column: string): Date {
736
+ const due = row[column]
737
+ if (!(due instanceof Date)) {
738
+ throw new QueryRefusedError('unexpected_row', `${table}.${column} came back as ${typeof due}; a queue's due column is a timestamp`)
739
+ }
740
+ return due
741
+ }
742
+
714
743
  /** `claim`, where the site may lease: a job outside its transaction. Inside one a failure would roll the lease back. */
715
744
  function claiming(parts: DataLayerParts, context: TableContext, site: DataSite, capability: unknown): (options?: unknown) => Promise<unknown> {
716
745
  if (site.kind === 'query') {
@@ -752,24 +781,22 @@ async function claimRows(
752
781
  }
753
782
  const limit = limitOf(options['limit'])
754
783
  const visible = visibleFor(model, grant.action)
755
- const conditions = conditionsOf(actionShape(model, visible), options['where'])
784
+ const conditions = conditionsOf(context, actionShape(model, visible), options['where'])
756
785
  if (scope === undefined) {
757
786
  return []
758
787
  }
788
+ const dialect = dialectOf(context)
759
789
  const key = keyOf(model)
760
790
  const chain = model.chain.map((link) => link.column)
761
791
  const selected = namesOf(nameSet([...visible, key, version, queue.attempts, ...chain]))
762
792
  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) => {
793
+ const byDue = { column: queue.due, direction: 'asc' as const }
794
+ const order = [byDue, { column: key, direction: 'asc' as const }]
795
+ const runtime = parts.runtime()
796
+ const leased = await parts.fenced(runtime, async (session) => {
765
797
  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
- )
798
+ const waiting = { due: queue.due, attempts: queue.attempts, now, maxAttempts: queue.maxAttempts }
799
+ const node = claimNode(rowState(table, conditions, order, limit), selected, waiting, scope, model.dates, dialect)
773
800
  const rows = await session.run<Readonly<Record<string, unknown>>>(node, { root: 'SelectQueryNode', table, joins: {}, scope, lock: 'claim' })
774
801
  const byAttempts = new Map<number, string[]>()
775
802
  for (const row of rows) {
@@ -785,7 +812,7 @@ async function claimRows(
785
812
  const due = new Date(now.getTime() + backoffMs(tickMs, attempts + 1))
786
813
  const changes = new Map<string, Primitive>([[queue.attempts, attempts + 1], [queue.due, due]])
787
814
  const updated = await session.run<Readonly<Record<string, unknown>>>(
788
- updateNode(table, changes, version, scopedWhere(inList(table, key, ids), scope), answer(context)),
815
+ updateNode(table, boundValues(context, changes), version, scopedWhere(inList(table, key, ids), scope), answer(context)),
789
816
  { root: 'UpdateQueryNode', table, joins: {}, scope },
790
817
  )
791
818
  for (const row of updated) {
@@ -797,7 +824,34 @@ async function claimRows(
797
824
  claimed.set(id, { version: next, attempts: attempts + 1, due })
798
825
  }
799
826
  }
800
- return { rows: await answerFiles(model, site.files, session, answerDays(table, model.dates, rows), grant.action), claimed }
827
+ // The job runs again when this claim would next find a row; a claim that found nothing leaves the re-arm as it is.
828
+ const fence = runtime.capabilities.fence()
829
+ if (fence !== null && rows.length > 0) {
830
+ // A full claim left rows behind: due at once.
831
+ let rearm: Date | null = new Date(now.getTime() + 1)
832
+ if (rows.length < limit) {
833
+ const later = nextClaimNode(rowState(table, conditions, [byDue], 1), waiting, scope, model.dates, dialect)
834
+ const [row] = answerRows(
835
+ dialect,
836
+ table,
837
+ rowColumnsOf(model),
838
+ await session.run<Readonly<Record<string, unknown>>>(later, { root: 'SelectQueryNode', table, joins: {}, scope }),
839
+ )
840
+ rearm = row === undefined ? null : new Date(Math.max(dueOf(row, table, queue.due).getTime(), now.getTime() + CLAIM_REARM_MIN_MS))
841
+ }
842
+ await rearmClaim(runtime, session, fence, rearm)
843
+ }
844
+ return {
845
+ rows: await answerFiles(
846
+ model,
847
+ site.files,
848
+ session,
849
+ answerRows(dialect, table, rowColumnsOf(model), rows),
850
+ grant.action,
851
+ nameSet(site.holds ?? []),
852
+ ),
853
+ claimed,
854
+ }
801
855
  })
802
856
  return leased.rows.map((row) => {
803
857
  const id = String(row[key])
@@ -957,10 +1011,11 @@ function unscopedRows(context: TableContext, site: DataSite, run: Runner, mode:
957
1011
  aggregate: bound(site, async <Row>(spec: AggregateSpec<Row>) => aggregateRows(context, run, everything(), context.shape, spec)),
958
1012
  get: bound(site, async (id: unknown) => {
959
1013
  const scope = everything()
960
- const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates)
1014
+ const dialect = dialectOf(context)
1015
+ const node = selectNode(rowState(table, [], [], 1), visible, scope, byKey(id), model.dates, dialect)
961
1016
  const session = await run.read()
962
1017
  const rows = await session.run(node, { root: 'SelectQueryNode', table, joins: {}, scope })
963
- const [row] = answerDays(table, model.dates, rows)
1018
+ const [row] = answerRows(dialect, table, rowColumnsOf(model), rows)
964
1019
  if (row === undefined) {
965
1020
  throw new NotFoundError(`${table} not found`)
966
1021
  }
@@ -1003,7 +1058,7 @@ async function insertUnscoped(context: TableContext, run: Runner, principal: str
1003
1058
  )
1004
1059
  }
1005
1060
  }
1006
- row.set(keyOf(model), Bun.randomUUIDv7())
1061
+ row.set(keyOf(model), uuidv7())
1007
1062
  if (model.version !== undefined) {
1008
1063
  row.set(model.version, 1)
1009
1064
  }
@@ -1045,7 +1100,8 @@ function readOptions(options: unknown, allowed: readonly string[], what: string)
1045
1100
  return read
1046
1101
  }
1047
1102
 
1048
- function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[] {
1103
+ /** A list's `where`, parsed, with each value as its dialect binds it (`boundTerms`). */
1104
+ function conditionsOf(context: TableContext, shape: TableShape, where: unknown): readonly (Compare | Contains)[] {
1049
1105
  if (where === undefined) {
1050
1106
  return []
1051
1107
  }
@@ -1059,7 +1115,7 @@ function conditionsOf(shape: TableShape, where: unknown): (Compare | Contains)[]
1059
1115
  if (conditions === undefined) {
1060
1116
  throw new QueryRefusedError('invalid_argument', 'where takes a plain array of [column, operator, value] conditions')
1061
1117
  }
1062
- return conditions
1118
+ return boundTerms(context, context.model, conditions)
1063
1119
  }
1064
1120
 
1065
1121
  function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[]): OrderColumn[] {
@@ -1069,7 +1125,7 @@ function orderOf(shape: TableShape, orderBy: unknown, tiebreak: readonly string[
1069
1125
  if (parts === undefined || parts.length !== 2 || (direction !== 'asc' && direction !== 'desc')) {
1070
1126
  throw new QueryRefusedError('list_page', "orderBy takes [column, 'asc' | 'desc'] terms, each a plain array")
1071
1127
  }
1072
- return { column: columnOf(shape, parts[0]), direction }
1128
+ return { column: comparableColumnOf(shape, parts[0], 'orders by'), direction }
1073
1129
  })
1074
1130
  if (terms === undefined) {
1075
1131
  throw new QueryRefusedError('list_page', "orderBy takes a plain array of [column, 'asc' | 'desc'] terms")
@@ -1202,15 +1258,16 @@ async function listRows(
1202
1258
  const table = context.model.name
1203
1259
  const options = readOptions(input, ['where', 'orderBy', 'limit', 'after'], 'list')
1204
1260
  const shape = actionShape(context.model, visible)
1205
- const conditions = conditionsOf(shape, options['where'])
1261
+ const conditions = conditionsOf(context, shape, options['where'])
1206
1262
  const order = orderOf(shape, options['orderBy'], tiebreak)
1207
1263
  const limit = limitOf(options['limit'])
1208
1264
  const position = options['after'] === undefined ? undefined : keysetAfter(table, order, decodeCursor(options['after'], order))
1209
1265
  if (scope === undefined) {
1210
1266
  return { items: [], next: null }
1211
1267
  }
1268
+ const dialect = dialectOf(context)
1212
1269
  const node = withCursorColumns(
1213
- selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates),
1270
+ selectNode(rowState(table, conditions, order, limit + 1), visible, scope, position, context.model.dates, dialect),
1214
1271
  table,
1215
1272
  order.map((term) => term.column),
1216
1273
  )
@@ -1221,7 +1278,7 @@ async function listRows(
1221
1278
  joins: {},
1222
1279
  scope,
1223
1280
  })
1224
- const page = answerDays(table, context.model.dates, rows.slice(0, limit))
1281
+ const page = answerRows(dialect, table, rowColumnsOf(context.model), rows.slice(0, limit))
1225
1282
  const last = page[page.length - 1]
1226
1283
  const items = page.map((row) => withoutCursor(row, order))
1227
1284
  return {
@@ -1239,7 +1296,7 @@ async function countRows(
1239
1296
  ): Promise<number> {
1240
1297
  const table = context.model.name
1241
1298
  const options = readOptions(input, ['where'], 'count')
1242
- const conditions = conditionsOf(actionShape(context.model, visible), options['where'])
1299
+ const conditions = conditionsOf(context, actionShape(context.model, visible), options['where'])
1243
1300
  if (scope === undefined) {
1244
1301
  return 0
1245
1302
  }
package/src/policy.ts CHANGED
@@ -160,6 +160,10 @@ 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[]
165
+ /** The JSON columns (`jsonb`, or declared `JSONB` on SQLite), written as a JSON value and never compared; absent when none. */
166
+ readonly json?: readonly Col[]
163
167
  }
164
168
 
165
169
  /** The columns and foreign keys of every table, generated next to the schema types. */
@@ -221,6 +225,10 @@ export interface TableModel {
221
225
  readonly dates: NameSet
222
226
  /** The `timestamp` and `timestamptz` columns: a write's text must be strict ISO 8601 with an offset. */
223
227
  readonly timestamps: NameSet
228
+ /** On SQLite, the `BOOLEAN` columns, stored as 0 or 1. */
229
+ readonly booleans: NameSet
230
+ /** The JSON columns: a write binds a JSON value's text, and no condition, order or aggregate names one. */
231
+ readonly json: NameSet
224
232
  /** The table's foreign keys, from the column list; a containment column must be one to its container's key. */
225
233
  readonly foreignKeys: readonly ForeignKey[]
226
234
  /**
@@ -342,7 +350,7 @@ function parseVocabulary(input: unknown): VocabularyModel {
342
350
  return freeze({ dimensions: freeze(containment), actions: nameSet(actions) })
343
351
  }
344
352
 
345
- const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps'])
353
+ const COLUMN_LIST_FIELDS = nameSet(['columns', 'foreignKeys', 'dates', 'timestamps', 'booleans', 'json'])
346
354
  const FOREIGN_KEY_FIELDS = nameSet(['columns', 'table', 'references'])
347
355
  const POLICY_FIELDS = nameSet(['scope', 'actions', 'insert', 'update', 'version', 'createdBy', 'columns', 'queue', 'files'])
348
356
  const QUEUE_FIELDS = nameSet(['attempts', 'due', 'maxAttempts'])
@@ -524,6 +532,8 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
524
532
  }
525
533
  const dates = parseColumnSet(table, ownEntry(entry, 'dates'), column, 'dates')
526
534
  const timestamps = parseColumnSet(table, ownEntry(entry, 'timestamps'), column, 'timestamps')
535
+ const booleans = parseColumnSet(table, ownEntry(entry, 'booleans'), column, 'booleans')
536
+ const json = parseColumnSet(table, ownEntry(entry, 'json'), column, 'json')
527
537
  const queue = queueInput === undefined
528
538
  ? undefined
529
539
  : parseQueue(table, queueInput, column, { columns, timestamps, version, actions, update, columnWrites })
@@ -551,6 +561,8 @@ function parseTable(table: string, columnList: unknown, policyInput: unknown, vo
551
561
  columnWrites: freeze(columnWrites),
552
562
  dates,
553
563
  timestamps,
564
+ booleans,
565
+ json,
554
566
  foreignKeys,
555
567
  }
556
568
  }
@@ -673,7 +685,7 @@ function parseQueue(
673
685
  return freeze({ attempts, due, maxAttempts: maxInput === undefined ? DEFAULT_MAX_ATTEMPTS : maxInput })
674
686
  }
675
687
 
676
- /** The column list's `date` (`dates`) or timestamp (`timestamps`) columns, each one of the table's. */
688
+ /** The column list's `date` (`dates`), timestamp (`timestamps`), boolean (`booleans`) or JSON (`json`) columns, each one of the table's. */
677
689
  function parseColumnSet(table: string, input: unknown, column: (name: unknown, field: string) => string, field: string): NameSet {
678
690
  if (input === undefined) {
679
691
  return nameSet([])
@@ -987,6 +999,9 @@ function checkStamps(table: ParsedTable, chain: readonly Container[]): void {
987
999
  if (hasOwn(table.columnWrites, stamp.column)) {
988
1000
  throw new PolicyError(`${table.name}: ${stamp.column} is stamped by the layer; it takes no write action of its own`)
989
1001
  }
1002
+ if (inSet(table.json, stamp.column)) {
1003
+ throw new PolicyError(`${table.name}: ${stamp.column} is a JSON column, which the layer cannot stamp as ${stamp.role}; give it a scalar type`)
1004
+ }
990
1005
  }
991
1006
  }
992
1007
 
@@ -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