zero-db-tool 0.0.0-stage → 1.0.0
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/LICENSE +28 -0
- package/README.md +86 -2
- package/assets/icon.png +0 -0
- package/client/client.js +543 -0
- package/client/src/AntdWorkbench.tsx +632 -0
- package/client/src/DatabaseConnectionsPage.tsx +455 -0
- package/client/src/api.ts +71 -0
- package/client/src/base.css +82 -0
- package/client/src/console-shim.ts +5 -0
- package/client/src/database-workbench.css +905 -0
- package/client/src/icons.tsx +33 -0
- package/client/src/main.tsx +83 -0
- package/client/src/text.d.ts +4 -0
- package/client/src/theme-fixes.css +29 -0
- package/client/src/theme.ts +25 -0
- package/client/src/workbench.css +156 -0
- package/cordis.patch.yml +4 -0
- package/dist/connections.js +909 -0
- package/dist/http.js +215 -0
- package/dist/index.js +77 -0
- package/dist/manager.js +193 -0
- package/dist/plugin-types.js +1 -0
- package/dist/sql-guard.js +239 -0
- package/dist/tools.js +229 -0
- package/package.json +63 -4
package/dist/http.js
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
import { DbConnectionError } from "./connections.js";
|
|
2
|
+
import { SqlGuardError } from "./sql-guard.js";
|
|
3
|
+
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
|
4
|
+
function isLoopbackHostname(hostname) {
|
|
5
|
+
const host = String(hostname ?? "").replace(/^\[|\]$/g, "").toLowerCase();
|
|
6
|
+
return host === "localhost" || host === "127.0.0.1" || host === "::1";
|
|
7
|
+
}
|
|
8
|
+
function originHostPort(origin) {
|
|
9
|
+
try {
|
|
10
|
+
const url = new URL(origin);
|
|
11
|
+
return { host: url.hostname.replace(/^\[|\]$/g, "").toLowerCase(), port: url.port || (url.protocol === "https:" ? "443" : "80") };
|
|
12
|
+
}
|
|
13
|
+
catch {
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
/** Host must be loopback or trusted; when Origin/Referer exists it must match. */
|
|
18
|
+
export function isTrustedRequest(req, trustedHosts) {
|
|
19
|
+
const hostHeader = req.headers.host;
|
|
20
|
+
if (!hostHeader)
|
|
21
|
+
return false;
|
|
22
|
+
let host;
|
|
23
|
+
try {
|
|
24
|
+
host = new URL(`http://${hostHeader}`);
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
return false;
|
|
28
|
+
}
|
|
29
|
+
const reqHost = host.hostname.replace(/^\[|\]$/g, "").toLowerCase();
|
|
30
|
+
const trusted = Array.isArray(trustedHosts) ? trustedHosts : [];
|
|
31
|
+
const hostOk = isLoopbackHostname(reqHost) || trusted.some((entry) => entry === hostHeader || entry === host.hostname || entry === host.host);
|
|
32
|
+
if (!hostOk)
|
|
33
|
+
return false;
|
|
34
|
+
const origin = String(req.headers.origin ?? req.headers.referer ?? "");
|
|
35
|
+
if (origin === "")
|
|
36
|
+
return true;
|
|
37
|
+
const parsed = originHostPort(origin);
|
|
38
|
+
if (!parsed)
|
|
39
|
+
return false;
|
|
40
|
+
if (isLoopbackHostname(parsed.host) && isLoopbackHostname(reqHost)) {
|
|
41
|
+
const reqPort = host.port || "80";
|
|
42
|
+
return parsed.port === "" || parsed.port === reqPort;
|
|
43
|
+
}
|
|
44
|
+
return trusted.some((entry) => entry === parsed.host || entry === origin || entry === `${parsed.host}:${parsed.port}`);
|
|
45
|
+
}
|
|
46
|
+
function send(res, status, payload) {
|
|
47
|
+
res.statusCode = status;
|
|
48
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
49
|
+
res.setHeader("Cache-Control", "no-store");
|
|
50
|
+
res.end(JSON.stringify(payload));
|
|
51
|
+
}
|
|
52
|
+
function statusFor(error) {
|
|
53
|
+
if (error instanceof SqlGuardError)
|
|
54
|
+
return 400;
|
|
55
|
+
if (error instanceof DbConnectionError) {
|
|
56
|
+
switch (error.code) {
|
|
57
|
+
case "DB_CONNECTION_NOT_FOUND": return 404;
|
|
58
|
+
case "DB_INVALID_CONFIG": return 400;
|
|
59
|
+
case "DB_READ_ONLY_VIOLATION": return 400;
|
|
60
|
+
case "DB_PERSISTENCE_ERROR": return 500;
|
|
61
|
+
default: return 502;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return 500;
|
|
65
|
+
}
|
|
66
|
+
function codeFor(error) {
|
|
67
|
+
if (error instanceof SqlGuardError)
|
|
68
|
+
return error.code;
|
|
69
|
+
if (error instanceof DbConnectionError)
|
|
70
|
+
return error.code;
|
|
71
|
+
const code = error && typeof error === "object" && "code" in error ? String(error.code) : "";
|
|
72
|
+
return code || "DB_ENGINE_ERROR";
|
|
73
|
+
}
|
|
74
|
+
async function readJson(req) {
|
|
75
|
+
const chunks = [];
|
|
76
|
+
let size = 0;
|
|
77
|
+
for await (const chunk of req) {
|
|
78
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
79
|
+
size += buffer.length;
|
|
80
|
+
if (size > MAX_BODY_BYTES)
|
|
81
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "request body too large");
|
|
82
|
+
chunks.push(buffer);
|
|
83
|
+
}
|
|
84
|
+
if (size === 0)
|
|
85
|
+
return {};
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
88
|
+
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "request body is not valid JSON");
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export async function handleRequest(req, res, service, options) {
|
|
95
|
+
if (!isTrustedRequest(req, options.trustedHosts)) {
|
|
96
|
+
send(res, 403, { ok: false, error: { code: "FORBIDDEN", message: "untrusted request origin" } });
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const rawUrl = req.url ?? "/";
|
|
100
|
+
const queryIndex = rawUrl.indexOf("?");
|
|
101
|
+
const rawPath = queryIndex === -1 ? rawUrl : rawUrl.slice(0, queryIndex);
|
|
102
|
+
const query = new URLSearchParams(queryIndex === -1 ? "" : rawUrl.slice(queryIndex + 1));
|
|
103
|
+
const apiIndex = rawPath.indexOf("/api/");
|
|
104
|
+
const path = (apiIndex >= 0 ? rawPath.slice(apiIndex) : rawPath).replace(/\/+$/, "") || "/";
|
|
105
|
+
const method = (req.method ?? "GET").toUpperCase();
|
|
106
|
+
try {
|
|
107
|
+
if (method === "GET" && path === "/api/version") {
|
|
108
|
+
send(res, 200, { ok: true, version: options.version });
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
if (method === "GET" && path === "/api/health") {
|
|
112
|
+
send(res, 200, { ok: true, connections: await service.health() });
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
if (method === "GET" && path === "/api/connections") {
|
|
116
|
+
send(res, 200, { ok: true, connections: service.list() });
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
if (method === "POST" && path === "/api/connections") {
|
|
120
|
+
const body = await readJson(req);
|
|
121
|
+
const summary = await service.add(connectionInput(body));
|
|
122
|
+
send(res, 200, { ok: true, connection: summary });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
if (method === "GET" && path === "/api/export") {
|
|
126
|
+
send(res, 200, { ok: true, document: service.exportConfig() });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
if (method === "POST" && path === "/api/import") {
|
|
130
|
+
const body = await readJson(req);
|
|
131
|
+
const conflict = body.conflict === "overwrite" ? "overwrite" : "skip";
|
|
132
|
+
const result = await service.importConfig(body.document, conflict);
|
|
133
|
+
send(res, 200, { ok: true, result });
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const itemMatch = /^\/api\/connections\/([^/]+)(?:\/(test|catalog|browse|query))?$/.exec(path);
|
|
137
|
+
if (itemMatch) {
|
|
138
|
+
const name = decodeURIComponent(itemMatch[1]);
|
|
139
|
+
const action = itemMatch[2];
|
|
140
|
+
if (method === "POST" && action === "test") {
|
|
141
|
+
send(res, 200, { ok: true, result: await service.test(name) });
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
if (method === "GET" && action === "catalog") {
|
|
145
|
+
const database = query.get("database") ?? undefined;
|
|
146
|
+
const [databases, tables] = await Promise.all([service.listDatabases(name), service.listTables(name, database)]);
|
|
147
|
+
send(res, 200, { ok: true, databases, tables });
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
if (method === "GET" && action === "browse") {
|
|
151
|
+
const database = query.get("database") ?? undefined;
|
|
152
|
+
const table = (query.get("table") ?? "").trim();
|
|
153
|
+
// 同一端点:不带 table(或只有空白)返回目录,带 table 返回分页数据。
|
|
154
|
+
if (table === "") {
|
|
155
|
+
const [databases, tables] = await Promise.all([service.listDatabases(name), service.listTables(name, database)]);
|
|
156
|
+
send(res, 200, { ok: true, databases, tables });
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
const page = Number(query.get("page") ?? "1");
|
|
160
|
+
const pageSize = Number(query.get("pageSize") ?? "50");
|
|
161
|
+
send(res, 200, { ok: true, result: await service.browse(name, table, page, pageSize, database) });
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if (method === "POST" && action === "query") {
|
|
165
|
+
const body = await readJson(req);
|
|
166
|
+
const sql = String(body.sql ?? "");
|
|
167
|
+
const maxRows = Number(body.maxRows ?? 500);
|
|
168
|
+
const database = typeof body.database === "string" && body.database !== "" ? body.database : undefined;
|
|
169
|
+
send(res, 200, { ok: true, result: await service.queryReadOnly(name, sql, maxRows, database) });
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
if (action === undefined && method === "PATCH") {
|
|
173
|
+
const body = await readJson(req);
|
|
174
|
+
// 页面允许改名:body.name 优先,缺省沿用 URL 里的当前名。
|
|
175
|
+
const summary = await service.update(name, connectionInput({ name, ...body }));
|
|
176
|
+
send(res, 200, { ok: true, connection: summary });
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (action === undefined && method === "DELETE") {
|
|
180
|
+
const removed = await service.remove(name);
|
|
181
|
+
if (!removed)
|
|
182
|
+
throw new DbConnectionError("DB_CONNECTION_NOT_FOUND", `no database connection named "${name}"`);
|
|
183
|
+
send(res, 200, { ok: true });
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
send(res, 404, { ok: false, error: { code: "NOT_FOUND", message: `unknown route ${method} ${path}` } });
|
|
188
|
+
}
|
|
189
|
+
catch (error) {
|
|
190
|
+
send(res, statusFor(error), { ok: false, error: { code: codeFor(error), message: error instanceof Error ? error.message : String(error) } });
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function connectionInput(body) {
|
|
194
|
+
const text = (key) => {
|
|
195
|
+
const value = body[key];
|
|
196
|
+
return typeof value === "string" && value.trim() !== "" ? value : undefined;
|
|
197
|
+
};
|
|
198
|
+
const mode = body.mode === "url-env" ? "url-env" : body.mode === "parameters" ? "parameters" : undefined;
|
|
199
|
+
const passwordMode = body.passwordMode === "runtime" || body.passwordMode === "environment" || body.passwordMode === "encrypted" ? body.passwordMode : undefined;
|
|
200
|
+
return {
|
|
201
|
+
name: String(body.name ?? ""),
|
|
202
|
+
engine: (body.engine === "postgres" || body.engine === "mysql" || body.engine === "sqlite" ? body.engine : "sqlite"),
|
|
203
|
+
...(text("path") ? { path: text("path") } : {}),
|
|
204
|
+
...(mode ? { mode } : {}),
|
|
205
|
+
...(text("urlEnv") ? { urlEnv: text("urlEnv") } : {}),
|
|
206
|
+
...(text("host") ? { host: text("host") } : {}),
|
|
207
|
+
...(typeof body.port === "number" ? { port: body.port } : {}),
|
|
208
|
+
...(text("database") ? { database: text("database") } : {}),
|
|
209
|
+
...(text("username") ? { username: text("username") } : {}),
|
|
210
|
+
...(passwordMode ? { passwordMode } : {}),
|
|
211
|
+
...(typeof body.password === "string" && body.password !== "" ? { password: body.password } : {}),
|
|
212
|
+
...(text("passwordEnv") ? { passwordEnv: text("passwordEnv") } : {}),
|
|
213
|
+
...(typeof body.ssl === "boolean" ? { ssl: body.ssl } : {}),
|
|
214
|
+
};
|
|
215
|
+
}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* zero-db-tool 插件入口:DSH 数据库工作台(连接下拉 + 对象树 + 数据/结构/SQL)。
|
|
3
|
+
*
|
|
4
|
+
* - 六个模型工具:sql_query / sql_exec / sql_schema / sql_stats / sql_health / sql_connections
|
|
5
|
+
* - HTTP API 挂在 webServer 的 /zero-db-tool/api 前缀,右侧栏工作台使用
|
|
6
|
+
* - 连接与凭据落在 <Documents>/DSH/zero-db-tool(ZERO_DB_TOOL_DIR 可覆盖)
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from "node:fs";
|
|
9
|
+
import os from "node:os";
|
|
10
|
+
import path from "node:path";
|
|
11
|
+
import { DbConnectionRegistry } from "./connections.js";
|
|
12
|
+
import { handleRequest } from "./http.js";
|
|
13
|
+
import { WorkbenchService } from "./manager.js";
|
|
14
|
+
import { registerTools } from "./tools.js";
|
|
15
|
+
export const inject = ["webServer", "tools", "sessions", "connection"];
|
|
16
|
+
const PLUGIN_ID = "zero-db-tool";
|
|
17
|
+
const API_PREFIX = "/zero-db-tool/api";
|
|
18
|
+
function resolveDataDir() {
|
|
19
|
+
const explicit = process.env.ZERO_DB_TOOL_DIR?.trim();
|
|
20
|
+
if (explicit)
|
|
21
|
+
return path.resolve(explicit);
|
|
22
|
+
const documents = process.env.USERPROFILE
|
|
23
|
+
? path.join(process.env.USERPROFILE, "Documents")
|
|
24
|
+
: path.join(os.homedir(), "Documents");
|
|
25
|
+
return path.join(documents, "DSH", "zero-db-tool");
|
|
26
|
+
}
|
|
27
|
+
function readVersion() {
|
|
28
|
+
try {
|
|
29
|
+
const document = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
|
|
30
|
+
return typeof document.version === "string" ? document.version : "0.0.0";
|
|
31
|
+
}
|
|
32
|
+
catch {
|
|
33
|
+
return "0.0.0";
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
export function apply(ctx) {
|
|
37
|
+
const log = ctx.logger ?? {};
|
|
38
|
+
const root = resolveDataDir();
|
|
39
|
+
const version = readVersion();
|
|
40
|
+
const registry = new DbConnectionRegistry(root);
|
|
41
|
+
const service = new WorkbenchService(registry);
|
|
42
|
+
const trustedHosts = () => {
|
|
43
|
+
try {
|
|
44
|
+
const startup = ctx.get?.("webStartup", true);
|
|
45
|
+
const runtime = ctx.get?.("webRuntime", true);
|
|
46
|
+
return Array.isArray(startup?.trustedHosts) ? startup.trustedHosts : Array.isArray(runtime?.trustedHosts) ? runtime.trustedHosts : [];
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
const unregister = ctx.webServer?.register({
|
|
53
|
+
kind: "prefix",
|
|
54
|
+
path: API_PREFIX,
|
|
55
|
+
handler: async (req, res) => {
|
|
56
|
+
const rejection = ctx.connection?.requestRejection?.(req);
|
|
57
|
+
if (rejection !== undefined) {
|
|
58
|
+
const response = res;
|
|
59
|
+
response.statusCode = rejection;
|
|
60
|
+
response.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
61
|
+
response.end(JSON.stringify({
|
|
62
|
+
ok: false,
|
|
63
|
+
error: {
|
|
64
|
+
code: rejection === 401 ? "UNAUTHORIZED" : "FORBIDDEN",
|
|
65
|
+
message: rejection === 401 ? "browser authentication required" : "untrusted request",
|
|
66
|
+
},
|
|
67
|
+
}));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
await handleRequest(req, res, service, { trustedHosts: trustedHosts(), version });
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
ctx.effect?.(() => unregister ?? (() => { }), "db-workbench-http");
|
|
74
|
+
ctx.effect?.(() => () => registry.dispose(), "db-workbench-dispose");
|
|
75
|
+
registerTools(ctx, service);
|
|
76
|
+
log.info?.(`[${PLUGIN_ID}] 已加载:6 个 sql_* 工具 + ${API_PREFIX}(数据目录 ${root})`);
|
|
77
|
+
}
|
package/dist/manager.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工作台业务层:把 DbConnectionRegistry 收窄成工具/HTTP 需要的能力。
|
|
3
|
+
* 写入语义:只读查询、INSERT 直通、UPDATE 需人类批准、其余写一律拒绝。
|
|
4
|
+
*/
|
|
5
|
+
import { stat } from "node:fs/promises";
|
|
6
|
+
import path from "node:path";
|
|
7
|
+
import { DbConnectionError, isSqliteHandle, } from "./connections.js";
|
|
8
|
+
import { SqlGuardError, assertReadOnlyStatement, assertSafeIdentifier, assertSingleStatement, assertWriteStatement, formatTable, isDbConnectionLoss, jsonSafeRows, splitStatements, toCsv, } from "./sql-guard.js";
|
|
9
|
+
export const SQL_QUERY_TIMEOUT_MS = 30_000;
|
|
10
|
+
export const SQL_EXEC_TIMEOUT_MS = 60_000;
|
|
11
|
+
export const SQL_MAX_ROWS_DEFAULT = 200;
|
|
12
|
+
export const SQL_MAX_ROWS_LIMIT = 1_000;
|
|
13
|
+
const STATS_TABLE_LIMIT = 100;
|
|
14
|
+
export class WorkbenchService {
|
|
15
|
+
registry;
|
|
16
|
+
constructor(registry) {
|
|
17
|
+
this.registry = registry;
|
|
18
|
+
}
|
|
19
|
+
list() {
|
|
20
|
+
return this.registry.list();
|
|
21
|
+
}
|
|
22
|
+
get(name) {
|
|
23
|
+
return this.registry.get(name);
|
|
24
|
+
}
|
|
25
|
+
add(input) {
|
|
26
|
+
return this.registry.add(input);
|
|
27
|
+
}
|
|
28
|
+
update(name, input) {
|
|
29
|
+
return this.registry.update(name, input);
|
|
30
|
+
}
|
|
31
|
+
remove(name) {
|
|
32
|
+
return this.registry.remove(name);
|
|
33
|
+
}
|
|
34
|
+
test(name) {
|
|
35
|
+
return this.registry.test(name);
|
|
36
|
+
}
|
|
37
|
+
exportConfig() {
|
|
38
|
+
return this.registry.exportConfig();
|
|
39
|
+
}
|
|
40
|
+
importConfig(document, conflict) {
|
|
41
|
+
return this.registry.importConfig(document, conflict);
|
|
42
|
+
}
|
|
43
|
+
listDatabases(name) {
|
|
44
|
+
return this.registry.listDatabases(name);
|
|
45
|
+
}
|
|
46
|
+
listTables(name, database) {
|
|
47
|
+
return this.registry.listTables(name, database);
|
|
48
|
+
}
|
|
49
|
+
browse(name, table, page, pageSize, database) {
|
|
50
|
+
if (table.trim() === "") {
|
|
51
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "未选择表:请先刷新表目录再选择表或视图");
|
|
52
|
+
}
|
|
53
|
+
return this.registry.browseTable(name, table, page, pageSize, database);
|
|
54
|
+
}
|
|
55
|
+
/** Read-only, row-capped query used by the workbench UI (supports a database override). */
|
|
56
|
+
queryPage(name, sql, maxRows = 500, database) {
|
|
57
|
+
return this.registry.queryPage(name, sql, maxRows, database);
|
|
58
|
+
}
|
|
59
|
+
/** Guarded single-statement read for the UI, with an optional database override. */
|
|
60
|
+
queryReadOnly(name, sql, maxRows = 500, database) {
|
|
61
|
+
const statements = splitStatements(sql ?? "");
|
|
62
|
+
assertSingleStatement(statements);
|
|
63
|
+
if (statements.length === 0)
|
|
64
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "sql is empty");
|
|
65
|
+
assertReadOnlyStatement(statements[0]);
|
|
66
|
+
return this.withTimeout(this.registry.queryPage(name, statements[0], maxRows, database), SQL_QUERY_TIMEOUT_MS);
|
|
67
|
+
}
|
|
68
|
+
async query(connection, sql, format = "json", limit = SQL_MAX_ROWS_DEFAULT) {
|
|
69
|
+
const statements = splitStatements(sql ?? "");
|
|
70
|
+
assertSingleStatement(statements);
|
|
71
|
+
if (statements.length === 0)
|
|
72
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "sql is empty");
|
|
73
|
+
assertReadOnlyStatement(statements[0]);
|
|
74
|
+
const safeLimit = Math.min(Math.max(Number.isInteger(limit) ? limit : SQL_MAX_ROWS_DEFAULT, 1), SQL_MAX_ROWS_LIMIT);
|
|
75
|
+
const { columns, all } = await this.withTimeout(this.withReconnect(connection, async () => {
|
|
76
|
+
const handle = await this.registry.connect(connection);
|
|
77
|
+
if (isSqliteHandle(handle)) {
|
|
78
|
+
const stmt = handle.prepare(statements[0].trim());
|
|
79
|
+
return { columns: stmt.columns().map((column) => column.name), all: stmt.all() };
|
|
80
|
+
}
|
|
81
|
+
const rows = await handle.query(statements[0].trim());
|
|
82
|
+
return { columns: rows.length > 0 ? Object.keys(rows[0]) : [], all: rows };
|
|
83
|
+
}), SQL_QUERY_TIMEOUT_MS, () => this.registry.evict(connection));
|
|
84
|
+
const truncated = all.length > safeLimit;
|
|
85
|
+
const rows = jsonSafeRows(truncated ? all.slice(0, safeLimit) : all);
|
|
86
|
+
const text = format === "table" ? formatTable(columns, rows) : format === "csv" ? toCsv(columns, rows) : undefined;
|
|
87
|
+
return { connection, columns, rows, rowCount: rows.length, truncated, ...(text !== undefined ? { text } : {}) };
|
|
88
|
+
}
|
|
89
|
+
/** Execute an INSERT/UPDATE batch. Callers own the UPDATE approval gate. */
|
|
90
|
+
async execute(connection, sql) {
|
|
91
|
+
const statements = splitStatements(sql ?? "");
|
|
92
|
+
if (statements.length === 0)
|
|
93
|
+
throw new SqlGuardError("DB_INVALID_CONFIG", "sql is empty");
|
|
94
|
+
const kinds = statements.map(assertWriteStatement);
|
|
95
|
+
return this.withTimeout((async () => {
|
|
96
|
+
const results = [];
|
|
97
|
+
for (let index = 0; index < statements.length; index += 1) {
|
|
98
|
+
const affectedRows = await this.withReconnect(connection, () => this.registry.executeWrite(connection, statements[index]));
|
|
99
|
+
results.push({ operation: kinds[index], affectedRows });
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
statementCount: results.length,
|
|
103
|
+
affectedRows: results.reduce((sum, item) => sum + item.affectedRows, 0),
|
|
104
|
+
results,
|
|
105
|
+
};
|
|
106
|
+
})(), SQL_EXEC_TIMEOUT_MS, () => this.registry.evict(connection));
|
|
107
|
+
}
|
|
108
|
+
/** Whether a batch needs human approval before it may run. */
|
|
109
|
+
needsApproval(sql) {
|
|
110
|
+
return splitStatements(sql ?? "").some((statement) => assertWriteStatement(statement) === "UPDATE");
|
|
111
|
+
}
|
|
112
|
+
async schema(connection, table) {
|
|
113
|
+
const tables = await this.withTimeout(this.registry.listTables(connection), SQL_QUERY_TIMEOUT_MS);
|
|
114
|
+
if (table === undefined || table.trim() === "")
|
|
115
|
+
return { connection, tables };
|
|
116
|
+
const safeTable = assertSafeIdentifier(table);
|
|
117
|
+
const page = await this.withTimeout(this.registry.browseTable(connection, safeTable, 1, 1), SQL_QUERY_TIMEOUT_MS);
|
|
118
|
+
return { connection, table: safeTable, columns: page.columns };
|
|
119
|
+
}
|
|
120
|
+
async stats(connection) {
|
|
121
|
+
const tables = await this.withTimeout(this.registry.listTables(connection), SQL_QUERY_TIMEOUT_MS);
|
|
122
|
+
const rowsByTable = {};
|
|
123
|
+
let truncated = false;
|
|
124
|
+
for (const [index, table] of tables.entries()) {
|
|
125
|
+
if (index >= STATS_TABLE_LIMIT) {
|
|
126
|
+
truncated = true;
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
const name = assertSafeIdentifier(table.name);
|
|
130
|
+
const rows = await this.withTimeout(this.registry.query(connection, `SELECT COUNT(*) AS n FROM ${name}`), SQL_QUERY_TIMEOUT_MS).catch(() => [{ n: -1 }]);
|
|
131
|
+
rowsByTable[name] = Number(rows[0]?.n ?? -1);
|
|
132
|
+
}
|
|
133
|
+
const config = this.registry.get(connection);
|
|
134
|
+
let sizeBytes;
|
|
135
|
+
if (config?.path) {
|
|
136
|
+
try {
|
|
137
|
+
sizeBytes = (await stat(path.resolve(config.path))).size;
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
sizeBytes = undefined;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return { connection, tableCount: tables.length, tables: rowsByTable, truncated, ...(sizeBytes !== undefined ? { sizeBytes } : {}) };
|
|
144
|
+
}
|
|
145
|
+
async health() {
|
|
146
|
+
const results = [];
|
|
147
|
+
for (const summary of this.registry.list()) {
|
|
148
|
+
try {
|
|
149
|
+
const probe = await this.registry.test(summary.name);
|
|
150
|
+
results.push({ name: summary.name, engine: summary.engine, ok: true, elapsedMs: probe.elapsedMs });
|
|
151
|
+
}
|
|
152
|
+
catch (error) {
|
|
153
|
+
results.push({
|
|
154
|
+
name: summary.name,
|
|
155
|
+
engine: summary.engine,
|
|
156
|
+
ok: false,
|
|
157
|
+
code: error instanceof DbConnectionError ? error.code : "DB_ENGINE_ERROR",
|
|
158
|
+
message: error instanceof Error ? error.message : String(error),
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return results;
|
|
163
|
+
}
|
|
164
|
+
async withReconnect(connection, operation) {
|
|
165
|
+
try {
|
|
166
|
+
return await operation();
|
|
167
|
+
}
|
|
168
|
+
catch (error) {
|
|
169
|
+
if (!isDbConnectionLoss(error))
|
|
170
|
+
throw error;
|
|
171
|
+
this.registry.evict(connection);
|
|
172
|
+
return operation();
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async withTimeout(promise, timeoutMs, onTimeout) {
|
|
176
|
+
let timer;
|
|
177
|
+
try {
|
|
178
|
+
return await Promise.race([
|
|
179
|
+
promise,
|
|
180
|
+
new Promise((_, reject) => {
|
|
181
|
+
timer = setTimeout(() => {
|
|
182
|
+
onTimeout?.();
|
|
183
|
+
reject(new SqlGuardError("DB_TIMEOUT", `database operation timed out after ${timeoutMs}ms`));
|
|
184
|
+
}, timeoutMs);
|
|
185
|
+
}),
|
|
186
|
+
]);
|
|
187
|
+
}
|
|
188
|
+
finally {
|
|
189
|
+
if (timer !== undefined)
|
|
190
|
+
clearTimeout(timer);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|