@jini-ai/db 0.3.1 → 0.3.3
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 +4 -0
- package/dist/secrets-vault/index.d.ts +2 -0
- package/dist/secrets-vault/index.js +2 -0
- package/dist/secrets-vault/repo.sql.d.ts +86 -0
- package/dist/secrets-vault/repo.sql.js +181 -0
- package/dist/sqlite/inspect.d.ts +5 -1
- package/dist/sqlite/inspect.js +47 -18
- package/dist/transfer/internal-ddl.d.ts +1 -1
- package/dist/transfer/internal-ddl.js +4 -4
- package/dist/transfer/types.d.ts +3 -0
- package/package.json +12 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
|
+
## 0.3.3 — 2026-10-12
|
|
2
|
+
|
|
3
|
+
- Vault `findDefault` restates the default group in the normalized expressions and binds `is_default` as a dialect literal, so a host's partial default index is matched (SQLite and Postgres). Raw-column filters stay; results are unchanged.
|
|
4
|
+
|
|
1
5
|
## 0.3.1 — 2026-10-08
|
|
2
6
|
|
|
3
7
|
- Tovu clean-up release: code Tovu moved into Jini, plus the Jini clean-up (see the commit log).
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { type VaultBatchOp, type VaultBatchResult, type VaultDefaultQuery, type VaultSingletonQuery, type VaultMeta, type VaultOptions, type VaultQuery, type VaultRecord, type VaultRepoPort } from "@jini-ai/platform/secrets/credential-sets";
|
|
2
|
+
import type { StorageKernel } from "../kernel/port.js";
|
|
3
|
+
/** Fixed columns consumed by the adapter; hosts own DDL, foreign keys and migration provenance.
|
|
4
|
+
* A partial unique default index and label index use the same scope as VaultRepoPort.
|
|
5
|
+
* Nullable principal/provider scope columns must be normalized in those index expressions, spelled
|
|
6
|
+
* as findDefault spells them, and the default index's predicate is `is_default = 1` on SQLite, `= true` on Postgres.
|
|
7
|
+
* Read indexes: (workspace_id,kind,owner_key,principal_id,provider,is_default), and the same
|
|
8
|
+
* group prefix plus (updated_at DESC,id DESC) with binary/C ID collation for promotion.
|
|
9
|
+
* Singleton reads use the lookup index's (workspace_id,kind) prefix, optionally owner/principal.
|
|
10
|
+
*/
|
|
11
|
+
export interface SecretsVaultTable {
|
|
12
|
+
workspace_id: string;
|
|
13
|
+
id: string;
|
|
14
|
+
kind: VaultRecord["kind"];
|
|
15
|
+
owner_key: string;
|
|
16
|
+
principal_id: string | null;
|
|
17
|
+
binding: string | null;
|
|
18
|
+
provider: string | null;
|
|
19
|
+
label: string;
|
|
20
|
+
is_default: boolean | number;
|
|
21
|
+
revision: number;
|
|
22
|
+
sealed_key_id: string | null;
|
|
23
|
+
sealed_ciphertext: string | null;
|
|
24
|
+
sealed_nonce: string | null;
|
|
25
|
+
sealed_alg: string | null;
|
|
26
|
+
last4: string | null;
|
|
27
|
+
token_length: number | null;
|
|
28
|
+
meta: string | VaultMeta;
|
|
29
|
+
created_at: string;
|
|
30
|
+
updated_at: string;
|
|
31
|
+
}
|
|
32
|
+
export interface SecretsVaultDatabase {
|
|
33
|
+
secrets_vault: SecretsVaultTable;
|
|
34
|
+
}
|
|
35
|
+
/** One Kysely adapter for SQLite and Postgres/PGlite. Workspace lock `secrets_vault:<workspaceId>`
|
|
36
|
+
* serializes every writer, including targeted patches and boot rotation. Nested transactions join
|
|
37
|
+
* the host's transaction, allowing MCP payload/pointer/status writes to commit together.
|
|
38
|
+
*/
|
|
39
|
+
export declare class SqlSecretsVaultRepo implements VaultRepoPort {
|
|
40
|
+
private readonly kernel;
|
|
41
|
+
constructor({ kernel }: {
|
|
42
|
+
kernel: StorageKernel<SecretsVaultDatabase>;
|
|
43
|
+
}, _options?: VaultOptions);
|
|
44
|
+
private write;
|
|
45
|
+
private group;
|
|
46
|
+
private scoped;
|
|
47
|
+
find(input: {
|
|
48
|
+
workspaceId: string;
|
|
49
|
+
id: string;
|
|
50
|
+
}, _options?: VaultOptions): Promise<VaultRecord | null>;
|
|
51
|
+
/** One indexed singleton SELECT; provider/default never participate in this lookup. */
|
|
52
|
+
findOne(input: VaultSingletonQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
|
|
53
|
+
/** One kernel transaction; nested mutations join it and retain their CAS/default owner.
|
|
54
|
+
* Lock every workspace in sorted order before writes to avoid opposite-order batch deadlocks.
|
|
55
|
+
* Failures must escape a surrounding host transaction (the kernel does not use savepoints).
|
|
56
|
+
*/
|
|
57
|
+
applyBatch({ ops }: {
|
|
58
|
+
ops: readonly VaultBatchOp[];
|
|
59
|
+
}, _options?: VaultOptions): Promise<VaultBatchResult[]>;
|
|
60
|
+
/** One indexed exact-group lookup; ciphertext is loaded only for the chosen default.
|
|
61
|
+
* The group is restated in the default index's normalized expressions and `is_default` is a
|
|
62
|
+
* literal, else neither SQLite nor a generic Postgres plan can match the partial index (Tovu
|
|
63
|
+
* EXPLAIN 2026-10-12: SQLite fell back to a raw-column index, Postgres to the label index). */
|
|
64
|
+
findDefault(input: VaultDefaultQuery, _options?: VaultOptions): Promise<VaultRecord | null>;
|
|
65
|
+
list(input: VaultQuery, _options?: VaultOptions): Promise<VaultRecord[]>;
|
|
66
|
+
put(input: {
|
|
67
|
+
record: VaultRecord;
|
|
68
|
+
expectedRevision: number | null;
|
|
69
|
+
}, _options?: VaultOptions): Promise<VaultRecord>;
|
|
70
|
+
/** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
|
|
71
|
+
patchMeta(input: {
|
|
72
|
+
workspaceId: string;
|
|
73
|
+
id: string;
|
|
74
|
+
expectedRevision: number;
|
|
75
|
+
patch: VaultMeta;
|
|
76
|
+
updatedAt: string;
|
|
77
|
+
}, _options?: VaultOptions): Promise<VaultRecord>;
|
|
78
|
+
delete(input: {
|
|
79
|
+
workspaceId: string;
|
|
80
|
+
id: string;
|
|
81
|
+
expectedRevision: number;
|
|
82
|
+
}, _options?: VaultOptions): Promise<boolean>;
|
|
83
|
+
/** Pick only one identity using the same binary ordering for deletion and provider moves. */
|
|
84
|
+
private promote;
|
|
85
|
+
}
|
|
86
|
+
//# sourceMappingURL=repo.sql.d.ts.map
|
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { sql } from "kysely";
|
|
2
|
+
import { assertVaultReplacement, VaultError } from "@jini-ai/platform/secrets/credential-sets";
|
|
3
|
+
import { jsonSet, toBool } from "../kernel/dialect.js";
|
|
4
|
+
function fromRow(row) {
|
|
5
|
+
const parts = [row.sealed_key_id, row.sealed_ciphertext, row.sealed_nonce, row.sealed_alg];
|
|
6
|
+
if (parts.some(v => v === null) && !parts.every(v => v === null))
|
|
7
|
+
throw new VaultError({ code: "invalid-record" });
|
|
8
|
+
let meta;
|
|
9
|
+
try {
|
|
10
|
+
meta = typeof row.meta === "string" ? JSON.parse(row.meta) : row.meta;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
throw new VaultError({ code: "invalid-meta" });
|
|
14
|
+
}
|
|
15
|
+
return { workspaceId: row.workspace_id, id: row.id, kind: row.kind, ownerKey: row.owner_key,
|
|
16
|
+
principalId: row.principal_id, binding: row.binding, provider: row.provider, label: row.label,
|
|
17
|
+
isDefault: toBool(row.is_default) ?? false, revision: Number(row.revision),
|
|
18
|
+
sealed: row.sealed_key_id === null ? null : { keyId: row.sealed_key_id, ciphertext: row.sealed_ciphertext, nonce: row.sealed_nonce, alg: row.sealed_alg },
|
|
19
|
+
last4: row.last4, tokenLength: row.token_length,
|
|
20
|
+
meta,
|
|
21
|
+
createdAt: row.created_at, updatedAt: row.updated_at };
|
|
22
|
+
}
|
|
23
|
+
function toRow(record) {
|
|
24
|
+
return { workspace_id: record.workspaceId, id: record.id, kind: record.kind, owner_key: record.ownerKey,
|
|
25
|
+
principal_id: record.principalId, binding: record.binding, provider: record.provider, label: record.label,
|
|
26
|
+
is_default: record.isDefault, revision: record.revision, sealed_key_id: record.sealed?.keyId ?? null,
|
|
27
|
+
sealed_ciphertext: record.sealed?.ciphertext ?? null, sealed_nonce: record.sealed?.nonce ?? null, sealed_alg: record.sealed?.alg ?? null,
|
|
28
|
+
last4: record.last4, token_length: record.tokenLength, meta: JSON.stringify(record.meta),
|
|
29
|
+
created_at: record.createdAt, updated_at: record.updatedAt };
|
|
30
|
+
}
|
|
31
|
+
/** One Kysely adapter for SQLite and Postgres/PGlite. Workspace lock `secrets_vault:<workspaceId>`
|
|
32
|
+
* serializes every writer, including targeted patches and boot rotation. Nested transactions join
|
|
33
|
+
* the host's transaction, allowing MCP payload/pointer/status writes to commit together.
|
|
34
|
+
*/
|
|
35
|
+
export class SqlSecretsVaultRepo {
|
|
36
|
+
kernel;
|
|
37
|
+
constructor({ kernel }, _options = {}) { this.kernel = kernel; }
|
|
38
|
+
write(workspaceId, body) {
|
|
39
|
+
return this.kernel.transaction(async () => {
|
|
40
|
+
await this.kernel.lockKey(`secrets_vault:${workspaceId}`);
|
|
41
|
+
return body();
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
group(record) {
|
|
45
|
+
return { workspaceId: record.workspaceId, kind: record.kind, ownerKey: record.ownerKey,
|
|
46
|
+
principalId: record.principalId, provider: record.provider };
|
|
47
|
+
}
|
|
48
|
+
scoped({ db, input }, _options = {}) {
|
|
49
|
+
let query = db.selectFrom("secrets_vault").where("workspace_id", "=", input.workspaceId)
|
|
50
|
+
.where("kind", "=", input.kind).where("owner_key", "=", input.ownerKey)
|
|
51
|
+
.where("principal_id", input.principalId === null ? "is" : "=", input.principalId);
|
|
52
|
+
if (input.provider !== undefined)
|
|
53
|
+
query = query.where("provider", input.provider === null ? "is" : "=", input.provider);
|
|
54
|
+
return query;
|
|
55
|
+
}
|
|
56
|
+
async find(input, _options = {}) {
|
|
57
|
+
const row = await this.kernel.run(db => db.selectFrom("secrets_vault").selectAll()
|
|
58
|
+
.where("workspace_id", "=", input.workspaceId).where("id", "=", input.id).executeTakeFirst());
|
|
59
|
+
return row ? fromRow(row) : null;
|
|
60
|
+
}
|
|
61
|
+
/** One indexed singleton SELECT; provider/default never participate in this lookup. */
|
|
62
|
+
async findOne(input, _options = {}) {
|
|
63
|
+
const row = await this.kernel.run(db => {
|
|
64
|
+
let query = db.selectFrom("secrets_vault").selectAll().where("workspace_id", "=", input.workspaceId).where("kind", "=", input.kind);
|
|
65
|
+
if (input.ownerKey !== undefined)
|
|
66
|
+
query = query.where("owner_key", "=", input.ownerKey);
|
|
67
|
+
if (input.principalId !== undefined)
|
|
68
|
+
query = query.where("principal_id", input.principalId === null ? "is" : "=", input.principalId);
|
|
69
|
+
return query.limit(1).executeTakeFirst();
|
|
70
|
+
});
|
|
71
|
+
return row ? fromRow(row) : null;
|
|
72
|
+
}
|
|
73
|
+
/** One kernel transaction; nested mutations join it and retain their CAS/default owner.
|
|
74
|
+
* Lock every workspace in sorted order before writes to avoid opposite-order batch deadlocks.
|
|
75
|
+
* Failures must escape a surrounding host transaction (the kernel does not use savepoints).
|
|
76
|
+
*/
|
|
77
|
+
async applyBatch({ ops }, _options = {}) {
|
|
78
|
+
return this.kernel.transaction(async () => {
|
|
79
|
+
const workspaces = ops.map(op => "put" in op ? op.put.record.workspaceId : "delete" in op ? op.delete.workspaceId : op.patchMeta.workspaceId);
|
|
80
|
+
for (const workspaceId of [...new Set(workspaces)].sort())
|
|
81
|
+
await this.kernel.lockKey(`secrets_vault:${workspaceId}`);
|
|
82
|
+
const results = [];
|
|
83
|
+
for (const op of ops) {
|
|
84
|
+
results.push("put" in op ? await this.put(op.put) : "delete" in op ? await this.delete(op.delete) : await this.patchMeta(op.patchMeta));
|
|
85
|
+
}
|
|
86
|
+
return results;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
/** One indexed exact-group lookup; ciphertext is loaded only for the chosen default.
|
|
90
|
+
* The group is restated in the default index's normalized expressions and `is_default` is a
|
|
91
|
+
* literal, else neither SQLite nor a generic Postgres plan can match the partial index (Tovu
|
|
92
|
+
* EXPLAIN 2026-10-12: SQLite fell back to a raw-column index, Postgres to the label index). */
|
|
93
|
+
async findDefault(input, _options = {}) {
|
|
94
|
+
const row = await this.kernel.run(db => this.scoped({ db, input }).selectAll()
|
|
95
|
+
.where(sql `(principal_id IS NULL)`, "=", input.principalId === null).where(sql `coalesce(principal_id,'')`, "=", input.principalId ?? "")
|
|
96
|
+
.where(sql `(provider IS NULL)`, "=", input.provider === null).where(sql `coalesce(provider,'')`, "=", input.provider ?? "")
|
|
97
|
+
.where(sql `is_default = ${sql.raw(this.kernel.dialect === "sqlite" ? "1" : "true")}`).limit(1).executeTakeFirst());
|
|
98
|
+
return row ? fromRow(row) : null;
|
|
99
|
+
}
|
|
100
|
+
async list(input, _options = {}) {
|
|
101
|
+
const rows = await this.kernel.run(db => this.scoped({ db, input }).selectAll().execute());
|
|
102
|
+
// Sort identifiers in JS to avoid host database collation changing the memory contract.
|
|
103
|
+
return rows.map(fromRow).sort((a, b) => a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
|
|
104
|
+
}
|
|
105
|
+
async put(input, _options = {}) {
|
|
106
|
+
return this.write(input.record.workspaceId, async () => {
|
|
107
|
+
const existing = await this.find(input.record);
|
|
108
|
+
assertVaultReplacement({ ...input, existing });
|
|
109
|
+
const scope = this.group(input.record);
|
|
110
|
+
// Unchanged-label rotations need no uniqueness read; DB constraints still guard writes.
|
|
111
|
+
const moved = existing !== null && existing.provider !== input.record.provider;
|
|
112
|
+
if (moved || existing?.label !== input.record.label) {
|
|
113
|
+
const duplicate = await this.kernel.run(db => this.scoped({ db, input: scope }).select("id")
|
|
114
|
+
.where("id", "!=", input.record.id).where("label", "=", input.record.label).limit(1).executeTakeFirst());
|
|
115
|
+
if (duplicate)
|
|
116
|
+
throw new VaultError({ code: "conflict" });
|
|
117
|
+
}
|
|
118
|
+
const hasGroup = (existing !== null && !moved) || input.record.isDefault || Boolean(await this.kernel.run(db => this.scoped({ db, input: scope }).select("id").limit(1).executeTakeFirst()));
|
|
119
|
+
const saved = { ...input.record, isDefault: input.record.isDefault || !hasGroup };
|
|
120
|
+
// Clear before insert/update so a partial UNIQUE default index never sees two defaults.
|
|
121
|
+
if (saved.isDefault)
|
|
122
|
+
await this.kernel.run(db => db.updateTable("secrets_vault")
|
|
123
|
+
.set(eb => ({ is_default: false, revision: eb("revision", "+", 1) }))
|
|
124
|
+
.where("workspace_id", "=", saved.workspaceId).where("kind", "=", saved.kind).where("owner_key", "=", saved.ownerKey)
|
|
125
|
+
.where("principal_id", saved.principalId === null ? "is" : "=", saved.principalId)
|
|
126
|
+
.where("provider", saved.provider === null ? "is" : "=", saved.provider)
|
|
127
|
+
.where("id", "!=", saved.id).where("is_default", "=", true).execute());
|
|
128
|
+
const row = await this.kernel.run(db => input.expectedRevision === null
|
|
129
|
+
? db.insertInto("secrets_vault").values(toRow(saved)).returningAll().executeTakeFirstOrThrow()
|
|
130
|
+
: db.updateTable("secrets_vault").set(toRow(saved)).where("workspace_id", "=", saved.workspaceId)
|
|
131
|
+
.where("id", "=", saved.id).where("revision", "=", input.expectedRevision).returningAll().executeTakeFirst());
|
|
132
|
+
if (!row)
|
|
133
|
+
throw new VaultError({ code: "conflict" });
|
|
134
|
+
if (moved && existing.isDefault)
|
|
135
|
+
await this.promote({ record: existing });
|
|
136
|
+
return fromRow(row);
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
/** Top-level targeted JSON writes preserve ciphertext/default fields; caller validates merged meta. */
|
|
140
|
+
async patchMeta(input, _options = {}) {
|
|
141
|
+
return this.write(input.workspaceId, async () => {
|
|
142
|
+
const row = await this.kernel.run(db => db.updateTable("secrets_vault").set(eb => {
|
|
143
|
+
let meta = eb.ref("meta");
|
|
144
|
+
for (const [key, value] of Object.entries(input.patch))
|
|
145
|
+
meta = jsonSet(this.kernel.dialect, meta, [key], value);
|
|
146
|
+
return { meta: meta, revision: eb("revision", "+", 1), updated_at: input.updatedAt };
|
|
147
|
+
}).where("workspace_id", "=", input.workspaceId).where("id", "=", input.id)
|
|
148
|
+
.where("revision", "=", input.expectedRevision).returningAll().executeTakeFirst());
|
|
149
|
+
if (!row)
|
|
150
|
+
throw new VaultError({ code: "conflict" });
|
|
151
|
+
return fromRow(row);
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
async delete(input, _options = {}) {
|
|
155
|
+
return this.write(input.workspaceId, async () => {
|
|
156
|
+
const existing = await this.find(input);
|
|
157
|
+
if (!existing)
|
|
158
|
+
return false;
|
|
159
|
+
if (existing.revision !== input.expectedRevision)
|
|
160
|
+
throw new VaultError({ code: "conflict" });
|
|
161
|
+
await this.kernel.run(db => db.deleteFrom("secrets_vault").where("workspace_id", "=", input.workspaceId)
|
|
162
|
+
.where("id", "=", input.id).where("revision", "=", input.expectedRevision).execute());
|
|
163
|
+
if (existing.isDefault)
|
|
164
|
+
await this.promote({ record: existing });
|
|
165
|
+
return true;
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
/** Pick only one identity using the same binary ordering for deletion and provider moves. */
|
|
169
|
+
async promote({ record }, _options = {}) {
|
|
170
|
+
// Let the database pick one identity; binary collation avoids locale-dependent winners.
|
|
171
|
+
const promoted = await this.kernel.run(db => this.scoped({ db, input: this.group(record) })
|
|
172
|
+
.select(["id", "updated_at"]).orderBy("updated_at", "desc")
|
|
173
|
+
.orderBy(this.kernel.dialect === "sqlite" ? sql `id COLLATE BINARY` : sql `id COLLATE "C"`, "desc")
|
|
174
|
+
.limit(1).executeTakeFirst());
|
|
175
|
+
if (promoted)
|
|
176
|
+
await this.kernel.run(db => db.updateTable("secrets_vault")
|
|
177
|
+
.set(eb => ({ is_default: true, revision: eb("revision", "+", 1) }))
|
|
178
|
+
.where("workspace_id", "=", record.workspaceId).where("id", "=", promoted.id).execute());
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
//# sourceMappingURL=repo.sql.js.map
|
package/dist/sqlite/inspect.d.ts
CHANGED
|
@@ -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
|
|
61
|
+
export declare function verifySqliteIntegrity(opts: VerifyDbOptions, { includeRowCounts }?: {
|
|
62
|
+
includeRowCounts?: boolean;
|
|
63
|
+
}): DbIntegrityReport;
|
|
60
64
|
//# sourceMappingURL=inspect.d.ts.map
|
package/dist/sqlite/inspect.js
CHANGED
|
@@ -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(
|
|
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
|
|
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
|
-
|
|
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,
|
|
@@ -12,7 +12,7 @@ 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 predicates and
|
|
15
|
+
/** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
|
|
16
16
|
* @complexity O(index columns plus predicate bytes); emits SQL without executing it.
|
|
17
17
|
*/
|
|
18
18
|
export declare function indexSql(schema: string, table: TransferTable): string;
|
|
@@ -63,12 +63,12 @@ export function reseedIdentitySql(schema, table, sqlTag = "transfer") {
|
|
|
63
63
|
})
|
|
64
64
|
.join("");
|
|
65
65
|
}
|
|
66
|
-
/** Writes declared indexes, retaining trusted host predicates and
|
|
66
|
+
/** Writes declared indexes, retaining trusted host expression terms, predicates and uniqueness.
|
|
67
67
|
* @complexity O(index columns plus predicate bytes); emits SQL without executing it.
|
|
68
68
|
*/
|
|
69
69
|
export function indexSql(schema, table) {
|
|
70
70
|
return table.indexes
|
|
71
|
-
.map((index) => `CREATE ${index.unique ? "UNIQUE " : ""}INDEX ${quoteIdent(fitIdentifier(index.name))} ON ${qualified(schema, table.name)} (${index.columns.map(quoteIdent).join(", ")})${index.where === undefined ? "" : ` WHERE ${index.where}`};\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`)
|
|
72
72
|
.join("");
|
|
73
73
|
}
|
|
74
74
|
const REFERENTIAL_ACTIONS = new Set(["NO ACTION", "RESTRICT", "CASCADE", "SET NULL", "SET DEFAULT"]);
|
|
@@ -87,8 +87,8 @@ function parentColumns(fk, byName) {
|
|
|
87
87
|
const columns = fk.foreignColumns ?? parent.primaryKey;
|
|
88
88
|
if (columns.length !== fk.columns.length)
|
|
89
89
|
return null;
|
|
90
|
-
//
|
|
91
|
-
const unique = sameColumns(columns, parent.primaryKey) || parent.indexes.some((index) => index.unique && index.where === undefined && 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));
|
|
92
92
|
return unique ? columns : null;
|
|
93
93
|
}
|
|
94
94
|
function constraintsOf(schema, table, byName) {
|
package/dist/transfer/types.d.ts
CHANGED
|
@@ -10,6 +10,9 @@ 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;
|
|
14
17
|
/** Trusted, host-declared Postgres predicate SQL; never operator input or SQLite plugin SQL. */
|
|
15
18
|
readonly where?: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@jini-ai/db",
|
|
3
|
-
"version": "0.3.
|
|
3
|
+
"version": "0.3.3",
|
|
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": {
|
|
@@ -112,6 +112,11 @@
|
|
|
112
112
|
"types": "./dist/recovery/index.d.ts",
|
|
113
113
|
"import": "./dist/recovery/index.js",
|
|
114
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"
|
|
115
120
|
}
|
|
116
121
|
},
|
|
117
122
|
"typesVersions": {
|
|
@@ -163,6 +168,9 @@
|
|
|
163
168
|
],
|
|
164
169
|
"recovery": [
|
|
165
170
|
"./dist/recovery/index.d.ts"
|
|
171
|
+
],
|
|
172
|
+
"secrets-vault": [
|
|
173
|
+
"./dist/secrets-vault/index.d.ts"
|
|
166
174
|
]
|
|
167
175
|
}
|
|
168
176
|
},
|
|
@@ -184,7 +192,8 @@
|
|
|
184
192
|
"registry": "https://registry.npmjs.org"
|
|
185
193
|
},
|
|
186
194
|
"dependencies": {
|
|
187
|
-
"@jini-ai/core": "^0.4.
|
|
195
|
+
"@jini-ai/core": "^0.4.3",
|
|
196
|
+
"@jini-ai/platform": "^0.5.4"
|
|
188
197
|
},
|
|
189
198
|
"peerDependencies": {
|
|
190
199
|
"kysely": "^0.29.6",
|
|
@@ -214,7 +223,7 @@
|
|
|
214
223
|
"better-sqlite3": "13.0.3",
|
|
215
224
|
"kysely": "0.29.6",
|
|
216
225
|
"pg": "8.23.0",
|
|
217
|
-
"@jini-ai/core": "0.4.
|
|
226
|
+
"@jini-ai/core": "0.4.3"
|
|
218
227
|
},
|
|
219
228
|
"scripts": {
|
|
220
229
|
"build": "tsc -p tsconfig.build.json",
|