@jini-ai/db 0.3.0 → 0.3.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.
Files changed (63) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/dist/core/artifact-naming.d.ts +4 -1
  3. package/dist/core/artifact-naming.js +3 -4
  4. package/dist/core/index.d.ts +1 -0
  5. package/dist/core/messages.d.ts +1 -1
  6. package/dist/core/pg-types.d.ts +52 -0
  7. package/dist/core/pg-types.js +8 -0
  8. package/dist/core/transfer-naming.d.ts +10 -0
  9. package/dist/core/transfer-naming.js +2 -0
  10. package/dist/kernel/postgres/driver.d.ts +1 -1
  11. package/dist/kernel/postgres/driver.js +1 -1
  12. package/dist/kernel/postgres/pglite-socket.d.ts +1 -1
  13. package/dist/kernel/postgres/pglite-socket.js +1 -1
  14. package/dist/pg-fixture.d.ts +50 -0
  15. package/dist/pg-fixture.js +84 -0
  16. package/dist/pglite/owner.js +7 -0
  17. package/dist/postgres/index.d.ts +1 -1
  18. package/dist/postgres/index.js +1 -1
  19. package/dist/postgres/types.d.ts +1 -52
  20. package/dist/postgres/types.js +2 -13
  21. package/dist/recovery/deep-link.d.ts +60 -0
  22. package/dist/recovery/deep-link.js +16 -0
  23. package/dist/recovery/degraded-banners.d.ts +40 -0
  24. package/dist/recovery/degraded-banners.js +69 -0
  25. package/dist/recovery/disclosure.d.ts +58 -0
  26. package/dist/recovery/disclosure.js +55 -0
  27. package/dist/recovery/evaluate-boot-migration-policy.d.ts +41 -0
  28. package/dist/recovery/evaluate-boot-migration-policy.js +50 -0
  29. package/dist/recovery/hook-policy.d.ts +9 -0
  30. package/dist/recovery/hook-policy.js +2 -0
  31. package/dist/recovery/index.d.ts +15 -0
  32. package/dist/recovery/index.js +13 -0
  33. package/dist/recovery/lookup-adapters.d.ts +40 -0
  34. package/dist/recovery/lookup-adapters.js +44 -0
  35. package/dist/recovery/migrate-forward-execute.d.ts +65 -0
  36. package/dist/recovery/migrate-forward-execute.js +68 -0
  37. package/dist/recovery/migrate-forward-hooks.d.ts +118 -0
  38. package/dist/recovery/migrate-forward-hooks.js +85 -0
  39. package/dist/recovery/operation-lock.d.ts +78 -0
  40. package/dist/recovery/operation-lock.js +58 -0
  41. package/dist/recovery/reconcile-interrupted-migration.d.ts +73 -0
  42. package/dist/recovery/reconcile-interrupted-migration.js +47 -0
  43. package/dist/recovery/recovery-orchestrator.d.ts +204 -0
  44. package/dist/recovery/recovery-orchestrator.js +96 -0
  45. package/dist/recovery/restore-hooks.d.ts +105 -0
  46. package/dist/recovery/restore-hooks.js +154 -0
  47. package/dist/recovery/restore-point-create.d.ts +80 -0
  48. package/dist/recovery/restore-point-create.js +37 -0
  49. package/dist/secrets-vault/index.d.ts +2 -0
  50. package/dist/secrets-vault/index.js +2 -0
  51. package/dist/secrets-vault/repo.sql.d.ts +82 -0
  52. package/dist/secrets-vault/repo.sql.js +176 -0
  53. package/dist/sqlite/inspect.d.ts +5 -1
  54. package/dist/sqlite/inspect.js +47 -18
  55. package/dist/sqlite/open.d.ts +1 -1
  56. package/dist/sqlite/open.js +3 -3
  57. package/dist/sqlite/restore-types.d.ts +7 -3
  58. package/dist/tools/surface-port.d.ts +11 -35
  59. package/dist/tools/transfer-tools.js +36 -37
  60. package/dist/transfer/internal-ddl.d.ts +3 -0
  61. package/dist/transfer/internal-ddl.js +6 -2
  62. package/dist/transfer/types.d.ts +6 -9
  63. package/package.json +57 -6
@@ -41,6 +41,8 @@ export interface DbIntegrityReport {
41
41
  issues: DbIntegrityIssue[];
42
42
  elapsedMs: number;
43
43
  generatedAt: number;
44
+ /** Strict counts when requested by a stopped database transfer. */
45
+ rowCounts?: DaemonDbTableInfo[] | undefined;
44
46
  }
45
47
  export interface VerifyDbOptions {
46
48
  db: SqliteDb;
@@ -56,5 +58,7 @@ export interface VerifyDbOptions {
56
58
  * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
57
59
  * propagating — a caller polling DB health should always get a report, not an exception.
58
60
  */
59
- export declare function verifySqliteIntegrity(opts: VerifyDbOptions): DbIntegrityReport;
61
+ export declare function verifySqliteIntegrity(opts: VerifyDbOptions, { includeRowCounts }?: {
62
+ includeRowCounts?: boolean;
63
+ }): DbIntegrityReport;
60
64
  //# sourceMappingURL=inspect.d.ts.map
@@ -38,40 +38,56 @@ export async function inspectSqliteDatabase(input) {
38
38
  catch {
39
39
  schemaVersion = null;
40
40
  }
41
- // 2. Table list with row counts.
41
+ // 2. Table list with row counts (the diagnostics contract is deliberately forgiving).
42
+ const tables = readSqliteTableCounts({ db });
43
+ // 3. File size = primary + -wal + -shm so the number matches du.
44
+ const sizeBytes = await sumFileSizes([file, `${file}-wal`, `${file}-shm`]);
45
+ return {
46
+ kind: 'sqlite',
47
+ location: file,
48
+ sizeBytes,
49
+ schemaVersion,
50
+ tables,
51
+ generatedAt: Date.now(),
52
+ };
53
+ }
54
+ /** Per-table counts shared by diagnostics and strict transfer verification. Diagnostics retains
55
+ * its ASCII-name/zero-on-error compatibility contract; transfers quote all schema-owned names and
56
+ * fail closed on any query error, because a missing table must never compare equal to an empty one.
57
+ * @complexity O(all table rows), one metadata query plus one count query per table.
58
+ */
59
+ function readSqliteTableCounts({ db }, { strict = false } = {}) {
42
60
  const tables = [];
43
61
  try {
44
- const names = db.prepare(`SELECT name FROM sqlite_master WHERE type='table' ORDER BY name`).all();
62
+ const names = db.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").all();
45
63
  for (const { name } of names) {
46
- if (isSystemTable(name))
64
+ if (strict ? name.startsWith('sqlite_') : isSystemTable(name))
47
65
  continue;
48
66
  try {
49
- const safe = sanitizeTableName(name);
67
+ const safe = strict ? name : sanitizeTableName(name);
50
68
  if (!safe)
51
69
  continue;
52
- const row = db.prepare(`SELECT count(*) AS c FROM "${safe}"`).get();
70
+ const quoted = '"' + safe.replaceAll('"', '""') + '"';
71
+ const row = db.prepare(`SELECT count(*) AS c FROM ${quoted}`).get();
72
+ if (strict && (!row || !Number.isSafeInteger(row.c) || row.c < 0))
73
+ throw new Error(`Could not count table ${name}.`);
53
74
  tables.push({ name: safe, rowCount: row?.c ?? 0 });
54
75
  }
55
- catch {
76
+ catch (error) {
77
+ if (strict)
78
+ throw error;
56
79
  // A malformed view / corrupted table shouldn't fail the whole report; record 0 rows.
57
80
  tables.push({ name, rowCount: 0 });
58
81
  }
59
82
  }
60
83
  }
61
- catch {
84
+ catch (error) {
85
+ if (strict)
86
+ throw error;
62
87
  // ignore — empty tables[] surfaces "cannot read schema" to the caller (a CLI shows 0 tables,
63
88
  // which is itself a useful signal).
64
89
  }
65
- // 3. File size = primary + -wal + -shm so the number matches du.
66
- const sizeBytes = await sumFileSizes([file, `${file}-wal`, `${file}-shm`]);
67
- return {
68
- kind: 'sqlite',
69
- location: file,
70
- sizeBytes,
71
- schemaVersion,
72
- tables,
73
- generatedAt: Date.now(),
74
- };
90
+ return tables;
75
91
  }
76
92
  async function sumFileSizes(paths) {
77
93
  let total = 0;
@@ -103,7 +119,7 @@ function sanitizeTableName(name) {
103
119
  * A pragma that throws is itself recorded as one `integrity`/`foreign_key` issue rather than
104
120
  * propagating — a caller polling DB health should always get a report, not an exception.
105
121
  */
106
- export function verifySqliteIntegrity(opts) {
122
+ export function verifySqliteIntegrity(opts, { includeRowCounts = false } = {}) {
107
123
  const { db, quick = false } = opts;
108
124
  const startedAt = Date.now();
109
125
  const issues = [];
@@ -111,6 +127,9 @@ export function verifySqliteIntegrity(opts) {
111
127
  const pragma = quick ? 'quick_check' : 'integrity_check';
112
128
  try {
113
129
  const rows = db.pragma(pragma);
130
+ if (includeRowCounts && (rows.length !== 1 || String(rows[0]?.[pragma] ?? Object.values(rows[0] ?? {})[0]).toLowerCase() !== 'ok')) {
131
+ issues.push({ kind: 'integrity', message: 'A stopped transfer requires exactly one successful integrity result.' });
132
+ }
114
133
  for (const row of rows) {
115
134
  // SQLite returns the string under either `integrity_check`, `quick_check`, or just the
116
135
  // first column. Normalise to the first string-valued field.
@@ -142,7 +161,17 @@ export function verifySqliteIntegrity(opts) {
142
161
  catch (err) {
143
162
  issues.push({ kind: 'foreign_key', message: `pragma foreign_key_check threw: ${err.message}` });
144
163
  }
164
+ let rowCounts;
165
+ if (includeRowCounts && issues.length === 0) {
166
+ try {
167
+ rowCounts = readSqliteTableCounts({ db }, { strict: true });
168
+ }
169
+ catch (error) {
170
+ issues.push({ kind: 'integrity', message: `row count verification failed: ${error.message}` });
171
+ }
172
+ }
145
173
  return {
174
+ ...(includeRowCounts ? { rowCounts } : {}),
146
175
  ok: issues.length === 0,
147
176
  mode: quick ? 'quick_check' : 'integrity_check',
148
177
  issues,
@@ -54,5 +54,5 @@ export declare const DEFAULT_PRAGMAS: readonly string[];
54
54
  * @throws Any error from the recovery hook, opener, or pragma application.
55
55
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
56
56
  */
57
- export declare function openSqliteConnection<Connection extends SqliteClient>(options: OpenSqliteConnectionOptions<Connection>): Connection;
57
+ export declare function openSqliteConnection<Connection extends SqliteClient>(required: Pick<OpenSqliteConnectionOptions<Connection>, "filePath" | "open">, options?: Pick<OpenSqliteConnectionOptions<Connection>, "recover" | "pragmas">): Connection;
58
58
  //# sourceMappingURL=open.d.ts.map
@@ -32,9 +32,9 @@ export const DEFAULT_PRAGMAS = [
32
32
  * @throws Any error from the recovery hook, opener, or pragma application.
33
33
  * @complexity O(p) calls for p pragmas; storage costs belong to the injected driver.
34
34
  */
35
- export function openSqliteConnection(options) {
36
- options.recover?.(options.filePath);
37
- const connection = options.open(options.filePath, {});
35
+ export function openSqliteConnection(required, options = {}) {
36
+ options.recover?.({ filePath: required.filePath }, {});
37
+ const connection = required.open({ filePath: required.filePath }, {});
38
38
  for (const pragma of options.pragmas ?? DEFAULT_PRAGMAS) {
39
39
  connection.pragma(pragma);
40
40
  }
@@ -7,7 +7,7 @@
7
7
  * package boundary cleanly. See `open.ts`'s module doc for the measured failure that made this a
8
8
  * rule rather than a preference.
9
9
  */
10
- import type { SqliteClient, SqliteOpener } from './types.js';
10
+ import type { SqliteClient } from './types.js';
11
11
  /**
12
12
  * A caller-injected hook run against `filePath` BEFORE the connection is opened.
13
13
  *
@@ -17,10 +17,14 @@ import type { SqliteClient, SqliteOpener } from './types.js';
17
17
  * supplied it runs for every path, including `:memory:`. A host with file-only recovery must make
18
18
  * its hook a no-op for ephemeral connections and hermetic tests, where there is nothing to recover.
19
19
  */
20
- export type SqliteRecoveryHook = (filePath: string) => void;
20
+ export type SqliteRecoveryHook = (required: {
21
+ filePath: string;
22
+ }, options?: Record<string, never>) => void;
21
23
  export interface OpenSqliteConnectionOptions<Connection extends SqliteClient = SqliteClient> {
22
24
  /** The consumer opens with its own driver copy. */
23
- readonly open: SqliteOpener<Connection>;
25
+ readonly open: (required: {
26
+ filePath: string;
27
+ }, options: Record<string, never>) => Connection;
24
28
  /** Filesystem path, or `':memory:'` for an ephemeral connection. */
25
29
  readonly filePath: string;
26
30
  /**
@@ -1,42 +1,18 @@
1
+ import type { ApprovalAnswer, ToolExecutionContext, ToolExecutionOptions } from "@jini-ai/core";
1
2
  /** Structural surface protocol: transport, confirmation policy and builders belong to the consumer. */
2
- import type { SurfaceEmission, SurfaceEmitter } from "@jini-ai/core";
3
+ import type { SurfaceEmission, SurfaceExchangeConversation, SurfaceExchangeStore, SurfaceAskThenReport } from "@jini-ai/core";
4
+ export type { SurfaceExchangeConversation as SurfaceExchange, SurfaceMessage } from "@jini-ai/core";
3
5
  import type { DatabaseTransferPlan } from "./plan-store.js";
4
- export type SurfaceMessage = {
5
- status: "received";
6
- params: Record<string, unknown>;
7
- } | {
8
- status: "expired" | "abandoned";
9
- };
10
- export interface SurfaceExchange {
11
- readonly id: string;
12
- send(emission: SurfaceEmission): Promise<void>;
13
- receive(): Promise<SurfaceMessage>;
14
- close(): void;
15
- /** When the exchange stops waiting, in epoch ms, if the host tracks one. Read right before the
16
- * confirmation is built and handed to it, so the host's card can count down and close on time. */
17
- expiresAtMs?(): number;
18
- }
19
6
  export interface TransferSurfacePorts {
20
- open(binding: {
21
- toolId: string;
22
- principalId: string;
23
- }, emit: SurfaceEmitter): SurfaceExchange;
24
- /** Must close the exchange after receiving/classifying a decision, including errors. */
25
- resolveDecision(exchange: SurfaceExchange, emission: SurfaceEmission): Promise<{
26
- confirmed: true;
27
- } | {
28
- confirmed: false;
29
- reason: "declined" | "expired" | "abandoned";
30
- }>;
7
+ open(required: Parameters<SurfaceExchangeStore["open"]>[0], optional?: Record<string, never>): SurfaceExchangeConversation;
8
+ /** Host transport only. The core approval owner calls it once for a replacement plan;
9
+ * the host binds principal/tool/expiry and never accepts model input as consent. */
10
+ confirmApproval(required: {
11
+ ctx: ToolExecutionContext;
12
+ plan: DatabaseTransferPlan;
13
+ }, optional: ToolExecutionOptions): Promise<ApprovalAnswer>;
31
14
  /** Must close in finally; outcome-delivery failures cannot replace a settled result. */
32
- askThenReport<T>(exchange: SurfaceExchange, emission: SurfaceEmission, handle: (answer: SurfaceMessage) => Promise<{
33
- result: T;
34
- outcome?: SurfaceEmission;
35
- }>): Promise<T>;
36
- /** `optional.expiresAtMs` is the exchange's deadline when it reports one (see `SurfaceExchange.expiresAtMs`). */
37
- confirmation(plan: DatabaseTransferPlan, exchangeId: string, optional?: {
38
- readonly expiresAtMs?: number;
39
- }): SurfaceEmission;
15
+ askThenReport: SurfaceAskThenReport;
40
16
  destinationForm(exchangeId: string): SurfaceEmission;
41
17
  destinationOutcome(input: {
42
18
  exchangeId: string;
@@ -1,5 +1,5 @@
1
1
  import { readFile, unlink } from "node:fs/promises";
2
- import { ToolInputError } from "@jini-ai/core";
2
+ import { createApprovalHandler, ToolInputError } from "@jini-ai/core";
3
3
  import { countSourceRows, inspectTarget, runCopy, planTransfer, SourceSchemaMismatchError, IncompleteTransferPlanError, InvalidConnectionStringError, LEFT_OUT_REASON } from "../transfer/index.js";
4
4
  import { DOMAIN, PLAN_TOOL_ID, STATUS_TOOL_ID, RUN_PERMISSION, SNAPSHOT_SCOPE_ID, MIN_SERVER_VERSION_NUM, getDatabaseTransferAgentToolCatalog } from "./transfer-catalog.js";
5
5
  import { defaultDbMessages } from "../core/messages.js";
@@ -181,23 +181,6 @@ async function handlePlan(deps, ctx) {
181
181
  });
182
182
  return planResult(plan);
183
183
  }
184
- async function askToConfirm(ctx, surfaces, plan, emitSurface) {
185
- const exchange = surfaces.open({ toolId: DATABASE_TRANSFER_RUN_TOOL_ID, principalId: ctx.principal.id }, emitSurface);
186
- const emission = surfaces.confirmation(plan, exchange.id, exchange.expiresAtMs ? { expiresAtMs: exchange.expiresAtMs() } : {});
187
- const closeOnAbort = () => exchange.close();
188
- ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
189
- try {
190
- const outcome = await surfaces.resolveDecision(exchange, emission);
191
- if (outcome.confirmed)
192
- return { confirmed: true };
193
- if (outcome.reason === "declined")
194
- return { confirmed: false, result: { copied: false, cancelled: true } };
195
- return { confirmed: false, result: { copied: false, cancelled: false, reason: outcome.reason } };
196
- }
197
- finally {
198
- ctx.signal.removeEventListener("abort", closeOnAbort);
199
- }
200
- }
201
184
  /** @complexity O(total rows), streamed. */
202
185
  async function copyPlanned(deps, plan) {
203
186
  const sources = snapshotSources(deps, plan.snapshot, plan.chatSnapshot);
@@ -238,23 +221,39 @@ const PLAN_TAKE_MESSAGES = {
238
221
  PLAN_NOT_FOUND: "no copy plan with that planId is waiting (a planId works once, for this principal, and a server restart drops plans). Call database_transfer_plan again.",
239
222
  PLAN_EXPIRED: "that copy plan expired (plans last 10 minutes). Call database_transfer_plan again.",
240
223
  };
224
+ /** The plan store retains actor/workspace binding and one-shot consumption. Core owns consent;
225
+ * the host supplies only transport, and permission is freshly evaluated after the human wait. */
241
226
  async function handleRun(deps, surfaces, ctx, optional = {}) {
242
- const planId = deps.ports.readers.string(deps.ports.readers.inputRecord(ctx.input), "planId");
243
- await deps.ports.requirePermission({ principalId: ctx.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
244
- if (ctx.signal.aborted)
245
- return { copied: false, cancelled: false, reason: "abandoned" };
246
- const taken = deps.ports.plans.take({ planId, principalId: ctx.principal.id, workspaceId: deps.ports.workspaceId });
247
- if (!taken.ok)
248
- return { copied: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] };
249
- if (taken.plan.replaces !== null) {
250
- if (!optional.emitSurface) {
251
- throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
252
- }
253
- const decision = await askToConfirm(ctx, surfaces, taken.plan, optional.emitSurface);
254
- if (!decision.confirmed)
255
- return decision.result;
256
- }
257
- return copyPlanned(deps, taken.plan);
227
+ const handler = createApprovalHandler({
228
+ prepare: async ({ ctx: snapshot }) => {
229
+ const planId = deps.ports.readers.string(deps.ports.readers.inputRecord(snapshot.input), "planId");
230
+ await deps.ports.requirePermission({ principalId: snapshot.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
231
+ const taken = deps.ports.plans.take({ planId, principalId: snapshot.principal.id, workspaceId: deps.ports.workspaceId });
232
+ if (!taken.ok)
233
+ return { refusal: { copied: false, cancelled: false, code: taken.code, message: PLAN_TAKE_MESSAGES[taken.code] } };
234
+ return { plan: taken.plan };
235
+ },
236
+ describe: ({ prepared }) => "refusal" in prepared
237
+ ? { ask: false, description: undefined }
238
+ : { ask: prepared.plan.replaces !== null, description: prepared.plan },
239
+ askHuman: ({ ctx: snapshot, description }, options) => {
240
+ if (!options.emitSurface)
241
+ throw new ToolInputError({ message: `${DATABASE_TRANSFER_RUN_TOOL_ID}: this execution context has no interactive confirmation channel (no emitSurface), so replacement cannot be confirmed here. Nothing was copied.` });
242
+ if (!description)
243
+ throw new ToolInputError({ message: "No transfer plan can be approved. Nothing was copied." });
244
+ return surfaces.confirmApproval({ ctx: snapshot, plan: description }, options);
245
+ },
246
+ notConfirmed: ({ reason }) => reason === "declined" ? { copied: false, cancelled: true } : { copied: false, cancelled: false, reason },
247
+ run: async ({ ctx: snapshot, prepared }) => {
248
+ if ("refusal" in prepared)
249
+ return prepared.refusal;
250
+ await deps.ports.requirePermission({ principalId: snapshot.principal.id, permission: RUN_PERMISSION, entityType: DOMAIN });
251
+ if (snapshot.signal.aborted)
252
+ return { copied: false, cancelled: false, reason: "abandoned" };
253
+ return copyPlanned(deps, prepared.plan);
254
+ },
255
+ });
256
+ return handler(ctx, optional);
258
257
  }
259
258
  function failedDestination(surfaces, exchangeId, code, message) {
260
259
  return { result: { saved: false, code, message }, outcome: surfaces.destinationOutcome({ exchangeId, state: "failure", message: `Not saved: ${message}.` }) };
@@ -298,11 +297,11 @@ async function handleSetDestination(deps, surfaces, ctx, optional = {}) {
298
297
  }
299
298
  if (ctx.signal.aborted)
300
299
  return { saved: false, reason: "abandoned" };
301
- const exchange = surfaces.open({ toolId: SET_DESTINATION_TOOL_ID, principalId: ctx.principal.id }, optional.emitSurface);
302
- const closeOnAbort = () => exchange.close();
300
+ const exchange = surfaces.open({ binding: { toolId: SET_DESTINATION_TOOL_ID, principalId: ctx.principal.id }, emit: optional.emitSurface });
301
+ const closeOnAbort = () => exchange.close({});
303
302
  ctx.signal.addEventListener("abort", closeOnAbort, { once: true });
304
303
  try {
305
- return await surfaces.askThenReport(exchange, surfaces.destinationForm(exchange.id), (answer) => handleDestinationAnswer(deps, surfaces, exchange.id, answer));
304
+ return await surfaces.askThenReport({ exchange, confirmationEmission: surfaces.destinationForm(exchange.id), handle: (answer) => handleDestinationAnswer(deps, surfaces, exchange.id, answer) });
306
305
  }
307
306
  finally {
308
307
  ctx.signal.removeEventListener("abort", closeOnAbort);
@@ -12,6 +12,9 @@ export declare function fitIdentifier(name: string): string;
12
12
  export declare function createTableSql(schema: string, table: TransferTable): string;
13
13
  /** Same rule as `manifest.ts`'s `reseedSequenceSql`, schema-qualified: empty -> next is 1, else max + 1. */
14
14
  export declare function reseedIdentitySql(schema: string, table: TransferTable, sqlTag?: string): string;
15
+ /** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
16
+ * @complexity O(index columns plus predicate bytes); emits SQL without executing it.
17
+ */
15
18
  export declare function indexSql(schema: string, table: TransferTable): string;
16
19
  /**
17
20
  * Every CHECK and foreign key, added NOT VALID and then validated; a failed validation is recorded
@@ -63,9 +63,12 @@ export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
63
63
  })
64
64
  .join("");
65
65
  }
66
+ /** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
67
+ * @complexity O(index columns plus predicate bytes); emits SQL without executing it.
68
+ */
66
69
  export function indexSql(schema, table) {
67
70
  return table.indexes
68
- .map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${index.columns.map(quoteIdent).join(", ")});\n`)
71
+ .map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${(index.expressions ?? index.columns.map(quoteIdent)).join(", ")})${index.where === undefined ? "" : ` WHERE ${index.where}`};\n`)
69
72
  .join("");
70
73
  }
71
74
  const REFERENTIAL_ACTIONS = new Set(["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"]);
@@ -84,7 +87,8 @@ function parentColumns(fk, byName) {
84
87
  const columns = fk.foreignColumns ?? parent.primaryKey;
85
88
  if (columns.length !== fk.columns.length)
86
89
  return null;
87
- const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && sameColumns(index.columns, columns));
90
+ // Partial or expression uniqueness cannot establish an FK target over the named columns.
91
+ const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && index.where === undefined && index.expressions === undefined && sameColumns(index.columns, columns));
88
92
  return unique ? columns : null;
89
93
  }
90
94
  function constraintsOf(schema, table, byName) {
@@ -10,7 +10,12 @@ export interface TransferColumn {
10
10
  export interface TransferIndex {
11
11
  readonly name: string;
12
12
  readonly columns: readonly string[];
13
+ /** Complete ordered index terms as trusted host SQL, replacing columns for expression indexes.
14
+ * Never populate from operator input or introspected plugin SQL; these cannot be FK targets. */
15
+ readonly expressions?: readonly string[];
13
16
  readonly unique: boolean;
17
+ /** Trusted, host-declared Postgres predicate SQL; never operator input or SQLite plugin SQL. */
18
+ readonly where?: string;
14
19
  }
15
20
  export interface TransferForeignKey {
16
21
  readonly name: string;
@@ -35,13 +40,5 @@ export interface TransferTable {
35
40
  readonly foreignKeys: readonly TransferForeignKey[];
36
41
  readonly checks: readonly TransferCheck[];
37
42
  }
38
- /** Host identifiers are required: changing a marker name would orphan earlier copies. */
39
- export interface TransferNaming {
40
- readonly defaultSchema: string;
41
- readonly markerTable: string;
42
- readonly unvalidatedTable: string;
43
- readonly schemaPrefix: string;
44
- /** Optional SQL dollar-quote tag for compatibility with existing script consumers. */
45
- readonly sqlTag?: string;
46
- }
43
+ export type { TransferNaming } from '../core/transfer-naming.js';
47
44
  //# sourceMappingURL=types.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@jini-ai/db",
3
- "version": "0.3.0",
3
+ "version": "0.3.2",
4
4
  "description": "Database ports, connection helpers, ownership, isolated Kysely kernels and migrations. All peers are optional; drivers are injected.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -14,7 +14,25 @@
14
14
  "runtime": "node",
15
15
  "neutralEntries": [
16
16
  "src/core"
17
- ]
17
+ ],
18
+ "isolation": {
19
+ "entries": {
20
+ "./tools": "transfer"
21
+ },
22
+ "shared": [
23
+ "src/kernel/dialect.ts",
24
+ "src/kernel/index.ts",
25
+ "src/kernel/kernel-core.ts",
26
+ "src/kernel/ops.ts",
27
+ "src/kernel/port.ts",
28
+ "src/kernel/postgres-lock.ts",
29
+ "src/kernel/schema-scope.ts",
30
+ "src/kernel/schema-shape.ts",
31
+ "src/kernel/store-copy.ts",
32
+ "src/kernel/turn-lock.ts",
33
+ "src/kernel/typegen.ts"
34
+ ]
35
+ }
18
36
  },
19
37
  "type": "module",
20
38
  "sideEffects": false,
@@ -64,6 +82,11 @@
64
82
  "import": "./dist/migrate/index.js",
65
83
  "default": "./dist/migrate/index.js"
66
84
  },
85
+ "./testing/pg-fixture": {
86
+ "types": "./dist/pg-fixture.d.ts",
87
+ "import": "./dist/pg-fixture.js",
88
+ "default": "./dist/pg-fixture.js"
89
+ },
67
90
  "./package.json": "./package.json",
68
91
  "./transfer": {
69
92
  "types": "./dist/transfer/index.d.ts",
@@ -79,6 +102,21 @@
79
102
  "types": "./dist/kernel/store-copy.d.ts",
80
103
  "import": "./dist/kernel/store-copy.js",
81
104
  "default": "./dist/kernel/store-copy.js"
105
+ },
106
+ "./recovery/*": {
107
+ "types": "./dist/recovery/*.d.ts",
108
+ "import": "./dist/recovery/*.js",
109
+ "default": "./dist/recovery/*.js"
110
+ },
111
+ "./recovery": {
112
+ "types": "./dist/recovery/index.d.ts",
113
+ "import": "./dist/recovery/index.js",
114
+ "default": "./dist/recovery/index.js"
115
+ },
116
+ "./secrets-vault": {
117
+ "types": "./dist/secrets-vault/index.d.ts",
118
+ "import": "./dist/secrets-vault/index.js",
119
+ "default": "./dist/secrets-vault/index.js"
82
120
  }
83
121
  },
84
122
  "typesVersions": {
@@ -110,6 +148,9 @@
110
148
  "migrate": [
111
149
  "./dist/migrate/index.d.ts"
112
150
  ],
151
+ "testing/pg-fixture": [
152
+ "./dist/pg-fixture.d.ts"
153
+ ],
113
154
  "package.json": [
114
155
  "./package.json"
115
156
  ],
@@ -121,6 +162,15 @@
121
162
  ],
122
163
  "kernel/store-copy": [
123
164
  "./dist/kernel/store-copy.d.ts"
165
+ ],
166
+ "recovery/*": [
167
+ "./dist/recovery/*.d.ts"
168
+ ],
169
+ "recovery": [
170
+ "./dist/recovery/index.d.ts"
171
+ ],
172
+ "secrets-vault": [
173
+ "./dist/secrets-vault/index.d.ts"
124
174
  ]
125
175
  }
126
176
  },
@@ -141,6 +191,10 @@
141
191
  "access": "public",
142
192
  "registry": "https://registry.npmjs.org"
143
193
  },
194
+ "dependencies": {
195
+ "@jini-ai/core": "^0.4.3",
196
+ "@jini-ai/platform": "^0.5.3"
197
+ },
144
198
  "peerDependencies": {
145
199
  "kysely": "^0.29.6",
146
200
  "better-sqlite3": "^13.0.0",
@@ -169,10 +223,7 @@
169
223
  "better-sqlite3": "13.0.3",
170
224
  "kysely": "0.29.6",
171
225
  "pg": "8.23.0",
172
- "@jini-ai/core": "0.4.1"
173
- },
174
- "dependencies": {
175
- "@jini-ai/core": "^0.4.1"
226
+ "@jini-ai/core": "0.4.3"
176
227
  },
177
228
  "scripts": {
178
229
  "build": "tsc -p tsconfig.build.json",