@jini-ai/db 0.6.12 → 0.6.15-rc.2
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/CHANGELOG.md +29 -0
- package/README.md +76 -0
- package/dist/kernel/kernel-core.js +22 -4
- package/dist/kernel/owned-transaction.d.ts +15 -0
- package/dist/kernel/owned-transaction.js +9 -0
- package/dist/kernel/port.d.ts +1 -0
- package/dist/kernel/schema-scope.js +6 -1
- package/dist/kernel/sqlite/driver.js +20 -3
- package/dist/migrate/ddl.d.ts +11 -0
- package/dist/migrate/ddl.js +13 -0
- package/dist/migrate/index.d.ts +3 -1
- package/dist/migrate/index.js +2 -1
- package/dist/migrate/legacy-ledger.d.ts +39 -0
- package/dist/migrate/legacy-ledger.js +67 -0
- package/dist/migrate/runner.d.ts +58 -0
- package/dist/migrate/runner.js +85 -12
- package/dist/migrate/step.d.ts +1 -1
- package/dist/migrate/step.js +1 -1
- package/dist/owner-store/index.d.ts +3 -4
- package/dist/owner-store/index.js +3 -4
- package/dist/owner-store/migrations/0000_owner_store.js +2 -5
- package/dist/owner-store/migrations/index.d.ts +3 -1
- package/dist/owner-store/migrations/index.js +3 -1
- package/dist/secrets-vault/repo.sql.d.ts +3 -4
- package/dist/secrets-vault/repo.sql.js +12 -2
- package/dist/sqlite/checked-client.d.ts +19 -0
- package/dist/sqlite/checked-client.js +117 -0
- package/dist/sqlite/checked-state.d.ts +32 -0
- package/dist/sqlite/checked-state.js +26 -0
- package/dist/sqlite/index.d.ts +3 -0
- package/dist/sqlite/index.js +3 -0
- package/dist/sqlite/transaction.d.ts +29 -0
- package/dist/sqlite/transaction.js +80 -0
- package/package.json +8 -6
- package/dist/owner-store/backup.d.ts +0 -32
- package/dist/owner-store/backup.js +0 -102
- package/dist/owner-store/open.d.ts +0 -25
- package/dist/owner-store/open.js +0 -73
- package/dist/owner-store/service.d.ts +0 -69
- package/dist/owner-store/service.js +0 -122
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,32 @@
|
|
|
1
|
+
## 0.6.13
|
|
2
|
+
|
|
3
|
+
### Patch Changes
|
|
4
|
+
|
|
5
|
+
- 9138c3b: Leased SQLite transactions release their lease before the next queued kernel transaction takes its turn, so it no longer fails with `transaction_busy`. Checked clients quarantine only uncertain outcomes: a failed COMMIT followed by a successful ROLLBACK, or a stray ROLLBACK with nothing open, leaves the handle usable.
|
|
6
|
+
- aa8de3d: Add opt-in checked SQLite clients and leased transaction sessions, plus batch migration atomicity,
|
|
7
|
+
ordered-prefix history checks, injected clocks and explicit legacy ledger mappings. Existing raw
|
|
8
|
+
clients, transaction signatures and default per-step migration behavior are unchanged.
|
|
9
|
+
- 03dec0a: Preserve credential hint metadata across owner-store backup restores and reject database/key path aliases on Windows and macOS.
|
|
10
|
+
- 506196f: BREAKING (host import path): the owner-store composition moved from `@jini-ai/db/owner-store` to the new
|
|
11
|
+
`@jini-ai/server/owner-store` entry, so `@jini-ai/db` no longer reaches `@jini-ai/platform` or its own
|
|
12
|
+
sibling domains (guard L1 / SI-domain). Moved: `openOwnerStore`, `OwnerStoreRecoveryError`, `OwnerStoreService`,
|
|
13
|
+
`OWNER_WORKSPACE_ID`, `ownerContext`, `exportOwnerStore`, `restoreOwnerStore`, `OwnerStoreBackupError` and the
|
|
14
|
+
`OpenOwnerStore*` / `OwnerStoreDatabase` / `OwnerGrant` / `OwnerPutInput` / `OwnerSyncTarget` types. Behaviour is
|
|
15
|
+
unchanged. `@jini-ai/db/owner-store` keeps `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl` and
|
|
16
|
+
`ownerStoreMigration`.
|
|
17
|
+
|
|
18
|
+
Migration: import those names from `@jini-ai/server/owner-store` and add `@jini-ai/server` (same version as
|
|
19
|
+
`@jini-ai/db`) to the host's dependencies; that entry uses the optional `@jini-ai/db`, `@jini-ai/platform`
|
|
20
|
+
and `kysely` peers. `OwnerStoreService` additionally accepts an optional `repo`; existing kernel-only
|
|
21
|
+
constructions still work.
|
|
22
|
+
|
|
23
|
+
- Updated dependencies [7479159]
|
|
24
|
+
- Updated dependencies [c31264d]
|
|
25
|
+
- Updated dependencies [0728914]
|
|
26
|
+
- Updated dependencies [6ecbdb2]
|
|
27
|
+
- Updated dependencies [63bacc5]
|
|
28
|
+
- @jini-ai/core@0.6.13
|
|
29
|
+
|
|
1
30
|
## 0.6.12
|
|
2
31
|
|
|
3
32
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -201,6 +201,72 @@ builds the same four definitions for catalog inspection; its display-only defaul
|
|
|
201
201
|
- [Unavailable restore mechanisms have no attestation override](docs/decisions/DR-002-restore-point-precondition.md).
|
|
202
202
|
- [Storage copying takes its schemas from the host](docs/decisions/DR-003-host-owned-schema-copy.md).
|
|
203
203
|
|
|
204
|
+
### Optional checked SQLite transactions and migration policies
|
|
205
|
+
|
|
206
|
+
`@jini-ai/db/sqlite` adds the following object-input APIs:
|
|
207
|
+
|
|
208
|
+
```ts
|
|
209
|
+
declare function createCheckedSqliteClient(
|
|
210
|
+
required: { database: IntegerSource }, optional?: {}
|
|
211
|
+
): CheckedSqliteClient;
|
|
212
|
+
declare function withSqliteTransaction<T>(
|
|
213
|
+
required: { client: CheckedSqliteClient; kernel: StorageKernel<unknown>; work: Work<T> },
|
|
214
|
+
optional?: { rollbackOnFailedOutcome?: boolean }
|
|
215
|
+
): Promise<T>;
|
|
216
|
+
```
|
|
217
|
+
|
|
218
|
+
The host's `database` must support `statement.safeIntegers(true)`. The factory memoizes one
|
|
219
|
+
borrowed wrapper per handle; `sqliteKernel(client)` supplies its matching kernel. Safe bigint
|
|
220
|
+
cells and write metadata become numbers; overflow throws `SqliteClientError` with code
|
|
221
|
+
`unsafe_integer`. Blobs and floats retain their values. Iteration decodes one row at a time.
|
|
222
|
+
The wrapper's `close()` does nothing. Mixing raw and checked kernel ownership is refused.
|
|
223
|
+
Connection-only imports still load no runtime Kysely dependency; sessions use the supplied kernel.
|
|
224
|
+
|
|
225
|
+
`work({ session })` receives `TransactionSession` with `query({ statement }, {})`,
|
|
226
|
+
`execute({ statement }, {})` and `transaction({ work }, {})`. Statements are Kysely
|
|
227
|
+
`RawBuilder`s. Nested work joins; only the root return value decides whether the optional
|
|
228
|
+
failed-Outcome policy rolls back. Omission or `false` commits resolved values, including
|
|
229
|
+
`{ ok: false }`; `true` rolls that result back and returns the identical object after successful
|
|
230
|
+
cleanup. Thrown errors roll back. Retained sessions, overlapping helpers and entry into existing
|
|
231
|
+
transactions are refused. Uncertain outcomes (a COMMIT that may have applied, or a transaction a
|
|
232
|
+
failed ROLLBACK left open) quarantine the shared wrapper; queued and future SQL fails. A failed
|
|
233
|
+
COMMIT followed by a successful ROLLBACK, or a stray ROLLBACK with nothing open, is not quarantined. Native control errors remain causes of typed `commit_failed` /
|
|
234
|
+
`rollback_failed` errors; combined failures use `AggregateError`. Other codes are `quarantined`,
|
|
235
|
+
`session_expired` and `transaction_busy`. The host retains responsibility for the native handle.
|
|
236
|
+
The exported error constructor is `new SqliteClientError({ code }, { cause })`; its second object
|
|
237
|
+
is optional.
|
|
238
|
+
|
|
239
|
+
`@jini-ai/db/migrate` adds `migrate({ kernel, steps, ledgerTable }, options = {})`, which
|
|
240
|
+
delegates to `runMigrations`. Both accept these optional `MigrationOptions` fields:
|
|
241
|
+
|
|
242
|
+
```ts
|
|
243
|
+
declare function migrate(
|
|
244
|
+
required: { kernel: StorageKernel<unknown>; steps: readonly MigrationStep[]; ledgerTable: string },
|
|
245
|
+
optional?: Omit<MigrationOptions, "ledgerTable">
|
|
246
|
+
): Promise<MigrationReport>;
|
|
247
|
+
|
|
248
|
+
interface MigrationExtensions {
|
|
249
|
+
atomicity?: "step" | "batch";
|
|
250
|
+
historyCheck?: "known" | "ordered-prefix";
|
|
251
|
+
clock?: Clock; // @jini-ai/core/primitives, nowMs()
|
|
252
|
+
legacyLedger?: LegacyLedgerMapping;
|
|
253
|
+
}
|
|
254
|
+
interface LegacyLedgerMapping {
|
|
255
|
+
columns: { version: string; name: string; checksum: string; appliedAt: string };
|
|
256
|
+
identities: Readonly<Record<string, { version: number; name: string }>>;
|
|
257
|
+
timestamps?: "database-default" | "iso";
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
Batch mode requires a kernel-owned transaction and transactional DDL, refuses pending `prepare`
|
|
262
|
+
hooks, backs up outside the transaction and verifies history again under the ledger lock.
|
|
263
|
+
Ordered-prefix checks reject holes before pending work and repeat under that lock. ISO clocks
|
|
264
|
+
are sampled once per inserted row. Legacy mappings require complete, unique positive-safe-integer
|
|
265
|
+
versions ascending in step order and unique nonempty names; identifiers are quoted and history is read by numeric version.
|
|
266
|
+
Existing rows are never rewritten. Mapped timestamps use the database default unless `iso` is
|
|
267
|
+
explicit; supplying a clock with database-default timestamps is refused. The default runner
|
|
268
|
+
retains its standard ledger, known-ID checks and per-step commits.
|
|
269
|
+
|
|
204
270
|
### Host database prose
|
|
205
271
|
|
|
206
272
|
`defaultDbMessages` and `DbMessages` are exported from `@jini-ai/db/tools`.
|
|
@@ -214,3 +280,13 @@ message replacements remain supported; unspecified runtime fields retain neutral
|
|
|
214
280
|
missing-source-table/column formatter subset. Messages never select a schema or rewrite SQL.
|
|
215
281
|
Persisted `TransferNaming` remains required with no fallback; its display-only catalog
|
|
216
282
|
examples still default to `app` / `app_`. Keep each host's existing wire names explicit.
|
|
283
|
+
|
|
284
|
+
`@jini-ai/db/owner-store` exports the independent owner schema and pinned migration history.
|
|
285
|
+
The concrete owner-vault assembly moved to `@jini-ai/server/owner-store`; use that entry for
|
|
286
|
+
`openOwnerStore`, `OwnerStoreService` and encrypted backup operations.
|
|
287
|
+
|
|
288
|
+
**Migration (breaking, next release):** replace
|
|
289
|
+
`import { openOwnerStore, OwnerStoreService, exportOwnerStore, restoreOwnerStore, OwnerStoreBackupError, OwnerStoreRecoveryError } from '@jini-ai/db/owner-store'`
|
|
290
|
+
with the same names from `'@jini-ai/server/owner-store'`, and add `@jini-ai/server` (same version as
|
|
291
|
+
`@jini-ai/db`) to the host's dependencies. `OWNER_STORE_LEDGER`, `ownerStoreMigrations`, `ownerStoreDdl`
|
|
292
|
+
and `ownerStoreMigration` stay here.
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
2
|
import { UnsupportedCapabilityError, } from "./port.js";
|
|
3
3
|
import { TurnLock } from "./turn-lock.js";
|
|
4
|
+
import { ownedTransactions } from "./owned-transaction.js";
|
|
4
5
|
/** The turn locks the caller's async context holds, across every kernel in the process. */
|
|
5
6
|
const heldLocks = new AsyncLocalStorage();
|
|
6
7
|
/**
|
|
@@ -40,9 +41,16 @@ export function buildKernel(driver) {
|
|
|
40
41
|
return fn(driver.base);
|
|
41
42
|
return takingTurn(lock, "shared", async () => scope.run({ kind: "run", db: driver.base }, () => fn(driver.base)));
|
|
42
43
|
}
|
|
43
|
-
|
|
44
|
+
function assertOwnedAvailable() {
|
|
45
|
+
if (scope.getStore() !== undefined || joinsForeign()) {
|
|
46
|
+
throw new Error("an owned transaction cannot join an existing run or foreign transaction");
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
async function transaction(fn, owned) {
|
|
44
50
|
require("interactiveTransactions");
|
|
45
51
|
await driver.ready;
|
|
52
|
+
if (owned !== undefined)
|
|
53
|
+
assertOwnedAvailable();
|
|
46
54
|
const current = scope.getStore();
|
|
47
55
|
if (current?.kind === "transaction")
|
|
48
56
|
return fn();
|
|
@@ -50,14 +58,18 @@ export function buildKernel(driver) {
|
|
|
50
58
|
throw new Error("transaction() was called inside a run() body; start the transaction first and call run() inside it");
|
|
51
59
|
}
|
|
52
60
|
if (joinsForeign())
|
|
53
|
-
return fn
|
|
61
|
+
return scope.run({ kind: "transaction", db: driver.base }, fn);
|
|
54
62
|
return takingTurn(lock, "exclusive", async () => {
|
|
63
|
+
if (owned !== undefined)
|
|
64
|
+
assertOwnedAvailable();
|
|
55
65
|
ownTransactions += 1;
|
|
56
66
|
try {
|
|
57
67
|
return await driver.begin((tx) => scope.run({ kind: "transaction", db: tx }, fn));
|
|
58
68
|
}
|
|
59
69
|
finally {
|
|
60
70
|
ownTransactions -= 1;
|
|
71
|
+
// Still inside the turn: the next queued caller must not see this owner's state.
|
|
72
|
+
owned?.onSettled?.();
|
|
61
73
|
}
|
|
62
74
|
});
|
|
63
75
|
}
|
|
@@ -69,7 +81,7 @@ export function buildKernel(driver) {
|
|
|
69
81
|
}
|
|
70
82
|
await driver.lockKey(current?.db ?? driver.base, key);
|
|
71
83
|
}
|
|
72
|
-
|
|
84
|
+
const kernel = {
|
|
73
85
|
dialect: driver.dialect,
|
|
74
86
|
transport: driver.transport,
|
|
75
87
|
capabilities: driver.capabilities,
|
|
@@ -90,9 +102,15 @@ export function buildKernel(driver) {
|
|
|
90
102
|
if (scope.getStore()?.kind === "transaction")
|
|
91
103
|
throw new Error("backupTo() must be called outside a transaction");
|
|
92
104
|
await driver.ready;
|
|
93
|
-
|
|
105
|
+
// A copy must wait for unrelated work to commit or roll back on the shared connection.
|
|
106
|
+
await takingTurn(lock, "exclusive", () => driver.backup(destPath));
|
|
94
107
|
},
|
|
95
108
|
close: () => driver.close(),
|
|
96
109
|
};
|
|
110
|
+
ownedTransactions.set(kernel, {
|
|
111
|
+
assertAvailable: assertOwnedAvailable,
|
|
112
|
+
transaction: (work, optional = {}) => transaction(work, optional),
|
|
113
|
+
});
|
|
114
|
+
return kernel;
|
|
97
115
|
}
|
|
98
116
|
//# sourceMappingURL=kernel-core.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { StorageKernel } from "./port.js";
|
|
2
|
+
/** Private access to the kernel's scope checks; public transactions retain their join semantics. */
|
|
3
|
+
export interface OwnedTransactionControl {
|
|
4
|
+
assertAvailable(): void;
|
|
5
|
+
/** `onSettled` runs after commit/rollback but before the turn lock is released. */
|
|
6
|
+
transaction<T>(work: () => Promise<T>, optional?: {
|
|
7
|
+
onSettled?: () => void;
|
|
8
|
+
}): Promise<T>;
|
|
9
|
+
}
|
|
10
|
+
export declare const ownedTransactions: WeakMap<StorageKernel<unknown>, OwnedTransactionControl>;
|
|
11
|
+
/** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
|
|
12
|
+
export declare function ownedTransactionOf({ kernel }: {
|
|
13
|
+
kernel: StorageKernel<unknown>;
|
|
14
|
+
}, _optional?: {}): OwnedTransactionControl;
|
|
15
|
+
//# sourceMappingURL=owned-transaction.d.ts.map
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export const ownedTransactions = new WeakMap();
|
|
2
|
+
/** Refuse unknown kernels rather than promising atomicity over an executor we do not own. */
|
|
3
|
+
export function ownedTransactionOf({ kernel }, _optional = {}) {
|
|
4
|
+
const control = ownedTransactions.get(kernel);
|
|
5
|
+
if (control === undefined)
|
|
6
|
+
throw new Error("an owned transaction requires a kernel built by buildKernel");
|
|
7
|
+
return control;
|
|
8
|
+
}
|
|
9
|
+
//# sourceMappingURL=owned-transaction.js.map
|
package/dist/kernel/port.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Kysely, RawBuilder } from "kysely";
|
|
2
|
+
export type { RawBuilder } from "kysely";
|
|
2
3
|
/**
|
|
3
4
|
* @file The storage kernel port: the ONE async way a repo reaches its database, on every driver.
|
|
4
5
|
* Package: `@jini-ai/db/kernel` (no driver is imported here; each driver lives in its own subpath).
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ownedTransactions } from "./owned-transaction.js";
|
|
1
2
|
/**
|
|
2
3
|
* @file A kernel whose query-builder statements address one Postgres schema: every `run()` body gets
|
|
3
4
|
* `db.withSchema(schema)` (Kysely's own plugin prefixes each table it names). Used when one
|
|
@@ -12,9 +13,13 @@
|
|
|
12
13
|
export function scopeToSchema(kernel, schema) {
|
|
13
14
|
if (kernel.dialect !== "postgres")
|
|
14
15
|
throw new Error(`schema '${schema}' needs a Postgres kernel, not ${kernel.dialect}`);
|
|
15
|
-
|
|
16
|
+
const scoped = {
|
|
16
17
|
...kernel,
|
|
17
18
|
run: (fn) => kernel.run((db) => fn(db.withSchema(schema))),
|
|
18
19
|
};
|
|
20
|
+
const control = ownedTransactions.get(kernel);
|
|
21
|
+
if (control !== undefined)
|
|
22
|
+
ownedTransactions.set(scoped, control);
|
|
23
|
+
return scoped;
|
|
19
24
|
}
|
|
20
25
|
//# sourceMappingURL=schema-scope.js.map
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { Kysely, SqliteDialect } from "kysely";
|
|
3
3
|
import { buildKernel, TurnLock } from "../index.js";
|
|
4
|
+
import { checkedClients, checkedStates, connectionsByKernel, rawKernelClients } from "../../sqlite/checked-state.js";
|
|
5
|
+
import { ownedTransactions } from "../owned-transaction.js";
|
|
4
6
|
const kernels = new WeakMap();
|
|
5
|
-
/** The reverse of `kernels`, plus the owning kernels {@link openSqliteFileKernel} hands out. */
|
|
6
|
-
const connectionsByKernel = new WeakMap();
|
|
7
7
|
/** One turn lock per database FILE, shared by every connection to it in this process. */
|
|
8
8
|
const fileTurnLocks = new Map();
|
|
9
9
|
function turnLockFor(client) {
|
|
@@ -40,6 +40,11 @@ function bindingShim(client) {
|
|
|
40
40
|
}
|
|
41
41
|
export function sqliteKernel(source) {
|
|
42
42
|
const client = sqliteClientOf(source);
|
|
43
|
+
const checked = checkedClients.has(client);
|
|
44
|
+
if (checkedStates.has(client) && !checked)
|
|
45
|
+
throw new Error("cannot mix raw and checked SQLite kernel ownership");
|
|
46
|
+
if (!checked)
|
|
47
|
+
rawKernelClients.add(client);
|
|
43
48
|
const known = kernels.get(client);
|
|
44
49
|
if (known !== undefined)
|
|
45
50
|
return known;
|
|
@@ -60,7 +65,16 @@ export function sqliteKernel(source) {
|
|
|
60
65
|
return result;
|
|
61
66
|
}
|
|
62
67
|
catch (error) {
|
|
63
|
-
if (
|
|
68
|
+
if (checked) {
|
|
69
|
+
try {
|
|
70
|
+
if (client.inTransaction)
|
|
71
|
+
client.exec("ROLLBACK");
|
|
72
|
+
}
|
|
73
|
+
catch (cleanup) {
|
|
74
|
+
throw new AggregateError([error, cleanup], "SQLite transaction and rollback failed");
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
else if (client.inTransaction)
|
|
64
78
|
client.exec("ROLLBACK");
|
|
65
79
|
throw error;
|
|
66
80
|
}
|
|
@@ -113,6 +127,9 @@ export function openSqliteFileKernel(required, optional = {}) {
|
|
|
113
127
|
close: async () => closeSqliteConnection(client),
|
|
114
128
|
};
|
|
115
129
|
connectionsByKernel.set(owned, client);
|
|
130
|
+
const control = ownedTransactions.get(kernel);
|
|
131
|
+
if (control !== undefined)
|
|
132
|
+
ownedTransactions.set(owned, control);
|
|
116
133
|
return owned;
|
|
117
134
|
}
|
|
118
135
|
/**
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { StorageKernel } from "../kernel/index.js";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
4
|
+
* transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
|
|
5
|
+
* @complexity O(statements).
|
|
6
|
+
*/
|
|
7
|
+
export declare function executeDdl({ kernel, ddl }: {
|
|
8
|
+
kernel: StorageKernel<unknown>;
|
|
9
|
+
ddl: string;
|
|
10
|
+
}, _options?: {}): Promise<void>;
|
|
11
|
+
//# sourceMappingURL=ddl.d.ts.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
/**
|
|
3
|
+
* Runs a `;`-separated DDL script one statement at a time; the runner owns the encompassing
|
|
4
|
+
* transaction. Lives here so migration steps outside kernel/migrate need no Kysely import.
|
|
5
|
+
* @complexity O(statements).
|
|
6
|
+
*/
|
|
7
|
+
export async function executeDdl({ kernel, ddl }, _options = {}) {
|
|
8
|
+
// Kysely executes one SQLite statement at a time.
|
|
9
|
+
for (const statement of ddl.split(";").filter(part => part.trim())) {
|
|
10
|
+
await kernel.execute(sql.raw(statement));
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
//# sourceMappingURL=ddl.js.map
|
package/dist/migrate/index.d.ts
CHANGED
|
@@ -2,7 +2,9 @@
|
|
|
2
2
|
* @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
|
|
3
3
|
* their pinned checksums and the ledger table's name (required, no default).
|
|
4
4
|
*/
|
|
5
|
-
export { assertValidSteps, hasLedger, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
|
|
5
|
+
export { assertValidSteps, hasLedger, migrate, type MigrationOptions, type MigrationReport, runMigrations } from "./runner.js";
|
|
6
|
+
export type { LegacyLedgerMapping } from "./legacy-ledger.js";
|
|
6
7
|
export { MIGRATION_ID, MigrationChecksumError, type MigrationContext, type MigrationStep, UnknownAppliedMigrationError, } from "./step.js";
|
|
7
8
|
export { sourceChecksum } from "./checksum.js";
|
|
9
|
+
export { executeDdl } from "./ddl.js";
|
|
8
10
|
//# sourceMappingURL=index.d.ts.map
|
package/dist/migrate/index.js
CHANGED
|
@@ -2,7 +2,8 @@
|
|
|
2
2
|
* @file `@jini-ai/db/migrate`: one migration runner for every dialect. The consumer owns its steps,
|
|
3
3
|
* their pinned checksums and the ledger table's name (required, no default).
|
|
4
4
|
*/
|
|
5
|
-
export { assertValidSteps, hasLedger, runMigrations } from "./runner.js";
|
|
5
|
+
export { assertValidSteps, hasLedger, migrate, runMigrations } from "./runner.js";
|
|
6
6
|
export { MIGRATION_ID, MigrationChecksumError, UnknownAppliedMigrationError, } from "./step.js";
|
|
7
7
|
export { sourceChecksum } from "./checksum.js";
|
|
8
|
+
export { executeDdl } from "./ddl.js";
|
|
8
9
|
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { MigrationStep } from "./step.js";
|
|
2
|
+
import type { Ledger, LedgerRow } from "./runner.js";
|
|
3
|
+
import type { StorageDialect } from "../kernel/port.js";
|
|
4
|
+
/** Persisted identities remain host-owned; no existing row is rewritten. */
|
|
5
|
+
export interface LegacyLedgerMapping {
|
|
6
|
+
columns: {
|
|
7
|
+
version: string;
|
|
8
|
+
name: string;
|
|
9
|
+
checksum: string;
|
|
10
|
+
appliedAt: string;
|
|
11
|
+
};
|
|
12
|
+
identities: Readonly<Record<string, {
|
|
13
|
+
version: number;
|
|
14
|
+
name: string;
|
|
15
|
+
}>>;
|
|
16
|
+
timestamps?: "database-default" | "iso";
|
|
17
|
+
}
|
|
18
|
+
/** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
|
|
19
|
+
export declare function validateLegacyMapping({ mapping, steps }: {
|
|
20
|
+
mapping: LegacyLedgerMapping;
|
|
21
|
+
steps: readonly MigrationStep[];
|
|
22
|
+
}, _optional?: {}): void;
|
|
23
|
+
export declare function ensureLegacyLedger({ ledger, mapping, dialect }: {
|
|
24
|
+
ledger: Ledger;
|
|
25
|
+
mapping: LegacyLedgerMapping;
|
|
26
|
+
dialect: StorageDialect;
|
|
27
|
+
}, _optional?: {}): Promise<void>;
|
|
28
|
+
/** Read in numeric version order, matching both parts of each persisted identity. */
|
|
29
|
+
export declare function readLegacyLedger({ ledger, mapping }: {
|
|
30
|
+
ledger: Ledger;
|
|
31
|
+
mapping: LegacyLedgerMapping;
|
|
32
|
+
}, _optional?: {}): Promise<LedgerRow[]>;
|
|
33
|
+
export declare function insertLegacyRow({ ledger, mapping, step, timestamp }: {
|
|
34
|
+
ledger: Ledger;
|
|
35
|
+
mapping: LegacyLedgerMapping;
|
|
36
|
+
step: MigrationStep;
|
|
37
|
+
timestamp: () => string;
|
|
38
|
+
}, _optional?: {}): Promise<void>;
|
|
39
|
+
//# sourceMappingURL=legacy-ledger.d.ts.map
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
/** Validate the whole map before backups, DDL or migration work. O(steps + identities). */
|
|
3
|
+
export function validateLegacyMapping({ mapping, steps }, _optional = {}) {
|
|
4
|
+
const columns = Object.values(mapping.columns);
|
|
5
|
+
if (columns.some((column) => typeof column !== "string" || column.length === 0) || new Set(columns).size !== 4) {
|
|
6
|
+
throw new Error("legacy ledger columns must be four distinct nonempty identifiers");
|
|
7
|
+
}
|
|
8
|
+
let previous = 0;
|
|
9
|
+
const names = new Set();
|
|
10
|
+
for (const step of steps) {
|
|
11
|
+
const identity = mapping.identities[step.id];
|
|
12
|
+
if (!Object.hasOwn(mapping.identities, step.id) || identity === undefined)
|
|
13
|
+
throw new Error(`missing legacy identity for ${step.id}`);
|
|
14
|
+
validateIdentity({ identity });
|
|
15
|
+
// Rows are read back in version order, so versions must ascend with the steps for an ordered-prefix check.
|
|
16
|
+
if (identity.version <= previous || names.has(identity.name))
|
|
17
|
+
throw new Error("legacy identities must be unique with versions ascending in step order");
|
|
18
|
+
previous = identity.version;
|
|
19
|
+
names.add(identity.name);
|
|
20
|
+
}
|
|
21
|
+
if (Object.keys(mapping.identities).length !== steps.length)
|
|
22
|
+
throw new Error("legacy identities must match the supplied steps");
|
|
23
|
+
}
|
|
24
|
+
function validateIdentity({ identity }, _optional = {}) {
|
|
25
|
+
if (!Number.isSafeInteger(identity.version) || identity.version <= 0)
|
|
26
|
+
throw new Error("legacy versions must be positive safe integers");
|
|
27
|
+
if (typeof identity.name !== "string" || identity.name.length === 0)
|
|
28
|
+
throw new Error("legacy names must be nonempty strings");
|
|
29
|
+
}
|
|
30
|
+
export async function ensureLegacyLedger({ ledger, mapping, dialect }, _optional = {}) {
|
|
31
|
+
const c = mapping.columns;
|
|
32
|
+
// Postgres integer is only 32-bit; mapped versions accept the full safe JS integer range.
|
|
33
|
+
const versionType = dialect === "sqlite" ? "integer" : "bigint";
|
|
34
|
+
await ledger.run((db) => db.schema.createTable(ledger.table).ifNotExists()
|
|
35
|
+
.addColumn(c.version, versionType, (column) => column.primaryKey())
|
|
36
|
+
.addColumn(c.name, "text", (column) => column.notNull())
|
|
37
|
+
.addColumn(c.checksum, "text", (column) => column.notNull())
|
|
38
|
+
.addColumn(c.appliedAt, "text", (column) => column.notNull().defaultTo(sql `CURRENT_TIMESTAMP`))
|
|
39
|
+
.execute());
|
|
40
|
+
}
|
|
41
|
+
/** Read in numeric version order, matching both parts of each persisted identity. */
|
|
42
|
+
export async function readLegacyLedger({ ledger, mapping }, _optional = {}) {
|
|
43
|
+
const c = mapping.columns;
|
|
44
|
+
const byVersion = new Map(Object.entries(mapping.identities).map(([id, identity]) => [identity.version, { id, ...identity }]));
|
|
45
|
+
const rows = await ledger.run((db) => db.selectFrom(ledger.table).select([
|
|
46
|
+
sql `${sql.id(c.version)}`.as("version"),
|
|
47
|
+
sql `${sql.id(c.name)}`.as("name"),
|
|
48
|
+
sql `${sql.id(c.checksum)}`.as("checksum"),
|
|
49
|
+
sql `${sql.id(c.appliedAt)}`.as("applied_at"),
|
|
50
|
+
]).orderBy(sql.id(c.version)).execute());
|
|
51
|
+
return rows.map((row) => {
|
|
52
|
+
const identity = byVersion.get(row.version);
|
|
53
|
+
if (identity !== undefined && identity.name !== row.name)
|
|
54
|
+
throw new Error(`legacy migration name drift at version ${row.version}`);
|
|
55
|
+
return { id: identity?.id ?? `legacy:${row.version}:${row.name}`, checksum: row.checksum, applied_at: row.applied_at };
|
|
56
|
+
});
|
|
57
|
+
}
|
|
58
|
+
export async function insertLegacyRow({ ledger, mapping, step, timestamp }, _optional = {}) {
|
|
59
|
+
const c = mapping.columns;
|
|
60
|
+
const identity = mapping.identities[step.id];
|
|
61
|
+
const row = { [c.version]: identity.version, [c.name]: identity.name, [c.checksum]: step.checksum };
|
|
62
|
+
if (mapping.timestamps === "iso")
|
|
63
|
+
row[c.appliedAt] = timestamp();
|
|
64
|
+
// The builder (not raw SQL) so the ledger's `withSchema` also places this insert.
|
|
65
|
+
await ledger.run((db) => db.insertInto(ledger.table).values(row).execute());
|
|
66
|
+
}
|
|
67
|
+
//# sourceMappingURL=legacy-ledger.js.map
|
package/dist/migrate/runner.d.ts
CHANGED
|
@@ -1,14 +1,65 @@
|
|
|
1
|
+
import { type Kysely } from "kysely";
|
|
2
|
+
import { type Clock } from "@jini-ai/core/primitives";
|
|
1
3
|
import { type StorageKernel } from "../kernel/index.js";
|
|
4
|
+
import { type LegacyLedgerMapping } from "./legacy-ledger.js";
|
|
2
5
|
import { type MigrationStep } from "./step.js";
|
|
6
|
+
/**
|
|
7
|
+
* @file The migration runner: applies an ordered list of {@link MigrationStep}s to one database on
|
|
8
|
+
* any dialect and records each in a ledger table the consumer names (required, no default: this
|
|
9
|
+
* package ships no tables, so no name of its own can leak into a consumer's database).
|
|
10
|
+
*
|
|
11
|
+
* - Default ledger `<ledgerTable>(id, checksum, applied_at)`, created by the runner inside the first step's
|
|
12
|
+
* transaction (so a step's pre-change backup has no trace of the runner), same on every dialect.
|
|
13
|
+
* - Before anything is applied, every recorded id must be one this runtime knows
|
|
14
|
+
* (unless an additive history opts into `allowUnknownApplied`)
|
|
15
|
+
* ({@link UnknownAppliedMigrationError}) with the checksum this runtime has
|
|
16
|
+
* ({@link MigrationChecksumError}). Nothing is applied on a mismatch.
|
|
17
|
+
* - Serialized: by default each pending step runs in ONE kernel transaction that first takes
|
|
18
|
+
* `lockKey(<ledgerTable>)` (Postgres advisory lock; SQLite's `BEGIN IMMEDIATE` write lock) and
|
|
19
|
+
* re-reads and verifies the full ledger, so two processes starting at once apply a step exactly once
|
|
20
|
+
* and an older runtime refuses history committed by a newer one while it was waiting.
|
|
21
|
+
* - A kernel without interactive transactions is refused (`require`), never downgraded.
|
|
22
|
+
* - Given {@link MigrationOptions.backupPath}, a database that already holds tables is copied there
|
|
23
|
+
* once, outside any transaction, before the first pending step (ledger absent or behind). Nothing
|
|
24
|
+
* pending, an empty database or a driver without `backup` (Postgres): no copy.
|
|
25
|
+
* - One runner, several histories: each history names its own ledger
|
|
26
|
+
* ({@link MigrationOptions.ledgerTable}) and, on Postgres, may name the schema that ledger lives in
|
|
27
|
+
* ({@link MigrationOptions.schema}). Ledger statements
|
|
28
|
+
* go through Kysely `withSchema`, never `SET search_path` (no session state on a shared PGlite).
|
|
29
|
+
*/
|
|
30
|
+
export interface LedgerRow {
|
|
31
|
+
id: string;
|
|
32
|
+
checksum: string;
|
|
33
|
+
applied_at: string;
|
|
34
|
+
}
|
|
35
|
+
type LedgerDb = Record<string, LedgerRow>;
|
|
3
36
|
export interface MigrationOptions {
|
|
4
37
|
/** The ledger table (REQUIRED, no default); also the migration lock's key. */
|
|
5
38
|
ledgerTable: string;
|
|
39
|
+
/** Additive host histories may be opened by an older runtime; known checksums still must match. */
|
|
40
|
+
allowUnknownApplied?: boolean;
|
|
6
41
|
/** Where to copy an existing database before the first pending step changes it (see the file header). */
|
|
7
42
|
backupPath?: string;
|
|
8
43
|
/** Postgres only: the schema holding the ledger, created with it when missing. */
|
|
9
44
|
schema?: string;
|
|
10
45
|
/** Names the newer runtime in {@link UnknownAppliedMigrationError}'s message (default "version"). */
|
|
11
46
|
appName?: string;
|
|
47
|
+
/** Opt in to one owned transaction for the entire pending batch. Default: per-step commits. */
|
|
48
|
+
atomicity?: "step" | "batch";
|
|
49
|
+
/** Opt in to requiring recorded history to be an exact prefix of the supplied steps. */
|
|
50
|
+
historyCheck?: "known" | "ordered-prefix";
|
|
51
|
+
/** Sampled once for each inserted ISO timestamp, never for already-recorded rows. */
|
|
52
|
+
clock?: Clock;
|
|
53
|
+
/** Explicit persisted identities and column names for an existing version/name ledger. */
|
|
54
|
+
legacyLedger?: LegacyLedgerMapping;
|
|
55
|
+
}
|
|
56
|
+
/** Where one history's ledger lives, resolved from {@link MigrationOptions}. */
|
|
57
|
+
export interface Ledger {
|
|
58
|
+
readonly table: string;
|
|
59
|
+
readonly schema: string | undefined;
|
|
60
|
+
readonly lockKey: string;
|
|
61
|
+
readonly mapping: LegacyLedgerMapping | undefined;
|
|
62
|
+
run<T>(fn: (db: Kysely<LedgerDb>) => Promise<T>): Promise<T>;
|
|
12
63
|
}
|
|
13
64
|
export interface MigrationReport {
|
|
14
65
|
/** Steps this call applied, in order. */
|
|
@@ -19,6 +70,12 @@ export interface MigrationReport {
|
|
|
19
70
|
}
|
|
20
71
|
/** Throws on duplicate, unordered or malformed ids and on a checksum that is not sha256 hex. */
|
|
21
72
|
export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
|
|
73
|
+
/** Object-input facade over the existing runner; all extensions remain opt-in. */
|
|
74
|
+
export declare function migrate(required: {
|
|
75
|
+
kernel: StorageKernel<unknown>;
|
|
76
|
+
steps: readonly MigrationStep[];
|
|
77
|
+
ledgerTable: string;
|
|
78
|
+
}, optional?: Omit<MigrationOptions, "ledgerTable">): Promise<MigrationReport>;
|
|
22
79
|
/**
|
|
23
80
|
* Applies every pending step of `steps`, in order, to `kernel`'s database.
|
|
24
81
|
*
|
|
@@ -30,4 +87,5 @@ export declare function assertValidSteps(steps: readonly MigrationStep[]): void;
|
|
|
30
87
|
export declare function runMigrations(kernel: StorageKernel<unknown>, steps: readonly MigrationStep[], options: MigrationOptions): Promise<MigrationReport>;
|
|
31
88
|
/** True when `kernel`'s database has the ledger `ledgerTable` (it has been through {@link runMigrations}). */
|
|
32
89
|
export declare function hasLedger(kernel: StorageKernel<unknown>, ledgerTable: string): Promise<boolean>;
|
|
90
|
+
export {};
|
|
33
91
|
//# sourceMappingURL=runner.d.ts.map
|