@fabrika/db 0.9.0-dev.47 → 0.9.0-dev.49

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/db",
3
- "version": "0.9.0-dev.47",
3
+ "version": "0.9.0-dev.49",
4
4
  "type": "module",
5
5
  "sideEffects": [
6
6
  "./src/testing.ts",
@@ -96,9 +96,9 @@
96
96
  "test": "bun test"
97
97
  },
98
98
  "dependencies": {
99
- "@fabrika/auth-core": "0.9.0-dev.47",
100
- "@fabrika/platform": "0.9.0-dev.47",
101
- "@fabrika/platform-node": "0.9.0-dev.47",
99
+ "@fabrika/auth-core": "0.9.0-dev.49",
100
+ "@fabrika/platform": "0.9.0-dev.49",
101
+ "@fabrika/platform-node": "0.9.0-dev.49",
102
102
  "kysely": "0.29.6",
103
103
  "kysely-postgres-js": "5.0.1",
104
104
  "zod": "^3.25.76"
package/src/orm-types.ts CHANGED
@@ -10,7 +10,6 @@ import type {
10
10
  ActionOf,
11
11
  ApplicationTableName,
12
12
  ChildTableName,
13
- ContainerOf,
14
13
  DimensionOf,
15
14
  DimensionTableName,
16
15
  InsertValues,
@@ -113,7 +112,7 @@ export interface IndexedTable {
113
112
  readonly chain: string
114
113
  /** The dimensions whose `Ref` reaches the table: a dimension table's own and every dimension of its chain. */
115
114
  readonly refs: string
116
- /** The dimensions whose `Within` lists the table: every dimension of its chain, and a top-level table's own. */
115
+ /** The dimensions whose `Within` lists the table: every dimension of its chain, and a dimension table's own. */
117
116
  readonly reach: string
118
117
  readonly versioned: boolean
119
118
  /** A queue table: its rows are claimed and finished through `row.ref`. */
@@ -176,8 +175,8 @@ type ChainDimensions<P, T, V> = PolicyOf<P, T> extends { readonly scope: infer S
176
175
  : never
177
176
  : never
178
177
 
179
- /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a top-level table's own. */
180
- type ReachOf<P, T, V> = [ContainerOf<P, T>] extends [never] ? DimensionOf<P, T> | ChainDimensions<P, T, V> : ChainDimensions<P, T, V>
178
+ /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a dimension table's own. */
179
+ type ReachOf<P, T, V> = DimensionOf<P, T> | ChainDimensions<P, T, V>
181
180
 
182
181
  /**
183
182
  * The dimensions outside its chain whose `Within` reads table `T` through a foreign key (`readThrough`); a child view's
@@ -216,7 +215,7 @@ export type DbIndex<DB, P, V = unknown> = {
216
215
  /** Dimension → the dimension tables listed in it: those it contains, and a top-level table its own. */
217
216
  readonly listed: { readonly [T in DimensionTableName<P> as ListDimensionOf<P, T>]: T }
218
217
  /**
219
- * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a top-level table its own, and
218
+ * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a dimension table its own, and
220
219
  * each that reads through it (`readThrough`).
221
220
  */
222
221
  readonly within: { readonly [T in DimensionTableName<P> | ChildTableName<P> as ReachOf<P, T, V> | ReadThroughOf<P, T>]: T }
@@ -533,7 +532,7 @@ type ListRefusal<T extends string, E extends IndexedTable, A extends string> = `
533
532
 
534
533
  /**
535
534
  * `ctx.db.within` of an `over` endpoint: every table whose containment chain holds its dimension (tasks two levels
536
- * down through their stamped `org_id`), and a top-level table its own; child tables included.
535
+ * down through their stamped `org_id`), and a dimension table its own; child tables included.
537
536
  */
538
537
  export type WithinTables<Ix extends AnyDbIndex, D extends string, A extends string, K extends DataKind> = {
539
538
  readonly [T in WithinIn<Ix, D>]: WithinRows<T, Ix['tables'][T], A, K>
@@ -2,7 +2,8 @@
2
2
  // database when its Durable Object boots (ADR-0065), in a ledger in the same database. The identity and the
3
3
  // checksum rule are the Postgres runner's (ADR-0017): `(bundle, name)`, and the SHA-256 of an applied file's text.
4
4
  // Every new object instance runs it, so a bundle whose files match the digest recorded for it is not read further.
5
- // Runs inside a Worker: no Bun import.
5
+ // `migrateSqlite` commits each file on its own; `planSqliteMigrations` applies every pending file of every bundle in one
6
+ // transaction, which the migrating boot of an application's object uses (ADR-0069 §3). Runs inside a Worker: no Bun import.
6
7
 
7
8
  /** What the runner needs of the database; a Durable Object's `storage.sql.exec` and `storage.transactionSync` fit it. */
8
9
  export interface SqliteMigrationTarget {
@@ -240,3 +241,103 @@ export async function migrateSqlite(
240
241
  }
241
242
  return { applied }
242
243
  }
244
+
245
+ /** One row of the ledger, as a migration record names it: the identity and the checksum, without the time it ran. */
246
+ export interface SqliteLedgerEntry {
247
+ readonly bundle: string
248
+ readonly name: string
249
+ readonly checksum: string
250
+ }
251
+
252
+ /** The ledger's rows in `(bundle, name)` order, and their digest. */
253
+ export interface SqliteLedger {
254
+ readonly entries: readonly SqliteLedgerEntry[]
255
+ readonly digest: string
256
+ }
257
+
258
+ /** The SHA-256 of the rows' `bundle name checksum` lines in `(bundle, name)` order: neither part holds a space or a newline. */
259
+ export async function sqliteLedgerDigest(entries: readonly SqliteLedgerEntry[]): Promise<string> {
260
+ const sorted = [...entries].sort((a, b) => compareNames(a.bundle, b.bundle) || compareNames(a.name, b.name))
261
+ return await checksumOf(sorted.map((entry) => `${entry.bundle} ${entry.name} ${entry.checksum}\n`).join(''))
262
+ }
263
+
264
+ /** The ledger as it stands; empty while the table does not exist. */
265
+ export async function readSqliteLedger(target: SqliteMigrationTarget): Promise<SqliteLedger> {
266
+ const entries = [...readLedger(target)].map(([identity, checksum]): SqliteLedgerEntry => {
267
+ const slash = identity.indexOf('/')
268
+ return { bundle: identity.slice(0, slash), name: identity.slice(slash + 1), checksum }
269
+ }).sort((a, b) => compareNames(a.bundle, b.bundle) || compareNames(a.name, b.name))
270
+ return { entries, digest: await sqliteLedgerDigest(entries) }
271
+ }
272
+
273
+ /** What the database needs to reach the bundles: nothing, a digest only, or pending files. */
274
+ export interface SqliteMigrationPlan {
275
+ /** The ledger the plan starts from; `null` when every bundle matched its digest and the ledger was not read. */
276
+ readonly ledger: SqliteLedger | null
277
+ /** The files to apply, the bundles in the order given and each bundle's files in name order. */
278
+ readonly pending: readonly SqliteLedgerEntry[]
279
+ /** Whether `apply` writes anything: a pending file, or a bundle digest that is out of date. */
280
+ readonly writes: boolean
281
+ /**
282
+ * Applies every pending file with its ledger row, and records every out-of-date bundle digest, in one transaction
283
+ * that ends with `PRAGMA foreign_key_check`: a failing file or a row the check returns rolls the whole set back.
284
+ * Answers the identities it applied.
285
+ */
286
+ apply(): readonly string[]
287
+ }
288
+
289
+ /** Plans the bundles against the ledger without writing; refuses what `migrateSqlite` refuses, before anything runs. */
290
+ export async function planSqliteMigrations(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<SqliteMigrationPlan> {
291
+ const planned = await plan(bundles)
292
+ const digests = readDigests(target, planned)
293
+ const stale = planned.filter((bundle) => digests.get(bundle.bundle) !== bundle.digest)
294
+ if (stale.length === 0) {
295
+ return { ledger: null, pending: [], writes: false, apply: () => [] }
296
+ }
297
+ const ledger = await readSqliteLedger(target)
298
+ const recorded = new Map(ledger.entries.map((entry) => [`${entry.bundle}/${entry.name}`, entry.checksum]))
299
+ verify(planned, recorded)
300
+ const pending = stale.flatMap((bundle) => bundle.migrations.filter((migration) => !recorded.has(`${migration.bundle}/${migration.name}`)))
301
+ return {
302
+ ledger,
303
+ pending: pending.map(({ bundle, name, checksum }) => ({ bundle, name, checksum })),
304
+ writes: true,
305
+ apply: () => applyAtomically(target, stale, pending),
306
+ }
307
+ }
308
+
309
+ class ForeignKeyViolation extends Error {
310
+ override readonly name = 'ForeignKeyViolation'
311
+ }
312
+
313
+ function applyAtomically(target: SqliteMigrationTarget, stale: readonly PlannedBundle[], pending: readonly PlannedMigration[]): readonly string[] {
314
+ const appliedAt = new Date().toISOString()
315
+ try {
316
+ target.transactionSync(() => {
317
+ target.exec(LEDGER_DDL)
318
+ for (const migration of pending) {
319
+ target.exec(migration.sql)
320
+ target.exec(
321
+ `INSERT INTO ${LEDGER} (bundle, name, checksum, applied_at) VALUES (?, ?, ?, ?)`,
322
+ migration.bundle,
323
+ migration.name,
324
+ migration.checksum,
325
+ appliedAt,
326
+ )
327
+ }
328
+ for (const bundle of stale) recordDigest(target, bundle)
329
+ if (target.exec('PRAGMA foreign_key_check').toArray().length > 0) {
330
+ throw new ForeignKeyViolation('a row violates a foreign key')
331
+ }
332
+ })
333
+ } catch (error) {
334
+ const files = pending.map((migration) => `${migration.bundle}/${migration.name}`).join(', ')
335
+ throw new SqliteMigrationError(
336
+ error instanceof ForeignKeyViolation
337
+ ? `SQLite migrations ${files} left a row that violates a foreign key; none of them was applied`
338
+ : `SQLite migrations ${files} failed; none of them was applied`,
339
+ { cause: error },
340
+ )
341
+ }
342
+ return pending.map((migration) => `${migration.bundle}/${migration.name}`)
343
+ }
package/src/store.ts CHANGED
@@ -747,37 +747,12 @@ export function childListPredicate(context: TableContext, capability: unknown, o
747
747
  }
748
748
 
749
749
  /**
750
- * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
751
- * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
752
- */
753
- export function reachColumn(model: TableModel, dimension: string): string | undefined {
754
- if (model.scope.mode === 'dimension' && model.scope.container === undefined && model.scope.dimension === dimension) {
755
- return model.scope.key
756
- }
757
- for (let index = 0; index < model.chain.length; index++) {
758
- const link = model.chain[index]
759
- if (link?.dimension === dimension) {
760
- return link.column
761
- }
762
- }
763
- return undefined
764
- }
765
-
766
- /**
767
- * Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
768
- * view through its parent's, its parent's own dimension included.
750
+ * Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
751
+ * chain or a secondary path; a child view through its parent's.
769
752
  */
770
753
  export function reachedBy(context: TableContext, dimension: string): boolean {
771
754
  const model = context.through?.context.model ?? context.model
772
- return parentColumn(model, context.through !== undefined, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
773
- }
774
-
775
- /** The column that places a row of `model` in `dimension`, a view's parent's own key among them (`own`). */
776
- function parentColumn(model: TableModel, own: boolean, dimension: string): string | undefined {
777
- if (own && model.scope.mode === 'dimension' && model.scope.dimension === dimension) {
778
- return model.scope.key
779
- }
780
- return reachColumn(model, dimension)
755
+ return nodeColumnOf(model, dimension) !== undefined || secondaryPathsOf(model, dimension).length > 0
781
756
  }
782
757
 
783
758
  /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */
@@ -811,14 +786,14 @@ export function reachPredicate(context: TableContext, capability: unknown): Oper
811
786
  )
812
787
  }
813
788
  if (context.through !== undefined) {
814
- return throughParent(context, context.through, grant, (parent, part) => withinReach(parent, part, true))
789
+ return throughParent(context, context.through, grant, withinReach)
815
790
  }
816
- return withinReach(context, grant, false)
791
+ return withinReach(context, grant)
817
792
  }
818
793
 
819
794
  /** A `Within`'s read of a table it reaches: through the column that places a row in its dimension, or its secondary paths. */
820
- function withinReach(context: TableContext, grant: WithinGrant, own: boolean): OperationNode | undefined {
821
- const column = parentColumn(context.model, own, grant.dimension)
795
+ function withinReach(context: TableContext, grant: WithinGrant): OperationNode | undefined {
796
+ const column = nodeColumnOf(context.model, grant.dimension)
822
797
  if (column !== undefined) {
823
798
  return withinPredicate(context, column, grant, 'read')
824
799
  }
@@ -972,7 +947,7 @@ export function scopeTerms(context: TableContext, capability: unknown, use: Scop
972
947
  }
973
948
  return [tests]
974
949
  }
975
- const column = reachColumn(model, grant.dimension)
950
+ const column = nodeColumnOf(model, grant.dimension)
976
951
  if (column === undefined) {
977
952
  throw new CapabilityError(
978
953
  'out_of_reach',
@@ -1324,7 +1299,7 @@ export function claimScope(
1324
1299
  throw new CapabilityError('table_kind', `${model.name} is an application table: claim it through ctx.db.app`)
1325
1300
  }
1326
1301
  checkAction(context, 'update', grant.action)
1327
- const column = reachColumn(model, grant.dimension)
1302
+ const column = nodeColumnOf(model, grant.dimension)
1328
1303
  if (column === undefined) {
1329
1304
  throw new CapabilityError(
1330
1305
  'out_of_reach',
@@ -2,7 +2,7 @@ import type { Selectable, Updateable } from 'kysely';
2
2
  import type { RowRef } from './capability';
3
3
  import type { ComparableColumn, ConditionTuple } from './description';
4
4
  import type { FileReference } from './file-references';
5
- import type { ActionOf, ApplicationTableName, ChildTableName, ContainerOf, DimensionOf, DimensionTableName, InsertValues, ListDimensionOf, ParentOf, ReadsAny, Tables, UpdateValues } from './policy';
5
+ import type { ActionOf, ApplicationTableName, ChildTableName, DimensionOf, DimensionTableName, InsertValues, ListDimensionOf, ParentOf, ReadsAny, Tables, UpdateValues } from './policy';
6
6
  import type { AggregateRow, AggregateSpec } from './store';
7
7
  import type { VocabularyContainerOf } from './vocabulary-tables';
8
8
  /** A member an endpoint may not use. It has no call signature, so a call fails at its line with this message. */
@@ -105,7 +105,7 @@ export interface IndexedTable {
105
105
  readonly chain: string;
106
106
  /** The dimensions whose `Ref` reaches the table: a dimension table's own and every dimension of its chain. */
107
107
  readonly refs: string;
108
- /** The dimensions whose `Within` lists the table: every dimension of its chain, and a top-level table's own. */
108
+ /** The dimensions whose `Within` lists the table: every dimension of its chain, and a dimension table's own. */
109
109
  readonly reach: string;
110
110
  readonly versioned: boolean;
111
111
  /** A queue table: its rows are claimed and finished through `row.ref`. */
@@ -182,8 +182,8 @@ type ChainDimensions<P, T, V> = PolicyOf<P, T> extends {
182
182
  } ? C | ([OwnerTable<P, C>] extends [never] ? VocabularyAncestors<V, C> : ChainDimensions<P, OwnerTable<P, C>, V>) : S extends {
183
183
  readonly child: infer Parent extends string;
184
184
  } ? DimensionOf<P, Parent> | ChainDimensions<P, Parent, V> : never : never;
185
- /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a top-level table's own. */
186
- type ReachOf<P, T, V> = [ContainerOf<P, T>] extends [never] ? DimensionOf<P, T> | ChainDimensions<P, T, V> : ChainDimensions<P, T, V>;
185
+ /** The dimensions whose `Within` lists table `T`: every dimension of its chain, and a dimension table's own. */
186
+ type ReachOf<P, T, V> = DimensionOf<P, T> | ChainDimensions<P, T, V>;
187
187
  /**
188
188
  * The dimensions outside its chain whose `Within` reads table `T` through a foreign key (`readThrough`); a child view's
189
189
  * are its parent's, as it is read through its parent row.
@@ -238,7 +238,7 @@ export type DbIndex<DB, P, V = unknown> = {
238
238
  readonly [T in DimensionTableName<P> as ListDimensionOf<P, T>]: T;
239
239
  };
240
240
  /**
241
- * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a top-level table its own, and
241
+ * Dimension → the tables an `over` of it lists: each whose containment chain holds it, a dimension table its own, and
242
242
  * each that reads through it (`readThrough`).
243
243
  */
244
244
  readonly within: {
@@ -489,7 +489,7 @@ type WithinRead<T extends string, E extends IndexedTable, A extends string, Memb
489
489
  type ListRefusal<T extends string, E extends IndexedTable, A extends string> = `a list of ${T} needs its read action '${E['actions']['read'] & string}', and this endpoint holds '${A}'`;
490
490
  /**
491
491
  * `ctx.db.within` of an `over` endpoint: every table whose containment chain holds its dimension (tasks two levels
492
- * down through their stamped `org_id`), and a top-level table its own; child tables included.
492
+ * down through their stamped `org_id`), and a dimension table its own; child tables included.
493
493
  */
494
494
  export type WithinTables<Ix extends AnyDbIndex, D extends string, A extends string, K extends DataKind> = {
495
495
  readonly [T in WithinIn<Ix, D>]: WithinRows<T, Ix['tables'][T], A, K>;
@@ -26,3 +26,35 @@ export declare class SqliteMigrationError extends Error {
26
26
  export declare function migrateSqlite(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<{
27
27
  readonly applied: readonly string[];
28
28
  }>;
29
+ /** One row of the ledger, as a migration record names it: the identity and the checksum, without the time it ran. */
30
+ export interface SqliteLedgerEntry {
31
+ readonly bundle: string;
32
+ readonly name: string;
33
+ readonly checksum: string;
34
+ }
35
+ /** The ledger's rows in `(bundle, name)` order, and their digest. */
36
+ export interface SqliteLedger {
37
+ readonly entries: readonly SqliteLedgerEntry[];
38
+ readonly digest: string;
39
+ }
40
+ /** The SHA-256 of the rows' `bundle name checksum` lines in `(bundle, name)` order: neither part holds a space or a newline. */
41
+ export declare function sqliteLedgerDigest(entries: readonly SqliteLedgerEntry[]): Promise<string>;
42
+ /** The ledger as it stands; empty while the table does not exist. */
43
+ export declare function readSqliteLedger(target: SqliteMigrationTarget): Promise<SqliteLedger>;
44
+ /** What the database needs to reach the bundles: nothing, a digest only, or pending files. */
45
+ export interface SqliteMigrationPlan {
46
+ /** The ledger the plan starts from; `null` when every bundle matched its digest and the ledger was not read. */
47
+ readonly ledger: SqliteLedger | null;
48
+ /** The files to apply, the bundles in the order given and each bundle's files in name order. */
49
+ readonly pending: readonly SqliteLedgerEntry[];
50
+ /** Whether `apply` writes anything: a pending file, or a bundle digest that is out of date. */
51
+ readonly writes: boolean;
52
+ /**
53
+ * Applies every pending file with its ledger row, and records every out-of-date bundle digest, in one transaction
54
+ * that ends with `PRAGMA foreign_key_check`: a failing file or a row the check returns rolls the whole set back.
55
+ * Answers the identities it applied.
56
+ */
57
+ apply(): readonly string[];
58
+ }
59
+ /** Plans the bundles against the ledger without writing; refuses what `migrateSqlite` refuses, before anything runs. */
60
+ export declare function planSqliteMigrations(target: SqliteMigrationTarget, bundles: readonly SqliteMigrationBundle[]): Promise<SqliteMigrationPlan>;
@@ -94,13 +94,8 @@ export declare function dimensionListPredicate(context: TableContext, capability
94
94
  export declare function parentPredicate(context: TableContext, grant: RefGrant, key?: string): OperationNode;
95
95
  export declare function childListPredicate(context: TableContext, capability: unknown, operation: Operation): OperationNode | undefined;
96
96
  /**
97
- * The column that places a row of `model` in `dimension`: the column of that link of its containment chain, or a
98
- * top-level table's own key; `undefined` when no `Within` of the dimension reaches the table.
99
- */
100
- export declare function reachColumn(model: TableModel, dimension: string): string | undefined;
101
- /**
102
- * Whether a `Within` of `dimension` lists the table: through its containment chain or a secondary path, and a child
103
- * view through its parent's, its parent's own dimension included.
97
+ * Whether a `Within` of `dimension` lists the table: a dimension table its own dimension's, then through its containment
98
+ * chain or a secondary path; a child view through its parent's.
104
99
  */
105
100
  export declare function reachedBy(context: TableContext, dimension: string): boolean;
106
101
  /** The secondary read paths of `model` that reach `dimension`, a dimension outside its chain: at their node or above it. */