zero-db-tool 0.0.0-stage → 1.0.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.
@@ -0,0 +1,632 @@
1
+ /**
2
+ * DBeaver / Navicat 式右侧栏工作台:连接下拉 + 对象树 + 数据/结构/SQL。
3
+ */
4
+ import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
+ import {
6
+ App, Button, Card, Dropdown, Empty, Flex, Form, Input, InputNumber, Modal, Popconfirm,
7
+ Drawer, Radio, Select, Space, Splitter, Switch, Table, Tabs, Tag, Tooltip, Tree, Typography, theme,
8
+ } from "antd";
9
+ import type { ColumnsType } from "antd/es/table";
10
+ import type { DataNode } from "antd/es/tree";
11
+ import {
12
+ ApartmentOutlined, ClearOutlined, CodeOutlined, CopyOutlined, DatabaseOutlined, DeleteOutlined, DownloadOutlined,
13
+ EditOutlined, EyeOutlined, MoreOutlined, PlayCircleOutlined, PlusOutlined, ProfileOutlined,
14
+ ReloadOutlined, SearchOutlined, TableOutlined, ThunderboltOutlined,
15
+ } from "@ant-design/icons";
16
+ import { api, type ColumnSummary, type Connection, type DbEngine, type TablePage, type TableSummary } from "./api";
17
+
18
+ const { Text } = Typography;
19
+ const HISTORY_KEY = "zero-db-tool.sql-history";
20
+ const ENGINE: Record<DbEngine, { label: string; color: string }> = {
21
+ sqlite: { label: "SQLite", color: "#2f8e6f" },
22
+ postgres: { label: "PostgreSQL", color: "#3b82f6" },
23
+ mysql: { label: "MySQL", color: "#d97706" },
24
+ };
25
+
26
+ type Health = { ok: boolean; ms?: number; message?: string };
27
+ type FormValues = {
28
+ name: string; engine: DbEngine; path?: string; mode?: "parameters" | "url-env"; urlEnv?: string;
29
+ host?: string; port?: number; database?: string; username?: string;
30
+ passwordMode?: "encrypted" | "runtime" | "environment"; password?: string; passwordEnv?: string; ssl?: boolean;
31
+ };
32
+ type TableResult = { columns: string[]; rows: Array<Record<string, unknown>>; rowCount: number; truncated: boolean };
33
+
34
+ function cell(value: unknown): string {
35
+ if (value === null) return "NULL";
36
+ if (value === undefined) return "";
37
+ if (typeof value === "object") return JSON.stringify(value);
38
+ return String(value);
39
+ }
40
+ function targetOf(connection: Connection): string {
41
+ if (connection.engine === "sqlite") return connection.path ?? "";
42
+ return (connection.host ?? "") + (connection.port ? ":" + connection.port : "") + (connection.database ? " / " + connection.database : "");
43
+ }
44
+ function csvOf(columns: string[], rows: Array<Record<string, unknown>>): string {
45
+ const escape = (value: unknown) => {
46
+ const text = cell(value);
47
+ return /[",\n]/.test(text) ? '"' + text.replace(/"/g, '""') + '"' : text;
48
+ };
49
+ return [columns.join(","), ...rows.map((row) => columns.map((column) => escape(row[column])).join(","))].join("\n");
50
+ }
51
+ function download(name: string, text: string, type?: string): void {
52
+ const blob = new Blob(["\ufeff" + text], { type: type ?? "text/csv;charset=utf-8" });
53
+ const url = URL.createObjectURL(blob);
54
+ const anchor = document.createElement("a");
55
+ anchor.href = url;
56
+ anchor.download = name;
57
+ anchor.click();
58
+ URL.revokeObjectURL(url);
59
+ }
60
+
61
+ export function AntdWorkbench(): React.JSX.Element {
62
+ const { message } = App.useApp();
63
+ const { token } = theme.useToken();
64
+ const [connections, setConnections] = useState<Connection[]>([]);
65
+ const [activeName, setActiveName] = useState("");
66
+ const [health, setHealth] = useState<Record<string, Health>>({});
67
+ const [databases, setDatabases] = useState<string[]>([]);
68
+ const [tablesByDb, setTablesByDb] = useState<Record<string, TableSummary[]>>({});
69
+ const [database, setDatabase] = useState("");
70
+ const [table, setTable] = useState("");
71
+ const [pageSize, setPageSize] = useState(50);
72
+ const [page, setPage] = useState<TablePage | null>(null);
73
+ const [mode, setMode] = useState<"data" | "schema" | "sql">("data");
74
+ const [sql, setSql] = useState("");
75
+ const [result, setResult] = useState<TableResult | null>(null);
76
+ const [loading, setLoading] = useState("");
77
+ const [search, setSearch] = useState("");
78
+ const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
79
+ const [formOpen, setFormOpen] = useState(false);
80
+ const [editing, setEditing] = useState<Connection | null>(null);
81
+ const [history, setHistory] = useState<string[]>([]);
82
+ const [version, setVersion] = useState("");
83
+ const [narrow, setNarrow] = useState(false);
84
+ const [treeOpen, setTreeOpen] = useState(true);
85
+ const [drawerOpen, setDrawerOpen] = useState(false);
86
+ const appRef = useRef<HTMLDivElement>(null);
87
+ const [form] = Form.useForm<FormValues>();
88
+ const fileRef = useRef<HTMLInputElement>(null);
89
+ const engine = Form.useWatch("engine", form) ?? "sqlite";
90
+ const passwordMode = Form.useWatch("passwordMode", form) ?? "encrypted";
91
+ const connectMode = Form.useWatch("mode", form) ?? "parameters";
92
+
93
+ const active = useMemo(() => connections.find((item) => item.name === activeName), [connections, activeName]);
94
+
95
+ useEffect(() => {
96
+ try { setHistory(JSON.parse(localStorage.getItem(HISTORY_KEY) ?? "[]") as string[]); } catch { setHistory([]); }
97
+ void api.version().then((payload) => setVersion(payload.version)).catch(() => setVersion(""));
98
+ }, []);
99
+
100
+ const pushHistory = useCallback((statement: string) => {
101
+ const text = statement.trim();
102
+ if (!text) return;
103
+ setHistory((current) => {
104
+ const next = [text, ...current.filter((item) => item !== text)].slice(0, 8);
105
+ try { localStorage.setItem(HISTORY_KEY, JSON.stringify(next)); } catch { /* ignore */ }
106
+ return next;
107
+ });
108
+ }, []);
109
+
110
+ const loadConnections = useCallback(async () => {
111
+ setLoading("connections");
112
+ try {
113
+ const payload = await api.list();
114
+ setConnections(payload.connections ?? []);
115
+ } catch (cause) {
116
+ message.error(cause instanceof Error ? cause.message : String(cause));
117
+ } finally { setLoading(""); }
118
+ }, [message]);
119
+
120
+ useEffect(() => { void loadConnections(); }, [loadConnections]);
121
+
122
+ useEffect(() => {
123
+ const node = appRef.current;
124
+ if (!node || typeof ResizeObserver === "undefined") return;
125
+ const observer = new ResizeObserver((entries) => {
126
+ const width = entries[0]?.contentRect.width ?? node.clientWidth;
127
+ setNarrow(width < 560);
128
+ });
129
+ observer.observe(node);
130
+ return () => observer.disconnect();
131
+ }, []);
132
+
133
+ const loadTable = useCallback(async (name: string, db: string, tableName: string, nextPage = 1, size = pageSize) => {
134
+ setLoading("rows");
135
+ try {
136
+ const payload = await api.browse(name, tableName, nextPage, size, db || undefined);
137
+ setPage(payload.result);
138
+ setTable(tableName);
139
+ setDatabase(db);
140
+ } catch (cause) {
141
+ message.error(cause instanceof Error ? cause.message : String(cause));
142
+ } finally { setLoading(""); }
143
+ }, [message, pageSize]);
144
+
145
+ const selectConnection = useCallback(async (name: string) => {
146
+ const connection = connections.find((item) => item.name === name);
147
+ if (!connection) return;
148
+ setActiveName(name);
149
+ setPage(null); setResult(null); setTablesByDb({}); setDatabase(""); setTable(""); setSearch("");
150
+ setLoading("catalog");
151
+ try {
152
+ const payload = await api.catalog(name, connection.database ?? undefined);
153
+ const dbs = payload.databases ?? [];
154
+ const configured = (connection.database ?? '').trim();
155
+ // 服务级连接(MySQL / 未指定库的 PostgreSQL)只列库,表在展开时按库懒加载。
156
+ const serverLevel = (connection.engine === 'mysql' || connection.engine === 'postgres') && configured === '';
157
+ const db = configured !== '' ? configured : (dbs.length === 1 ? dbs[0] ?? '' : '');
158
+ setDatabases(dbs.length > 0 ? dbs : ['']);
159
+ setDatabase(db);
160
+ if (serverLevel) {
161
+ setTablesByDb({});
162
+ setExpandedKeys([]);
163
+ } else {
164
+ setExpandedKeys((dbs.length > 0 ? dbs : ['']).map((item) => 'db:' + item));
165
+ setTablesByDb({ [db]: payload.tables ?? [] });
166
+ const first = (payload.tables ?? [])[0];
167
+ if (first) await loadTable(name, db, first.name, 1, pageSize);
168
+ }
169
+ } catch (cause) {
170
+ message.error(cause instanceof Error ? cause.message : String(cause));
171
+ } finally { setLoading(""); }
172
+ }, [connections, loadTable, message, pageSize]);
173
+
174
+ async function testConnection(connection: Connection) {
175
+ try {
176
+ const payload = await api.test(connection.name);
177
+ setHealth((current) => ({ ...current, [connection.name]: { ok: true, ms: payload.result?.elapsedMs } }));
178
+ message.success(connection.name + " 可用");
179
+ } catch (cause) {
180
+ const text = cause instanceof Error ? cause.message : String(cause);
181
+ setHealth((current) => ({ ...current, [connection.name]: { ok: false, message: text } }));
182
+ message.error(text);
183
+ }
184
+ }
185
+
186
+ async function removeConnection(connection: Connection) {
187
+ try {
188
+ await api.remove(connection.name);
189
+ message.success("已删除 " + connection.name);
190
+ if (activeName === connection.name) { setActiveName(""); setPage(null); setDatabases([]); setTablesByDb({}); }
191
+ await loadConnections();
192
+ } catch (cause) {
193
+ message.error(cause instanceof Error ? cause.message : String(cause));
194
+ }
195
+ }
196
+
197
+ function openCreate() {
198
+ setEditing(null);
199
+ form.resetFields();
200
+ form.setFieldsValue({ engine: "sqlite", passwordMode: "encrypted", mode: "parameters", host: "127.0.0.1", ssl: false });
201
+ setFormOpen(true);
202
+ }
203
+ function openEdit(connection: Connection) {
204
+ setEditing(connection);
205
+ form.setFieldsValue({
206
+ name: connection.name, engine: connection.engine, path: connection.path,
207
+ mode: connection.mode ?? "parameters", urlEnv: connection.urlEnv, host: connection.host,
208
+ port: connection.port, database: connection.database, username: connection.username,
209
+ passwordMode: connection.passwordMode ?? "runtime", passwordEnv: connection.passwordEnv, ssl: connection.ssl,
210
+ });
211
+ setFormOpen(true);
212
+ }
213
+
214
+ async function save() {
215
+ const values = await form.validateFields();
216
+ const body: Record<string, unknown> = values.engine === "sqlite"
217
+ ? { name: values.name, engine: "sqlite", path: values.path }
218
+ : values.mode === "url-env"
219
+ ? { name: values.name, engine: values.engine, mode: "url-env", urlEnv: values.urlEnv }
220
+ : {
221
+ name: values.name, engine: values.engine, mode: "parameters",
222
+ host: values.host, port: values.port, database: values.database, username: values.username,
223
+ passwordMode: values.passwordMode, ssl: values.ssl === true,
224
+ ...(values.passwordMode === "environment" ? { passwordEnv: values.passwordEnv } : (values.password ? { password: values.password } : {})),
225
+ };
226
+ setLoading("save");
227
+ try {
228
+ if (editing) await api.update(editing.name, body);
229
+ else await api.add(body);
230
+ message.success(editing ? "连接已更新" : "连接已保存");
231
+ setFormOpen(false);
232
+ await loadConnections();
233
+ } catch (cause) {
234
+ message.error(cause instanceof Error ? cause.message : String(cause));
235
+ } finally { setLoading(""); }
236
+ }
237
+
238
+ async function exportConnections() {
239
+ try {
240
+ const payload = await api.exportAll();
241
+ download("zero-db-tool-connections-" + new Date().toISOString().slice(0, 10) + ".json", JSON.stringify(payload.document, null, 2) + "\n", "application/json");
242
+ message.success("已导出(不含密码)");
243
+ } catch (cause) {
244
+ message.error(cause instanceof Error ? cause.message : String(cause));
245
+ }
246
+ }
247
+
248
+ async function importConnections(file: File) {
249
+ try {
250
+ const document_ = JSON.parse(await file.text());
251
+ const payload = await api.importAll(document_, "skip");
252
+ message.success("导入完成:新增 " + payload.result.imported + ",跳过 " + payload.result.skipped);
253
+ await loadConnections();
254
+ } catch (cause) {
255
+ message.error(cause instanceof Error ? cause.message : String(cause));
256
+ }
257
+ }
258
+
259
+ async function runSql() {
260
+ if (!active || sql.trim() === "") return;
261
+ setLoading("sql");
262
+ setResult(null);
263
+ try {
264
+ const payload = await api.query(active.name, sql, database || undefined);
265
+ setResult(payload.result);
266
+ pushHistory(sql);
267
+ } catch (cause) {
268
+ message.error(cause instanceof Error ? cause.message : String(cause));
269
+ } finally { setLoading(""); }
270
+ }
271
+
272
+ function copyValue(value: unknown) {
273
+ const text = cell(value);
274
+ if (text === "" || text === "NULL") return;
275
+ void navigator.clipboard?.writeText(text).then(() => message.success("已复制"));
276
+ }
277
+
278
+ async function expandDatabase(key: string) {
279
+ if (!active) return;
280
+ if (tablesByDb[key] !== undefined) return;
281
+ try {
282
+ const payload = await api.catalog(active.name, key || undefined);
283
+ setTablesByDb((current) => ({ ...current, [key]: payload.tables ?? [] }));
284
+ } catch (cause) {
285
+ message.error(cause instanceof Error ? cause.message : String(cause));
286
+ }
287
+ }
288
+
289
+ const treeData: DataNode[] = useMemo(() => {
290
+ const query = search.trim().toLowerCase();
291
+ const nodes: DataNode[] = [];
292
+ for (const db of databases) {
293
+ const tables = tablesByDb[db] ?? [];
294
+ const visible = query === "" ? tables : tables.filter((item) => item.name.toLowerCase().includes(query));
295
+ if (query !== "" && visible.length === 0) continue;
296
+ const loaded = tablesByDb[db] !== undefined;
297
+ nodes.push({
298
+ key: 'db:' + db,
299
+ title: db === '' ? '(默认库)' : db,
300
+ icon: <DatabaseOutlined />,
301
+ selectable: false,
302
+ isLeaf: false,
303
+ ...(loaded ? { children: visible.map((item) => ({
304
+ key: 'tb:' + db + ':' + item.name,
305
+ title: item.name,
306
+ icon: item.type === 'view' ? <EyeOutlined /> : <TableOutlined />,
307
+ isLeaf: true,
308
+ })) } : {}),
309
+ });
310
+
311
+ }
312
+ return nodes;
313
+ }, [databases, tablesByDb, search]);
314
+
315
+ const dataColumns: ColumnsType<Record<string, unknown>> = useMemo(() => {
316
+ const columns: ColumnSummary[] = page?.columns ?? [];
317
+ if (columns.length > 0) {
318
+ const mapped = columns.map((column) => ({
319
+ title: <Space size={4}><span>{column.name}</span>{column.primaryKey ? <Tag color="gold" style={{ marginInlineEnd: 0 }}>PK</Tag> : null}</Space>,
320
+ dataIndex: column.name, key: column.name, ellipsis: true,
321
+ render: (value: unknown) => <span onDoubleClick={() => copyValue(value)} title={cell(value)}>{cell(value)}</span>,
322
+ }));
323
+ return [{ title: "#", key: "__row", width: 42, render: (_: unknown, __: unknown, index: number) => <span className="dbw-rownum">{index + 1}</span> }, ...mapped];
324
+ }
325
+ const keys = page?.rows[0] ? Object.keys(page.rows[0]) : [];
326
+ return keys.map((key) => ({ title: key, dataIndex: key, key, ellipsis: true, render: (value: unknown) => cell(value) }));
327
+ }, [page]);
328
+
329
+ const sqlColumns: ColumnsType<Record<string, unknown>> = useMemo(() => {
330
+ const keys = result?.columns.length ? result.columns : (result?.rows[0] ? Object.keys(result.rows[0]) : []);
331
+ return keys.map((key) => ({ title: key, dataIndex: key, key, ellipsis: true, render: (value: unknown) => <span onDoubleClick={() => copyValue(value)}>{cell(value)}</span> }));
332
+ }, [result]);
333
+
334
+ const schemaColumns: ColumnsType<ColumnSummary> = [
335
+ { title: "字段", dataIndex: "name", key: "name", width: 130 },
336
+ { title: "类型", dataIndex: "type", key: "type", render: (value: string) => value || "未知类型" },
337
+ { title: "约束", key: "constraint", render: (_: unknown, column: ColumnSummary) => [column.primaryKey ? "主键" : "", column.nullable ? "可空" : "非空"].filter(Boolean).join(" · ") },
338
+ ];
339
+
340
+ const dataKeys = dataColumns.map((column) => String(column.dataIndex ?? "")).filter((key) => key !== "__row");
341
+ const activeMeta = active ? ENGINE[active.engine] : null;
342
+ const state = active ? health[active.name] : undefined;
343
+
344
+ const tabItems = [
345
+ {
346
+ key: "data",
347
+ label: <Space size={4}><TableOutlined />数据</Space>,
348
+ children: (
349
+ <Flex vertical gap={8} style={{ height: "100%" }}>
350
+ <div className="dbw-grid-wrap">
351
+ <Table
352
+ size="small" bordered sticky rowKey={(_, index) => String(index)} columns={dataColumns}
353
+ dataSource={page?.rows ?? []} pagination={false} scroll={{ x: "max-content" }} loading={loading === "rows"}
354
+ locale={{ emptyText: <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={table ? "没有数据" : (narrow ? "点击「对象」选择表" : "从左侧选择表或视图")} /> }}
355
+ />
356
+ </div>
357
+ {page ? (
358
+ <Flex justify="space-between" align="center">
359
+ <Text type="secondary">第 {page.page} 页 · 本页 {page.rows.length} 行</Text>
360
+ <Space size={4}>
361
+ <Button size="small" disabled={page.page <= 1 || loading === "rows"} onClick={() => void loadTable(activeName, database, table, page.page - 1, pageSize)}>上一页</Button>
362
+ <Button size="small" disabled={!page.hasNext || loading === "rows"} onClick={() => void loadTable(activeName, database, table, page.page + 1, pageSize)}>下一页</Button>
363
+ </Space>
364
+ </Flex>
365
+ ) : null}
366
+ </Flex>
367
+ ),
368
+ },
369
+ {
370
+ key: "schema",
371
+ label: <Space size={4}><ProfileOutlined />结构</Space>,
372
+ 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="从左侧选择表或视图" /> }} />
375
+ ),
376
+ },
377
+ {
378
+ key: "sql",
379
+ label: <Space size={4}><CodeOutlined />SQL</Space>,
380
+ children: (
381
+ <Flex vertical gap={8} className="dbw-sql">
382
+ <Input.TextArea
383
+ rows={7} value={sql} onChange={(event) => setSql(event.target.value)} spellCheck={false}
384
+ placeholder={"SELECT *\nFROM table_name\nLIMIT 50"}
385
+ onKeyDown={(event) => { if ((event.ctrlKey || event.metaKey) && event.key === "Enter") { event.preventDefault(); void runSql(); } }}
386
+ />
387
+ <Flex justify="space-between" align="center" gap={8} wrap>
388
+ <Space size={6}>
389
+ <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>
391
+ </Space>
392
+ <Space size={0}>
393
+ <Tooltip title="清空"><Button size="small" type="text" icon={<ClearOutlined />} onClick={() => { setSql(""); setResult(null); }} /></Tooltip>
394
+ <Tooltip title="复制 SQL"><Button size="small" type="text" icon={<CopyOutlined />} onClick={() => { void navigator.clipboard?.writeText(sql); message.success("已复制 SQL"); }} /></Tooltip>
395
+ </Space>
396
+ </Flex>
397
+ {history.length > 0 ? (
398
+ <Flex gap={4} wrap align="center">
399
+ <Text type="secondary" style={{ fontSize: 11 }}>历史</Text>
400
+ {history.slice(0, 5).map((item) => (
401
+ <Tag key={item} style={{ cursor: "pointer", maxWidth: 170, overflow: "hidden", textOverflow: "ellipsis" }} onClick={() => setSql(item)} title={item}>
402
+ {item.replace(/\s+/g, " ").slice(0, 36)}
403
+ </Tag>
404
+ ))}
405
+ </Flex>
406
+ ) : null}
407
+ {result ? (
408
+ <Flex vertical gap={6}>
409
+ <Flex justify="space-between" align="center">
410
+ <Space size={6}>
411
+ <Tag color="blue">{result.rowCount} 行</Tag>
412
+ {result.truncated ? <Tag color="orange">已截断</Tag> : null}
413
+ </Space>
414
+ <Button size="small" type="text" icon={<DownloadOutlined />} onClick={() => download(activeName + "-query.csv", csvOf(result.columns.length ? result.columns : Object.keys(result.rows[0] ?? {}), result.rows))}>CSV</Button>
415
+ </Flex>
416
+ <Table size="small" bordered rowKey={(_, index) => String(index)} columns={sqlColumns} dataSource={result.rows} pagination={false} scroll={{ x: "max-content" }} />
417
+ </Flex>
418
+ ) : null}
419
+ </Flex>
420
+ ),
421
+ },
422
+ ];
423
+
424
+ const treeContent = (
425
+ <>
426
+ <div className="dbw-tree-head">
427
+ <span className="dbw-section-label">对象</span>
428
+ <Input size="small" variant="filled" allowClear prefix={<SearchOutlined />} placeholder="搜索表" value={search} onChange={(event) => setSearch(event.target.value)} />
429
+ </div>
430
+ <div className="dbw-tree-body">
431
+ <Tree
432
+ blockNode showIcon treeData={treeData} selectedKeys={active && table ? ["tb:" + database + ":" + table] : []}
433
+ expandedKeys={search.trim() !== "" ? databases.map((db) => "db:" + db) : expandedKeys}
434
+ onSelect={(keys) => {
435
+ const key = String(keys[0] ?? "");
436
+ if (!key.startsWith("tb:")) return;
437
+ const rest = key.slice(3);
438
+ const separator = rest.indexOf(":");
439
+ setMode("data");
440
+ if (narrow) setDrawerOpen(false);
441
+ void loadTable(activeName, rest.slice(0, separator), rest.slice(separator + 1), 1, pageSize);
442
+ }}
443
+ onExpand={(keys) => { setExpandedKeys(keys); for (const key of keys) void expandDatabase(String(key).slice(3)); }}
444
+ />
445
+ </div>
446
+ </>
447
+ );
448
+
449
+ const mainPane = (
450
+ <div className="dbw-main">
451
+ <div className="dbw-main-head">
452
+ <div className="dbw-main-title">
453
+ <Tooltip title={narrow ? "对象树" : treeOpen ? "隐藏对象树" : "显示对象树"}>
454
+ <Button size="small" type="text" aria-label="对象" icon={<ApartmentOutlined />} onClick={() => { if (narrow) setDrawerOpen(true); else setTreeOpen(!treeOpen); }}>{narrow ? "对象" : null}</Button>
455
+ </Tooltip>
456
+ <div>
457
+ <span className="dbw-table-name">{table || "选择表或视图"}</span>
458
+ <span className="dbw-table-path">{database ? database + " / " : ""}{table || "从对象树选择"}</span>
459
+ </div>
460
+ </div>
461
+ <Space size={2}>
462
+ <Select size="small" variant="borderless" style={{ width: 76 }} value={pageSize}
463
+ options={[20, 50, 100].map((size) => ({ value: size, label: size + "/页" }))}
464
+ onChange={(size) => { setPageSize(size); if (table) void loadTable(activeName, database, table, 1, size); }} />
465
+ <Tooltip title="刷新"><Button size="small" type="text" icon={<ReloadOutlined />} disabled={!table} onClick={() => void loadTable(activeName, database, table, page?.page ?? 1, pageSize)} /></Tooltip>
466
+ <Tooltip title="导出 CSV"><Button size="small" type="text" icon={<DownloadOutlined />} disabled={!page || page.rows.length === 0} onClick={() => page && download(activeName + "-" + page.table + ".csv", csvOf(dataKeys, page.rows))} /></Tooltip>
467
+ </Space>
468
+ </div>
469
+ <Tabs activeKey={mode} onChange={(key) => setMode(key as "data" | "schema" | "sql")} items={tabItems} size="small" />
470
+ </div>
471
+ );
472
+
473
+ return (
474
+ <div className="dbw-app" ref={appRef}>
475
+ <div className="dbw-topbar">
476
+ <div className="dbw-brand">
477
+ <span className="dbw-logo"><DatabaseOutlined /></span>
478
+ <div>
479
+ <span className="dbw-title">数据库工作台</span>
480
+ <span className="dbw-subtitle">
481
+ {active && activeMeta ? (
482
+ <>
483
+ <i className="dbw-dot" style={{ background: activeMeta.color }} />
484
+ {activeMeta.label + " · " + targetOf(active)}
485
+ {state?.ok ? <span className="dbw-ok"> · {state.ms !== undefined ? state.ms + "ms" : "OK"}</span> : null}
486
+ {state && !state.ok ? <span className="dbw-bad"> · 不可用</span> : null}
487
+ </>
488
+ ) : (
489
+ connections.length + " 个连接 · 只读优先"
490
+ )}
491
+ </span>
492
+ </div>
493
+ </div>
494
+ <Space size={2}>
495
+ <Tooltip title="刷新连接"><Button size="small" type="text" icon={<ReloadOutlined />} loading={loading === "connections"} onClick={() => void loadConnections()} /></Tooltip>
496
+ <Dropdown menu={{ items: [
497
+ { key: "version", label: "插件 " + (version ? "v" + version : "版本未知"), disabled: true },
498
+ { type: "divider" as const },
499
+ { key: "import", label: "导入连接", icon: <DownloadOutlined />, onClick: () => fileRef.current?.click() },
500
+ { key: "export", label: "导出连接", icon: <DownloadOutlined />, onClick: () => void exportConnections() },
501
+ ] }}>
502
+ <Button size="small" type="text" icon={<MoreOutlined />} />
503
+ </Dropdown>
504
+ <Button size="small" type="primary" icon={<PlusOutlined />} onClick={openCreate}>新建</Button>
505
+ </Space>
506
+ </div>
507
+ <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
+ />
514
+ {active ? (
515
+ <>
516
+ <Tooltip title="测试连接"><Button size="small" type="text" icon={<ThunderboltOutlined />} onClick={() => void testConnection(active)} /></Tooltip>
517
+ <Tooltip title="编辑连接"><Button size="small" type="text" icon={<EditOutlined />} onClick={() => openEdit(active)} /></Tooltip>
518
+ <Popconfirm title={"删除 " + active.name + "?"} onConfirm={() => void removeConnection(active)} okText="删除" cancelText="取消">
519
+ <Button size="small" type="text" danger icon={<DeleteOutlined />} />
520
+ </Popconfirm>
521
+ </>
522
+ ) : null}
523
+ </div>
524
+
525
+ <input ref={fileRef} type="file" accept="application/json,.json" hidden onChange={(event) => { const file = event.target.files?.[0]; if (file) void importConnections(file); event.target.value = ""; }} />
526
+
527
+ {active ? (
528
+ narrow ? (
529
+ <div className="dbw-workarea">
530
+ {mainPane}
531
+ <Drawer open={drawerOpen} onClose={() => setDrawerOpen(false)} placement="left" width={280} title="对象" styles={{ body: { padding: 0 } }}>
532
+ <div className="dbw-tree dbw-tree-drawer">{treeContent}</div>
533
+ </Drawer>
534
+ </div>
535
+ ) : treeOpen ? (
536
+ <Splitter className="dbw-splitter">
537
+ <Splitter.Panel defaultSize="32%" min="20%" max="55%">
538
+ <div className="dbw-tree">{treeContent}</div>
539
+ </Splitter.Panel>
540
+ <Splitter.Panel min="20%">{mainPane}</Splitter.Panel>
541
+ </Splitter>
542
+ ) : (
543
+ <div className="dbw-workarea">{mainPane}</div>
544
+ )
545
+ ) : (
546
+ <div className="dbw-empty-wrap">
547
+ <Card size="small" className="dbw-card" styles={{ body: { padding: 8 } }}>
548
+ <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择或新建一个连接">
549
+ <Button size="small" type="primary" icon={<PlusOutlined />} onClick={openCreate}>新建连接</Button>
550
+ </Empty>
551
+ </Card>
552
+ </div>
553
+ )}
554
+
555
+
556
+ <div className="dbw-footer">
557
+ <span>{active ? ENGINE[active.engine].label : "未连接"}</span>
558
+ <span>{active ? active.name : ""}</span>
559
+ <span className="dbw-footer-grow" />
560
+ <span>{page ? page.rows.length + " 行 / 页" : ""}</span>
561
+ <span>只读</span>
562
+ </div>
563
+ <Modal
564
+ open={formOpen} title={editing ? "编辑 " + editing.name : "新增连接"} okText="保存" cancelText="取消"
565
+ confirmLoading={loading === "save"} onOk={() => void save()} onCancel={() => setFormOpen(false)}
566
+ destroyOnHidden width="min(560px, calc(100vw - 24px))"
567
+ >
568
+ <Form form={form} layout="vertical" preserve={false}>
569
+ <Form.Item name="name" label="连接名称" rules={[{ required: true, message: "请输入连接名称" }]}>
570
+ <Input placeholder="例如:订单生产库" />
571
+ </Form.Item>
572
+ <Form.Item name="engine" label="数据库类型">
573
+ <Radio.Group optionType="button" buttonStyle="solid" size="middle">
574
+ <Radio.Button value="sqlite">SQLite</Radio.Button>
575
+ <Radio.Button value="postgres">PostgreSQL</Radio.Button>
576
+ <Radio.Button value="mysql">MySQL</Radio.Button>
577
+ </Radio.Group>
578
+ </Form.Item>
579
+ {engine === "sqlite" ? (
580
+ <Form.Item name="path" label="数据库文件绝对路径" rules={[{ required: true, message: "请输入数据库文件路径" }]}>
581
+ <Input placeholder="D:\\data\\app.db" />
582
+ </Form.Item>
583
+ ) : (
584
+ <>
585
+ <Form.Item name="mode" label="连接方式">
586
+ <Radio.Group>
587
+ <Radio.Button value="parameters">地址和账号</Radio.Button>
588
+ <Radio.Button value="url-env">DSN 环境变量</Radio.Button>
589
+ </Radio.Group>
590
+ </Form.Item>
591
+ {connectMode === "url-env" ? (
592
+ <Form.Item name="urlEnv" label="完整 DSN 环境变量名" rules={[{ required: true }]}>
593
+ <Input placeholder="DATABASE_URL" />
594
+ </Form.Item>
595
+ ) : (
596
+ <>
597
+ <Flex gap={8}>
598
+ <Form.Item name="host" label="主机地址" rules={[{ required: true }]} style={{ flex: 1 }}>
599
+ <Input placeholder="127.0.0.1" />
600
+ </Form.Item>
601
+ <Form.Item name="port" label="端口" style={{ width: 110 }}>
602
+ <InputNumber min={1} max={65535} placeholder={engine === "postgres" ? "5432" : "3306"} style={{ width: "100%" }} />
603
+ </Form.Item>
604
+ </Flex>
605
+ <Form.Item name="database" label="数据库名"><Input placeholder="留空使用默认库" /></Form.Item>
606
+ <Form.Item name="username" label="用户名" rules={[{ required: true }]}><Input /></Form.Item>
607
+ <Form.Item name="passwordMode" label="密码保存方式">
608
+ <Radio.Group>
609
+ <Radio value="encrypted">本地加密</Radio>
610
+ <Radio value="runtime">本次运行</Radio>
611
+ <Radio value="environment">环境变量</Radio>
612
+ </Radio.Group>
613
+ </Form.Item>
614
+ {passwordMode === "environment" ? (
615
+ <Form.Item name="passwordEnv" label="密码环境变量名" rules={[{ required: true }]}>
616
+ <Input placeholder="DB_PASSWORD" />
617
+ </Form.Item>
618
+ ) : (
619
+ <Form.Item name="password" label={editing ? "密码(留空不修改)" : "密码"} rules={editing ? [] : [{ required: true, message: "请输入密码" }]}>
620
+ <Input.Password placeholder={passwordMode === "runtime" ? "仅保存在当前进程内存" : "AES-256-GCM 加密保存"} />
621
+ </Form.Item>
622
+ )}
623
+ <Form.Item name="ssl" label="启用 SSL/TLS" valuePropName="checked"><Switch size="small" /></Form.Item>
624
+ </>
625
+ )}
626
+ </>
627
+ )}
628
+ </Form>
629
+ </Modal>
630
+ </div>
631
+ );
632
+ }