zero-db-tool 1.0.1 → 1.1.1

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.
@@ -9,11 +9,11 @@ import {
9
9
  import type { ColumnsType } from "antd/es/table";
10
10
  import type { DataNode } from "antd/es/tree";
11
11
  import {
12
- ApartmentOutlined, ClearOutlined, CodeOutlined, CopyOutlined, DatabaseOutlined, DeleteOutlined, DownloadOutlined,
12
+ ApartmentOutlined, ClearOutlined, CodeOutlined, CopyOutlined, DatabaseOutlined, DeleteOutlined, DownOutlined, DownloadOutlined,
13
13
  EditOutlined, EyeOutlined, MoreOutlined, PlayCircleOutlined, PlusOutlined, ProfileOutlined,
14
14
  ReloadOutlined, SearchOutlined, TableOutlined, ThunderboltOutlined,
15
15
  } from "@ant-design/icons";
16
- import { api, type ColumnSummary, type Connection, type DbEngine, type TablePage, type TableSummary } from "./api";
16
+ import { api, type ColumnSummary, type Connection, type DbEngine, type IndexSummary, type TablePage, type TableSummary } from "./api";
17
17
 
18
18
  const { Text } = Typography;
19
19
  const HISTORY_KEY = "zero-db-tool.sql-history";
@@ -59,7 +59,7 @@ function download(name: string, text: string, type?: string): void {
59
59
  }
60
60
 
61
61
  export function AntdWorkbench(): React.JSX.Element {
62
- const { message } = App.useApp();
62
+ const { message, modal } = App.useApp();
63
63
  const { token } = theme.useToken();
64
64
  const [connections, setConnections] = useState<Connection[]>([]);
65
65
  const [activeName, setActiveName] = useState("");
@@ -73,6 +73,8 @@ export function AntdWorkbench(): React.JSX.Element {
73
73
  const [mode, setMode] = useState<"data" | "schema" | "sql">("data");
74
74
  const [sql, setSql] = useState("");
75
75
  const [result, setResult] = useState<TableResult | null>(null);
76
+ const [indexes, setIndexes] = useState<IndexSummary[]>([]);
77
+
76
78
  const [loading, setLoading] = useState("");
77
79
  const [search, setSearch] = useState("");
78
80
  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
@@ -92,6 +94,18 @@ export function AntdWorkbench(): React.JSX.Element {
92
94
 
93
95
  const active = useMemo(() => connections.find((item) => item.name === activeName), [connections, activeName]);
94
96
 
97
+ const pickDatabase = useCallback(async (value: string) => {
98
+ if (!active) return;
99
+ setDatabase(value); setTable(""); setPage(null); setIndexes([]);
100
+ setLoading("catalog");
101
+ try {
102
+ const payload = await api.catalog(active.name, value || undefined);
103
+ setTablesByDb((current) => ({ ...current, [value]: payload.tables ?? [] }));
104
+ } catch (cause) {
105
+ message.error(cause instanceof Error ? cause.message : String(cause));
106
+ } finally { setLoading(""); }
107
+ }, [active, message]);
108
+
95
109
  useEffect(() => {
96
110
  try { setHistory(JSON.parse(localStorage.getItem(HISTORY_KEY) ?? "[]") as string[]); } catch { setHistory([]); }
97
111
  void api.version().then((payload) => setVersion(payload.version)).catch(() => setVersion(""));
@@ -137,6 +151,9 @@ export function AntdWorkbench(): React.JSX.Element {
137
151
  setPage(payload.result);
138
152
  setTable(tableName);
139
153
  setDatabase(db);
154
+ void api.indexes(name, tableName, db || undefined)
155
+ .then((indexPayload) => setIndexes(indexPayload.indexes ?? []))
156
+ .catch(() => setIndexes([]));
140
157
  } catch (cause) {
141
158
  message.error(cause instanceof Error ? cause.message : String(cause));
142
159
  } finally { setLoading(""); }
@@ -146,7 +163,7 @@ export function AntdWorkbench(): React.JSX.Element {
146
163
  const connection = connections.find((item) => item.name === name);
147
164
  if (!connection) return;
148
165
  setActiveName(name);
149
- setPage(null); setResult(null); setTablesByDb({}); setDatabase(""); setTable(""); setSearch("");
166
+ setPage(null); setResult(null); setTablesByDb({}); setDatabase(""); setTable(""); setSearch(""); setIndexes([]);
150
167
  setLoading("catalog");
151
168
  try {
152
169
  const payload = await api.catalog(name, connection.database ?? undefined);
@@ -256,13 +273,43 @@ export function AntdWorkbench(): React.JSX.Element {
256
273
  }
257
274
  }
258
275
 
276
+ const readOnlySql = /^\s*(select|pragma|explain|show|describe|desc|with)\b/i.test(sql);
277
+
259
278
  async function runSql() {
260
279
  if (!active || sql.trim() === "") return;
261
280
  setLoading("sql");
262
281
  setResult(null);
263
282
  try {
264
- const payload = await api.query(active.name, sql, database || undefined);
265
- setResult(payload.result);
283
+ if (readOnlySql) {
284
+ const payload = await api.query(active.name, sql, database || undefined);
285
+ setResult(payload.result);
286
+ pushHistory(sql);
287
+ return;
288
+ }
289
+ const first = await api.execute(active.name, sql, { database: database || undefined });
290
+ if (first.needsConfirmation && first.challengeId) {
291
+ const confirmed = await new Promise<boolean>((resolve) => {
292
+ modal.confirm({
293
+ title: "确认执行 UPDATE?",
294
+ width: 560,
295
+ content: (
296
+ <div>
297
+ <Text type="secondary">这条语句会修改数据,确认后才执行:</Text>
298
+ <pre className="dbw-confirm-sql">{sql.trim()}</pre>
299
+ </div>
300
+ ),
301
+ okText: "执行",
302
+ cancelText: "取消",
303
+ onOk: () => resolve(true),
304
+ onCancel: () => resolve(false),
305
+ });
306
+ });
307
+ if (!confirmed) return;
308
+ const second = await api.execute(active.name, sql, { database: database || undefined, confirmationId: first.challengeId });
309
+ if (second.result) message.success("执行成功:影响 " + second.result.affectedRows + " 行");
310
+ } else if (first.result) {
311
+ message.success("执行成功:影响 " + first.result.affectedRows + " 行");
312
+ }
266
313
  pushHistory(sql);
267
314
  } catch (cause) {
268
315
  message.error(cause instanceof Error ? cause.message : String(cause));
@@ -331,6 +378,15 @@ export function AntdWorkbench(): React.JSX.Element {
331
378
  return keys.map((key) => ({ title: key, dataIndex: key, key, ellipsis: true, render: (value: unknown) => <span onDoubleClick={() => copyValue(value)}>{cell(value)}</span> }));
332
379
  }, [result]);
333
380
 
381
+ const indexOrigin = (value?: string): string => ({ c: "索引", u: "唯一约束", pk: "主键" }[value ?? ""] ?? value ?? "—");
382
+
383
+ const indexColumns: ColumnsType<IndexSummary> = [
384
+ { title: "名称", dataIndex: "name", key: "name", width: 168, ellipsis: true },
385
+ { title: "列", dataIndex: "columns", key: "columns", render: (value: string[]) => <span className="dbw-nowrap">{(value ?? []).join(", ") || "—"}</span> },
386
+ { title: "唯一", dataIndex: "unique", key: "unique", width: 64, render: (value: boolean) => (value ? <Tag color="blue">唯一</Tag> : "—") },
387
+ { title: "类型", dataIndex: "type", key: "type", width: 92, render: (value?: string) => indexOrigin(value) },
388
+ ];
389
+
334
390
  const schemaColumns: ColumnsType<ColumnSummary> = [
335
391
  { title: "字段", dataIndex: "name", key: "name", width: 130 },
336
392
  { title: "类型", dataIndex: "type", key: "type", render: (value: string) => value || "未知类型" },
@@ -347,6 +403,23 @@ export function AntdWorkbench(): React.JSX.Element {
347
403
  label: <Space size={4}><TableOutlined />数据</Space>,
348
404
  children: (
349
405
  <Flex vertical gap={8} style={{ height: "100%" }}>
406
+ <div className="dbw-toolbar">
407
+ {databases.length > 1 ? (
408
+ <Select
409
+ popupClassName="dbw-sel-popup"
410
+ size="small" value={database || undefined} placeholder="数据库" style={{ width: 132 }}
411
+ onChange={(value) => void pickDatabase(value)}
412
+ options={databases.map((item) => ({ value: item, label: item === "" ? "(默认库)" : item }))}
413
+ />
414
+ ) : null}
415
+ <Select
416
+ popupClassName="dbw-sel-popup"
417
+ size="small" showSearch allowClear value={table || undefined} placeholder="选择表或视图"
418
+ style={{ flex: 1, minWidth: 140 }} optionFilterProp="label"
419
+ onChange={(value?: string) => { if (value) void loadTable(activeName, database, value); }}
420
+ options={(tablesByDb[database] ?? []).map((item) => ({ value: item.name, label: item.name }))}
421
+ />
422
+ </div>
350
423
  <div className="dbw-grid-wrap">
351
424
  <Table
352
425
  size="small" bordered sticky rowKey={(_, index) => String(index)} columns={dataColumns}
@@ -370,8 +443,18 @@ export function AntdWorkbench(): React.JSX.Element {
370
443
  key: "schema",
371
444
  label: <Space size={4}><ProfileOutlined />结构</Space>,
372
445
  children: (
373
- <Table size="small" bordered pagination={false} rowKey="name" dataSource={page?.columns ?? []} columns={schemaColumns}
374
- locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="从左侧选择表或视图" /> }} />
446
+ <Flex vertical gap={12} style={{ height: "100%", overflow: "auto" }}>
447
+ <div>
448
+ <Text strong>字段</Text>
449
+ <Table size="small" bordered pagination={false} rowKey="name" dataSource={page?.columns ?? []} columns={schemaColumns}
450
+ locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="从左侧或上方选择表或视图" /> }} />
451
+ </div>
452
+ <div>
453
+ <Text strong>索引</Text>
454
+ <Table size="small" bordered tableLayout="fixed" pagination={false} rowKey="name" dataSource={indexes} columns={indexColumns}
455
+ locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={table ? "这张表没有索引" : "选择表后显示索引"} /> }} />
456
+ </div>
457
+ </Flex>
375
458
  ),
376
459
  },
377
460
  {
@@ -387,7 +470,7 @@ export function AntdWorkbench(): React.JSX.Element {
387
470
  <Flex justify="space-between" align="center" gap={8} wrap>
388
471
  <Space size={6}>
389
472
  <Button type="primary" size="small" icon={<PlayCircleOutlined />} loading={loading === "sql"} disabled={!sql.trim()} onClick={() => void runSql()}>执行</Button>
390
- <Text type="secondary" style={{ fontSize: 11 }}>只读单条 · Ctrl+Enter</Text>
473
+ <Text type="secondary" style={{ fontSize: 11 }}>SELECT 只读 · INSERT 直通 · UPDATE 逐次确认 · DELETE/DDL 拒绝</Text>
391
474
  </Space>
392
475
  <Space size={0}>
393
476
  <Tooltip title="清空"><Button size="small" type="text" icon={<ClearOutlined />} onClick={() => { setSql(""); setResult(null); }} /></Tooltip>
@@ -459,7 +542,7 @@ export function AntdWorkbench(): React.JSX.Element {
459
542
  </div>
460
543
  </div>
461
544
  <Space size={2}>
462
- <Select size="small" variant="borderless" style={{ width: 76 }} value={pageSize}
545
+ <Select popupClassName="dbw-sel-popup" size="small" variant="borderless" style={{ width: 76 }} value={pageSize}
463
546
  options={[20, 50, 100].map((size) => ({ value: size, label: size + "/页" }))}
464
547
  onChange={(size) => { setPageSize(size); if (table) void loadTable(activeName, database, table, 1, size); }} />
465
548
  <Tooltip title="刷新"><Button size="small" type="text" icon={<ReloadOutlined />} disabled={!table} onClick={() => void loadTable(activeName, database, table, page?.page ?? 1, pageSize)} /></Tooltip>
@@ -505,12 +588,32 @@ export function AntdWorkbench(): React.JSX.Element {
505
588
  </Space>
506
589
  </div>
507
590
  <div className="dbw-connbar">
508
- <Select
509
- size="middle" variant="filled" style={{ flex: 1, minWidth: 0 }} placeholder="选择连接"
510
- value={activeName || undefined} onChange={(value) => void selectConnection(value)}
511
- options={connections.map((connection) => ({ value: connection.name, label: connection.name + " · " + ENGINE[connection.engine].label }))}
512
- notFoundContent={<Text type="secondary">还没有连接</Text>}
513
- />
591
+ <Dropdown
592
+ trigger={["click"]}
593
+ placement="bottomLeft"
594
+ overlayClassName="dbw-conn-menu"
595
+ menu={{
596
+ style: { background: "var(--dbw-solid-bg, #ffffff)" },
597
+ selectedKeys: activeName ? [activeName] : [],
598
+ items: connections.map((connection) => ({
599
+ key: connection.name,
600
+ label: (
601
+ <Space size={8}>
602
+ <span>{connection.name}</span>
603
+ <Text type="secondary" style={{ fontSize: 11 }}>{ENGINE[connection.engine].label}</Text>
604
+ </Space>
605
+ ),
606
+ })),
607
+ onClick: ({ key }) => void selectConnection(key),
608
+ }}
609
+ >
610
+ <Button className="dbw-conn-trigger" size="middle">
611
+ <DatabaseOutlined />
612
+ <span className="dbw-conn-name">{active ? active.name : "选择连接"}</span>
613
+ <span className="dbw-conn-meta">{active ? ENGINE[active.engine].label : connections.length + " 个连接"}</span>
614
+ <DownOutlined className="dbw-conn-arrow" />
615
+ </Button>
616
+ </Dropdown>
514
617
  {active ? (
515
618
  <>
516
619
  <Tooltip title="测试连接"><Button size="small" type="text" icon={<ThunderboltOutlined />} onClick={() => void testConnection(active)} /></Tooltip>
package/client/src/api.ts CHANGED
@@ -33,6 +33,9 @@ export type TablePage = {
33
33
  hasNext: boolean;
34
34
  };
35
35
  export type QueryResult = { connection: string; sql: string; columns: string[]; rows: Array<Record<string, unknown>>; rowCount: number; truncated: boolean };
36
+ export type IndexSummary = { name: string; columns: string[]; unique: boolean; type?: string; definition?: string };
37
+ export type ExecuteResult = { statementCount: number; affectedRows: number; results: Array<{ operation: "INSERT" | "UPDATE"; affectedRows: number }> };
38
+ export type ExecuteResponse = { needsConfirmation?: boolean; challengeId?: string; statements?: string[]; result?: ExecuteResult };
36
39
  export type ConnectionDocument = { schemaVersion: 1; exportedAt: string; connections: Connection[] };
37
40
 
38
41
  const BASE = "/zero-db-tool/api";
@@ -65,6 +68,11 @@ export const api = {
65
68
  `/connections/${encodeURIComponent(name)}/browse?table=${encodeURIComponent(table)}&page=${page}&pageSize=${pageSize}${database ? `&database=${encodeURIComponent(database)}` : ""}`),
66
69
  query: (name: string, sql: string, database?: string) => request<{ result: QueryResult }>(
67
70
  `/connections/${encodeURIComponent(name)}/query`, { method: "POST", body: JSON.stringify({ sql, maxRows: 500, ...(database ? { database } : {}) }) }),
71
+ indexes: (name: string, table: string, database?: string) => request<{ indexes: IndexSummary[] }>(
72
+ `/connections/${encodeURIComponent(name)}/indexes?table=${encodeURIComponent(table)}${database ? `&database=${encodeURIComponent(database)}` : ""}`),
73
+ execute: (name: string, sql: string, opts?: { database?: string; confirmationId?: string }) => request<ExecuteResponse>(
74
+ `/connections/${encodeURIComponent(name)}/execute`,
75
+ { method: "POST", body: JSON.stringify({ sql, ...(opts?.database ? { database: opts.database } : {}), ...(opts?.confirmationId ? { confirmationId: opts.confirmationId } : {}) }) }),
68
76
  exportAll: () => request<{ document: ConnectionDocument }>("/export"),
69
77
  importAll: (document: unknown, conflict: "skip" | "overwrite") => request<{ result: { imported: number; updated: number; skipped: number } }>(
70
78
  "/import", { method: "POST", body: JSON.stringify({ document, conflict }) }),
@@ -5,7 +5,7 @@ import React, { useEffect } from "react";
5
5
  import { App as AntdApp, ConfigProvider, theme } from "antd";
6
6
  import zhCN from "antd/locale/zh_CN";
7
7
  import { AntdWorkbench } from "./AntdWorkbench";
8
- import { isDarkTheme, resolveColor } from "./theme";
8
+ import { isDarkTheme, opaqueColor, resolveColor } from "./theme";
9
9
  import css from "./workbench.css";
10
10
 
11
11
  const TAB_ID = "zero-db-tool";
@@ -23,11 +23,15 @@ function ensureStyle(): void {
23
23
  function Body(): React.JSX.Element {
24
24
  useEffect(() => { ensureStyle(); }, []);
25
25
  const dark = isDarkTheme();
26
+ const solidBackground = opaqueColor(resolveColor("--dsw-alias-bg-base", "#ffffff"), dark ? "#1b1b1b" : "#ffffff");
27
+ const solidLayer = opaqueColor(resolveColor("--dsw-alias-bg-layer-1", "#ffffff"), dark ? "#1b1b1b" : "#ffffff");
28
+ useEffect(() => { document.documentElement.style.setProperty("--dbw-solid-bg", solidBackground); }, [solidBackground]);
26
29
  const token = {
27
30
  colorPrimary: resolveColor("--dsw-alias-button-primary-fill", "#1677ff"),
28
31
  colorInfo: resolveColor("--dsw-alias-state-business-primary", "#1677ff"),
29
- colorBgBase: resolveColor("--dsw-alias-bg-base", "#ffffff"),
30
- colorBgContainer: resolveColor("--dsw-alias-bg-layer-1", "#ffffff"),
32
+ colorBgBase: solidBackground,
33
+ colorBgContainer: solidLayer,
34
+ colorBgElevated: solidLayer,
31
35
  colorText: resolveColor("--dsw-alias-label-primary", "#1a1a1a"),
32
36
  colorTextSecondary: resolveColor("--dsw-alias-label-secondary", "#6b7280"),
33
37
  colorBorder: resolveColor("--dsw-alias-border-l3", "#d9d9d9"),
@@ -13,6 +13,23 @@ export function resolveColor(name: string, fallback: string): string {
13
13
  }
14
14
  }
15
15
 
16
+ /** 把可能带透明度的颜色与实色底混合,得到不透明颜色。 */
17
+ export function opaqueColor(color: string, fallbackBase: string): string {
18
+ const parse = (value: string): [number, number, number, number] | null => {
19
+ const match = /^rgba?\(([^)]+)\)$/i.exec(value.trim());
20
+ if (!match) return null;
21
+ const parts = match[1]!.split(/[,\s/]+/).filter(Boolean).map(Number);
22
+ if (parts.length < 3 || parts.some((item) => Number.isNaN(item))) return null;
23
+ return [parts[0]!, parts[1]!, parts[2]!, parts.length > 3 ? parts[3]! : 1];
24
+ };
25
+ const foreground = parse(color);
26
+ const base = parse(fallbackBase) ?? [255, 255, 255, 1];
27
+ if (!foreground) return fallbackBase;
28
+ const alpha = Math.min(Math.max(foreground[3], 0), 1);
29
+ const mix = (value: number, under: number) => Math.round(value * alpha + under * (1 - alpha));
30
+ return `rgb(${mix(foreground[0], base[0])}, ${mix(foreground[1], base[1])}, ${mix(foreground[2], base[2])})`;
31
+ }
32
+
16
33
  export function isDarkTheme(): boolean {
17
34
  try {
18
35
  const scheme = getComputedStyle(document.documentElement).colorScheme;
@@ -123,6 +123,33 @@
123
123
  .dbw-app { flex: 1; min-height: 0; }
124
124
  .dbw-sql { height: 100%; overflow: auto; padding-right: 2px; }
125
125
  .dbw-grid-wrap { overflow: auto; }
126
+ .dbw-toolbar { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
127
+ .dbw-conn-trigger {
128
+ flex: 1; min-width: 0; height: 36px; padding: 0 10px;
129
+ display: flex; align-items: center; gap: 8px; justify-content: flex-start;
130
+ }
131
+ .dbw-conn-name { font-weight: 600; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
132
+ .dbw-conn-meta { font-size: 11px; color: var(--dsw-alias-label-secondary, #888); }
133
+ .dbw-conn-arrow { margin-left: auto; opacity: 0.55; }
134
+ /* 宿主对浮层的玻璃样式会让菜单透出内容,这里用不透明底色盖住。 */
135
+ .dbw-conn-menu.ant-dropdown .ant-dropdown-menu {
136
+ background: var(--dbw-solid-bg, #ffffff) !important;
137
+ border: 1px solid var(--dsw-alias-border-l1, rgb(0 0 0 / 8%));
138
+ box-shadow: 0 12px 32px rgb(0 0 0 / 14%);
139
+ }
140
+ .dbw-conn-menu .ant-dropdown-menu-item { border-radius: 6px; }
141
+ /* 数据页的数据库/表/每页条数下拉同样需要实色背景。 */
142
+ .ant-select-dropdown.dbw-sel-popup.ant-select-dropdown {
143
+ background: var(--dbw-solid-bg, #ffffff) !important;
144
+ border: 1px solid var(--dsw-alias-border-l1, rgb(0 0 0 / 8%));
145
+ box-shadow: 0 12px 32px rgb(0 0 0 / 14%);
146
+ }
147
+ .dbw-nowrap { display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
148
+ .dbw-confirm-sql {
149
+ margin: 8px 0 0; padding: 8px 10px; max-height: 180px; overflow: auto;
150
+ white-space: pre-wrap; word-break: break-word; font-size: 12px; line-height: 1.5;
151
+ border-radius: 8px; background: color-mix(in srgb, var(--dsw-alias-bg-layer-2, #f5f5f5) 80%, transparent);
152
+ }
126
153
  .dbw-tree-body .ant-tree { font-size: 12px; }
127
154
  .dbw-tree-body .ant-tree-node-content-wrapper { width: 100%; overflow: hidden; display: flex; align-items: center; gap: 4px; }
128
155
  .dbw-tree-body .ant-tree-iconEle { flex: none; }
@@ -602,6 +602,69 @@ export class DbConnectionRegistry {
602
602
  hasNext: rows.length > safePageSize,
603
603
  };
604
604
  }
605
+ async listIndexes(name, requestedTable, selectedDatabase) {
606
+ const config = this.getConfig(name);
607
+ const tables = await this.listTables(name, selectedDatabase);
608
+ const table = tables.find((candidate) => (candidate.schema ? `${candidate.schema}.${candidate.name}` : candidate.name) === requestedTable);
609
+ if (!table)
610
+ throw new DbConnectionError("DB_INVALID_CONFIG", `table or view "${requestedTable}" does not exist`);
611
+ const escapedName = config.engine === "mysql"
612
+ ? `\`${table.name.replaceAll("\`", "\`\`")}\``
613
+ : `"${table.name.replaceAll('"', '""')}"`;
614
+ const identifier = config.engine === "mysql" && table.schema
615
+ ? `\`${table.schema.replaceAll("\`", "\`\`")}\`.\`${table.name.replaceAll("\`", "\`\`")}\``
616
+ : escapedName;
617
+ if (config.engine === "sqlite") {
618
+ const rows = await this.queryWithReconnect(name, (handle) => handle.query(`PRAGMA index_list(${escapedName})`), selectedDatabase);
619
+ const indexes = [];
620
+ for (const row of rows) {
621
+ const indexName = String(row.name ?? "");
622
+ if (indexName === "")
623
+ continue;
624
+ const quoted = `"${indexName.replaceAll('"', '""')}"`;
625
+ const info = await this.queryWithReconnect(name, (handle) => handle.query(`PRAGMA index_info(${quoted})`), selectedDatabase);
626
+ indexes.push({
627
+ name: indexName,
628
+ columns: info.map((column) => String(column.name ?? "")).filter(Boolean),
629
+ unique: Number(row.unique ?? 0) === 1,
630
+ ...(typeof row.origin === "string" ? { type: row.origin } : {}),
631
+ });
632
+ }
633
+ return indexes;
634
+ }
635
+ if (config.engine === "postgres") {
636
+ const literal = table.name.replaceAll("'", "''");
637
+ const rows = await this.queryWithReconnect(name, (handle) => handle.query(`SELECT i.relname AS name, ix.indisunique AS is_unique, pg_get_indexdef(ix.indexrelid) AS definition,
638
+ (SELECT array_agg(a.attname ORDER BY k.ord)
639
+ FROM unnest(ix.indkey) WITH ORDINALITY AS k(attnum, ord)
640
+ JOIN pg_attribute a ON a.attrelid = t.oid AND a.attnum = k.attnum) AS columns
641
+ FROM pg_class t JOIN pg_index ix ON t.oid = ix.indrelid JOIN pg_class i ON i.oid = ix.indexrelid
642
+ WHERE t.relname = '${literal}' AND t.relkind = 'r'`), selectedDatabase);
643
+ return rows.map((row) => ({
644
+ name: String(row.name ?? ""),
645
+ columns: Array.isArray(row.columns) ? row.columns.map(String) : [],
646
+ unique: row.is_unique === true || String(row.is_unique) === "t",
647
+ ...(typeof row.definition === "string" ? { definition: row.definition } : {}),
648
+ }));
649
+ }
650
+ const rows = await this.queryWithReconnect(name, (handle) => handle.query(`SHOW INDEX FROM ${identifier}`), selectedDatabase);
651
+ const grouped = new Map();
652
+ for (const row of rows) {
653
+ const indexName = String(row.Key_name ?? "");
654
+ if (indexName === "")
655
+ continue;
656
+ const entry = grouped.get(indexName) ?? { columns: [], unique: true, type: typeof row.Index_type === "string" ? row.Index_type : undefined };
657
+ entry.columns.push({ seq: Number(row.Seq_in_index ?? 0), name: String(row.Column_name ?? "") });
658
+ entry.unique = entry.unique && Number(row.Non_unique ?? 1) === 0;
659
+ grouped.set(indexName, entry);
660
+ }
661
+ return [...grouped.entries()].map(([indexName, entry]) => ({
662
+ name: indexName,
663
+ columns: entry.columns.sort((a, b) => a.seq - b.seq).map((column) => column.name).filter(Boolean),
664
+ unique: entry.unique,
665
+ ...(entry.type ? { type: entry.type } : {}),
666
+ }));
667
+ }
605
668
  getConfig(name) {
606
669
  this.ensureLoadedSync(true);
607
670
  const config = this.configs.get(name);
@@ -662,9 +725,9 @@ export class DbConnectionRegistry {
662
725
  };
663
726
  }
664
727
  /** Execute one approved INSERT or UPDATE and return affected rows. */
665
- async executeWrite(name, sql) {
728
+ async executeWrite(name, sql, selectedDatabase) {
666
729
  assertDatabaseWriteSql(sql);
667
- return this.queryWithReconnect(name, (handle) => handle.run(sql));
730
+ return this.queryWithReconnect(name, (handle) => handle.run(sql), selectedDatabase);
668
731
  }
669
732
  /**
670
733
  * Drop the cached connection for `name` (if any) so the next connect()
package/dist/http.js CHANGED
@@ -1,6 +1,30 @@
1
+ /**
2
+ * 工作台 HTTP API(挂载在 DSH webServer 的 /zero-db-tool/api 前缀),供右侧栏使用。
3
+ * 成功 { ok: true, ... };失败 { ok: false, error: { code, message } }。
4
+ */
5
+ import { createHash, randomUUID } from "node:crypto";
1
6
  import { DbConnectionError } from "./connections.js";
2
- import { SqlGuardError } from "./sql-guard.js";
7
+ import { SqlGuardError, assertWriteStatement, splitStatements } from "./sql-guard.js";
3
8
  const MAX_BODY_BYTES = 2 * 1024 * 1024;
9
+ const WRITE_CHALLENGE_TTL_MS = 2 * 60_000;
10
+ const pendingWrites = new Map();
11
+ function sqlHash(sql) {
12
+ return createHash("sha256").update(sql.trim()).digest("hex");
13
+ }
14
+ function takeChallenge(id, connection, sql) {
15
+ const now = Date.now();
16
+ for (const [key, value] of pendingWrites)
17
+ if (value.expiresAt <= now)
18
+ pendingWrites.delete(key);
19
+ const challenge = pendingWrites.get(id);
20
+ if (!challenge)
21
+ throw new SqlGuardError("DB_CONFIRMATION_REQUIRED", "确认已过期,请重新执行 UPDATE");
22
+ if (challenge.connection !== connection || challenge.hash !== sqlHash(sql)) {
23
+ pendingWrites.delete(id);
24
+ throw new SqlGuardError("DB_CONFIRMATION_REQUIRED", "确认与当前语句不匹配,请重新执行 UPDATE");
25
+ }
26
+ pendingWrites.delete(id);
27
+ }
4
28
  function isLoopbackHostname(hostname) {
5
29
  const host = String(hostname ?? "").replace(/^\[|\]$/g, "").toLowerCase();
6
30
  return host === "localhost" || host === "127.0.0.1" || host === "::1";
@@ -133,7 +157,7 @@ export async function handleRequest(req, res, service, options) {
133
157
  send(res, 200, { ok: true, result });
134
158
  return;
135
159
  }
136
- const itemMatch = /^\/api\/connections\/([^/]+)(?:\/(test|catalog|browse|query))?$/.exec(path);
160
+ const itemMatch = /^\/api\/connections\/([^/]+)(?:\/(test|catalog|browse|query|indexes|execute))?$/.exec(path);
137
161
  if (itemMatch) {
138
162
  const name = decodeURIComponent(itemMatch[1]);
139
163
  const action = itemMatch[2];
@@ -161,6 +185,37 @@ export async function handleRequest(req, res, service, options) {
161
185
  send(res, 200, { ok: true, result: await service.browse(name, table, page, pageSize, database) });
162
186
  return;
163
187
  }
188
+ if (method === "GET" && action === "indexes") {
189
+ const database = query.get("database") ?? undefined;
190
+ const table = (query.get("table") ?? "").trim();
191
+ if (table === "")
192
+ throw new SqlGuardError("DB_INVALID_CONFIG", "未选择表:请先刷新表目录再选择表或视图");
193
+ send(res, 200, { ok: true, indexes: await service.indexes(name, table, database) });
194
+ return;
195
+ }
196
+ if (method === "POST" && action === "execute") {
197
+ const body = await readJson(req);
198
+ const sql = String(body.sql ?? "");
199
+ const database = typeof body.database === "string" && body.database !== "" ? body.database : undefined;
200
+ const statements = splitStatements(sql);
201
+ if (statements.length === 0)
202
+ throw new SqlGuardError("DB_INVALID_CONFIG", "sql is empty");
203
+ // 只放行 INSERT / UPDATE;DELETE、DDL、事务等在这里就被拒绝。
204
+ const kinds = statements.map((statement) => assertWriteStatement(statement));
205
+ const needsApproval = kinds.includes("UPDATE");
206
+ const confirmationId = String(body.confirmationId ?? "");
207
+ if (needsApproval && confirmationId === "") {
208
+ const challengeId = randomUUID();
209
+ pendingWrites.set(challengeId, { connection: name, hash: sqlHash(sql), expiresAt: Date.now() + WRITE_CHALLENGE_TTL_MS });
210
+ send(res, 200, { ok: true, needsConfirmation: true, challengeId, statements, kinds, database });
211
+ return;
212
+ }
213
+ if (needsApproval)
214
+ takeChallenge(confirmationId, name, sql);
215
+ const result = await service.execute(name, sql, database);
216
+ send(res, 200, { ok: true, result });
217
+ return;
218
+ }
164
219
  if (method === "POST" && action === "query") {
165
220
  const body = await readJson(req);
166
221
  const sql = String(body.sql ?? "");
package/dist/manager.js CHANGED
@@ -87,7 +87,7 @@ export class WorkbenchService {
87
87
  return { connection, columns, rows, rowCount: rows.length, truncated, ...(text !== undefined ? { text } : {}) };
88
88
  }
89
89
  /** Execute an INSERT/UPDATE batch. Callers own the UPDATE approval gate. */
90
- async execute(connection, sql) {
90
+ async execute(connection, sql, database) {
91
91
  const statements = splitStatements(sql ?? "");
92
92
  if (statements.length === 0)
93
93
  throw new SqlGuardError("DB_INVALID_CONFIG", "sql is empty");
@@ -95,7 +95,7 @@ export class WorkbenchService {
95
95
  return this.withTimeout((async () => {
96
96
  const results = [];
97
97
  for (let index = 0; index < statements.length; index += 1) {
98
- const affectedRows = await this.withReconnect(connection, () => this.registry.executeWrite(connection, statements[index]));
98
+ const affectedRows = await this.withReconnect(connection, () => this.registry.executeWrite(connection, statements[index], database));
99
99
  results.push({ operation: kinds[index], affectedRows });
100
100
  }
101
101
  return {
@@ -105,6 +105,12 @@ export class WorkbenchService {
105
105
  };
106
106
  })(), SQL_EXEC_TIMEOUT_MS, () => this.registry.evict(connection));
107
107
  }
108
+ /** Indexes for one table (read-only metadata). */
109
+ async indexes(connection, table, database) {
110
+ if (!table || table.trim() === "")
111
+ throw new SqlGuardError("DB_INVALID_CONFIG", "未选择表:请先刷新表目录再选择表或视图");
112
+ return this.withTimeout(this.registry.listIndexes(connection, table, database), SQL_QUERY_TIMEOUT_MS);
113
+ }
108
114
  /** Whether a batch needs human approval before it may run. */
109
115
  needsApproval(sql) {
110
116
  return splitStatements(sql ?? "").some((statement) => assertWriteStatement(statement) === "UPDATE");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "zero-db-tool",
3
- "version": "1.0.1",
3
+ "version": "1.1.1",
4
4
  "description": "DSH 数据库工作台:连接下拉 + 对象树 + 数据/结构/SQL,SQLite/PostgreSQL/MySQL,只读优先,六个 sql_* 工具",
5
5
  "type": "module",
6
6
  "license": "BSD-3-Clause",