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
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
import React, { useCallback, useEffect, useRef, useState } from "react";
|
|
2
|
+
import { RiDatabase2Line, RiDownload2Line, RiPlayLine, RiRefreshLine, RiShieldCheckLine, RiUpload2Line } from "./icons.js";
|
|
3
|
+
import { CONFIRMATION_HEADER, confirmationToken } from "./console-shim.js";
|
|
4
|
+
|
|
5
|
+
type DbEngine = "sqlite" | "postgres" | "mysql";
|
|
6
|
+
type ConnectionMode = "parameters" | "url-env";
|
|
7
|
+
type PasswordMode = "runtime" | "environment" | "encrypted";
|
|
8
|
+
type DbConnection = {
|
|
9
|
+
name: string; engine: DbEngine; path?: string; mode?: ConnectionMode; urlEnv?: string;
|
|
10
|
+
host?: string; port?: number; database?: string; username?: string;
|
|
11
|
+
passwordMode?: PasswordMode; passwordRef?: string; passwordEnv?: string; passwordStatus?: "runtime" | "environment" | "encrypted" | "required";
|
|
12
|
+
ssl?: boolean; createdAt: string;
|
|
13
|
+
};
|
|
14
|
+
type HealthState = { status: "checking" | "ok" | "error"; elapsedMs?: number; message?: string };
|
|
15
|
+
type ApiError = { error?: { message?: string } };
|
|
16
|
+
type ConnectionDocument = { schemaVersion: 1; exportedAt: string; connections: DbConnection[] };
|
|
17
|
+
type DbTable = { name: string; type: "table" | "view"; schema?: string };
|
|
18
|
+
type DbColumn = { name: string; type: string; nullable: boolean; primaryKey: boolean };
|
|
19
|
+
type DbTablePage = { connection: string; table: string; columns: DbColumn[]; rows: Array<Record<string, unknown>>; page: number; pageSize: number; hasNext: boolean };
|
|
20
|
+
type DbCatalog = { databases?: string[]; tables?: DbTable[] };
|
|
21
|
+
type DbQueryResult = { connection: string; sql: string; columns: string[]; rows: Array<Record<string, unknown>>; rowCount: number; truncated: boolean };
|
|
22
|
+
type WorkbenchMode = "table" | "sql";
|
|
23
|
+
type SqlSuggestionKind = "keyword" | "table" | "column";
|
|
24
|
+
type SqlSuggestion = { label: string; kind: SqlSuggestionKind; detail: string };
|
|
25
|
+
type SqlToken = { text: string; start: number; end: number };
|
|
26
|
+
|
|
27
|
+
const ENGINE_LABELS: Record<DbEngine, string> = { sqlite: "SQLite", postgres: "PostgreSQL", mysql: "MySQL" };
|
|
28
|
+
const DEFAULT_PORTS = { postgres: 5432, mysql: 3306 } as const;
|
|
29
|
+
const SQL_EDITOR_KEYWORDS = [
|
|
30
|
+
"SELECT", "FROM", "WHERE", "JOIN", "LEFT JOIN", "INNER JOIN", "GROUP BY", "ORDER BY",
|
|
31
|
+
"HAVING", "LIMIT", "OFFSET", "AS", "ON", "AND", "OR", "NOT", "NULL", "IS", "IN",
|
|
32
|
+
"LIKE", "BETWEEN", "DISTINCT", "COUNT(*)", "SUM(", "AVG(", "MIN(", "MAX(", "UNION ALL",
|
|
33
|
+
];
|
|
34
|
+
|
|
35
|
+
function sqlTokenAt(value: string, caret: number): SqlToken {
|
|
36
|
+
let start = caret;
|
|
37
|
+
while (start > 0 && /[A-Za-z0-9_$.*]/.test(value[start - 1] ?? "")) start -= 1;
|
|
38
|
+
let end = caret;
|
|
39
|
+
while (end < value.length && /[A-Za-z0-9_$.*]/.test(value[end] ?? "")) end += 1;
|
|
40
|
+
return { text: value.slice(start, caret), start, end };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function buildSqlSuggestions(token: string, tables: DbTable[], columns: DbColumn[] | undefined): SqlSuggestion[] {
|
|
44
|
+
const query = token.toLowerCase();
|
|
45
|
+
const matches = (value: string) => query === "" || value.toLowerCase().includes(query);
|
|
46
|
+
const tableSuggestions = tables.map((table) => {
|
|
47
|
+
const label = table.schema ? `${table.schema}.${table.name}` : table.name;
|
|
48
|
+
return { label, kind: "table" as const, detail: table.type === "view" ? "视图" : "表" };
|
|
49
|
+
}).filter((item) => matches(item.label));
|
|
50
|
+
const columnSuggestions = (columns ?? []).map((column) => ({
|
|
51
|
+
label: column.name, kind: "column" as const, detail: column.type || "字段",
|
|
52
|
+
})).filter((item) => matches(item.label));
|
|
53
|
+
const keywordSuggestions = SQL_EDITOR_KEYWORDS.map((label) => ({
|
|
54
|
+
label, kind: "keyword" as const, detail: "SQL 关键字",
|
|
55
|
+
})).filter((item) => matches(item.label));
|
|
56
|
+
return [...tableSuggestions, ...columnSuggestions, ...keywordSuggestions].slice(0, 12);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function DatabaseConnectionsPage(props: { workspaceId: string | null }): React.JSX.Element {
|
|
60
|
+
const [connections, setConnections] = useState<DbConnection[]>([]);
|
|
61
|
+
const [loading, setLoading] = useState(false);
|
|
62
|
+
const [busyName, setBusyName] = useState<string | null>(null);
|
|
63
|
+
const [error, setError] = useState<string | null>(null);
|
|
64
|
+
const [notice, setNotice] = useState<string | null>(null);
|
|
65
|
+
const [name, setName] = useState("");
|
|
66
|
+
const [engine, setEngine] = useState<DbEngine>("sqlite");
|
|
67
|
+
const [path, setPath] = useState("");
|
|
68
|
+
const [mode, setMode] = useState<ConnectionMode>("parameters");
|
|
69
|
+
const [urlEnv, setUrlEnv] = useState("");
|
|
70
|
+
const [host, setHost] = useState("");
|
|
71
|
+
const [port, setPort] = useState("");
|
|
72
|
+
const [database, setDatabase] = useState("");
|
|
73
|
+
const [username, setUsername] = useState("");
|
|
74
|
+
const [passwordMode, setPasswordMode] = useState<PasswordMode>("encrypted");
|
|
75
|
+
const [password, setPassword] = useState("");
|
|
76
|
+
const [passwordEnv, setPasswordEnv] = useState("");
|
|
77
|
+
const [ssl, setSsl] = useState(false);
|
|
78
|
+
const [editingName, setEditingName] = useState<string | null>(null);
|
|
79
|
+
const [formOpen, setFormOpen] = useState(false);
|
|
80
|
+
const [editingPasswordRequired, setEditingPasswordRequired] = useState(false);
|
|
81
|
+
const [importConflict, setImportConflict] = useState<"skip" | "overwrite">("skip");
|
|
82
|
+
const [health, setHealth] = useState<Record<string, HealthState>>({});
|
|
83
|
+
const importInputRef = useRef<HTMLInputElement>(null);
|
|
84
|
+
const [browserConnection, setBrowserConnection] = useState<string | null>(null);
|
|
85
|
+
const [browserTables, setBrowserTables] = useState<DbTable[]>([]);
|
|
86
|
+
const [browserDatabases, setBrowserDatabases] = useState<string[]>([]);
|
|
87
|
+
const [browserDatabase, setBrowserDatabase] = useState("");
|
|
88
|
+
const [browserTable, setBrowserTable] = useState("");
|
|
89
|
+
const [browserPage, setBrowserPage] = useState<DbTablePage | null>(null);
|
|
90
|
+
const [browserPageSize, setBrowserPageSize] = useState(50);
|
|
91
|
+
const [browserLoading, setBrowserLoading] = useState(false);
|
|
92
|
+
const [browserError, setBrowserError] = useState<string | null>(null);
|
|
93
|
+
const [schemaOpen, setSchemaOpen] = useState(false);
|
|
94
|
+
const [sqlText, setSqlText] = useState("");
|
|
95
|
+
const [sqlSuggestions, setSqlSuggestions] = useState<SqlSuggestion[]>([]);
|
|
96
|
+
const [sqlSuggestionOpen, setSqlSuggestionOpen] = useState(false);
|
|
97
|
+
const [sqlSuggestionIndex, setSqlSuggestionIndex] = useState(0);
|
|
98
|
+
const [sqlEditorId] = useState(() => `database-sql-editor-${Math.random().toString(36).slice(2, 9)}`);
|
|
99
|
+
const sqlInputRef = useRef<HTMLTextAreaElement>(null);
|
|
100
|
+
const [sqlFocusedTable, setSqlFocusedTable] = useState("");
|
|
101
|
+
const [queryRunning, setQueryRunning] = useState(false);
|
|
102
|
+
const [queryError, setQueryError] = useState<string | null>(null);
|
|
103
|
+
const [queryResult, setQueryResult] = useState<DbQueryResult | null>(null);
|
|
104
|
+
const [workbenchMode, setWorkbenchMode] = useState<WorkbenchMode>("table");
|
|
105
|
+
|
|
106
|
+
const endpoint = useCallback((suffix = "") => {
|
|
107
|
+
// DSH 侧路由:/zero-db-tool/api/{connections|export|import}
|
|
108
|
+
if (suffix === "/export") return "/zero-db-tool/api/export";
|
|
109
|
+
if (suffix === "/import") return "/zero-db-tool/api/import";
|
|
110
|
+
return "/zero-db-tool/api/connections" + suffix;
|
|
111
|
+
}, []);
|
|
112
|
+
|
|
113
|
+
const load = useCallback(async () => {
|
|
114
|
+
if (!props.workspaceId) return;
|
|
115
|
+
setLoading(true); setError(null);
|
|
116
|
+
try {
|
|
117
|
+
const response = await fetch(endpoint(), { credentials: "same-origin" });
|
|
118
|
+
const body = await response.json() as ApiError & { connections?: DbConnection[] };
|
|
119
|
+
if (!response.ok) throw new Error(body.error?.message ?? "加载数据库连接失败");
|
|
120
|
+
setConnections(body.connections ?? []);
|
|
121
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
122
|
+
finally { setLoading(false); }
|
|
123
|
+
}, [endpoint, props.workspaceId]);
|
|
124
|
+
useEffect(() => { void load(); }, [load]);
|
|
125
|
+
|
|
126
|
+
async function request(suffix: string, method: "POST" | "PATCH" | "DELETE", body?: object) {
|
|
127
|
+
const response = await fetch(endpoint(suffix), {
|
|
128
|
+
method, credentials: "same-origin",
|
|
129
|
+
headers: { [CONFIRMATION_HEADER]: confirmationToken(), ...(body ? { "Content-Type": "application/json" } : {}) },
|
|
130
|
+
...(body ? { body: JSON.stringify(body) } : {}),
|
|
131
|
+
});
|
|
132
|
+
const payload = await response.json() as ApiError & Record<string, unknown>;
|
|
133
|
+
if (!response.ok) throw new Error(payload.error?.message ?? "数据库连接操作失败");
|
|
134
|
+
return payload;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function resetForm() {
|
|
138
|
+
setName(""); setEngine("sqlite"); setPath(""); setMode("parameters"); setUrlEnv("");
|
|
139
|
+
setHost(""); setPort(""); setDatabase(""); setUsername(""); setPasswordMode("encrypted");
|
|
140
|
+
setPassword(""); setPasswordEnv(""); setSsl(false); setEditingName(null); setEditingPasswordRequired(false);
|
|
141
|
+
}
|
|
142
|
+
function beginEdit(connection: DbConnection) {
|
|
143
|
+
setEditingName(connection.name); setName(connection.name); setEngine(connection.engine); setPath(connection.path ?? "");
|
|
144
|
+
setMode(connection.mode ?? (connection.urlEnv ? "url-env" : "parameters")); setUrlEnv(connection.urlEnv ?? "");
|
|
145
|
+
setHost(connection.host ?? ""); setPort(connection.port?.toString() ?? ""); setDatabase(connection.database ?? "");
|
|
146
|
+
setUsername(connection.username ?? ""); setPasswordMode(connection.passwordMode ?? "runtime");
|
|
147
|
+
setPassword(""); setPasswordEnv(connection.passwordEnv ?? ""); setSsl(connection.ssl === true);
|
|
148
|
+
setEditingPasswordRequired(connection.mode === "parameters" && connection.passwordMode !== "environment" && connection.passwordMode !== "encrypted" && connection.passwordStatus !== "runtime");
|
|
149
|
+
setError(null); setNotice(null); setFormOpen(true);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
async function saveConnection(event: React.FormEvent) {
|
|
153
|
+
event.preventDefault(); setBusyName("__save__"); setError(null); setNotice(null);
|
|
154
|
+
try {
|
|
155
|
+
const body = engine === "sqlite" ? { name, engine, path } : mode === "url-env"
|
|
156
|
+
? { name, engine, mode, urlEnv }
|
|
157
|
+
: { name, engine, mode, host, ...(port.trim() ? { port: Number(port) } : {}), database, username,
|
|
158
|
+
passwordMode, ...(passwordMode === "runtime" || passwordMode === "encrypted" ? (password !== "" ? { password } : {}) : { passwordEnv }), ssl };
|
|
159
|
+
if (editingName) await request(`/${encodeURIComponent(editingName)}`, "PATCH", body);
|
|
160
|
+
else await request("", "POST", body);
|
|
161
|
+
setNotice(editingName ? `已保存连接 ${name.trim()}。` : `已添加连接 ${name.trim()}。`);
|
|
162
|
+
resetForm(); setFormOpen(false); await load();
|
|
163
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
164
|
+
finally { setBusyName(null); }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function testConnection(connection: DbConnection) {
|
|
168
|
+
setBusyName(connection.name); setError(null);
|
|
169
|
+
setHealth((current) => ({ ...current, [connection.name]: { status: "checking" } }));
|
|
170
|
+
try {
|
|
171
|
+
const payload = await request(`/${encodeURIComponent(connection.name)}/test`, "POST");
|
|
172
|
+
const result = payload.result as { elapsedMs?: number } | undefined;
|
|
173
|
+
setHealth((current) => ({ ...current, [connection.name]: { status: "ok", elapsedMs: result?.elapsedMs } }));
|
|
174
|
+
} catch (cause) {
|
|
175
|
+
setHealth((current) => ({ ...current, [connection.name]: { status: "error", message: cause instanceof Error ? cause.message : String(cause) } }));
|
|
176
|
+
} finally { setBusyName(null); }
|
|
177
|
+
}
|
|
178
|
+
async function testAll() {
|
|
179
|
+
setBusyName("__all__"); setError(null); setNotice(null);
|
|
180
|
+
setHealth((current) => { const next = { ...current }; for (const item of connections) next[item.name] = { status: "checking" }; return next; });
|
|
181
|
+
let cursor = 0; let passed = 0;
|
|
182
|
+
async function worker() {
|
|
183
|
+
while (cursor < connections.length) {
|
|
184
|
+
const connection = connections[cursor++]; if (!connection) return;
|
|
185
|
+
try {
|
|
186
|
+
const payload = await request(`/${encodeURIComponent(connection.name)}/test`, "POST");
|
|
187
|
+
const result = payload.result as { elapsedMs?: number } | undefined;
|
|
188
|
+
setHealth((current) => ({ ...current, [connection.name]: { status: "ok", elapsedMs: result?.elapsedMs } })); passed += 1;
|
|
189
|
+
} catch (cause) { setHealth((current) => ({ ...current, [connection.name]: { status: "error", message: cause instanceof Error ? cause.message : String(cause) } })); }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
await Promise.all(Array.from({ length: Math.min(4, connections.length) }, () => worker()));
|
|
193
|
+
setNotice(`连接检查完成:${passed}/${connections.length} 可用。`); setBusyName(null);
|
|
194
|
+
}
|
|
195
|
+
async function removeConnection(connection: DbConnection) {
|
|
196
|
+
if (!window.confirm(`确定删除数据库连接“${connection.name}”吗?`)) return;
|
|
197
|
+
setBusyName(connection.name); setError(null); setNotice(null);
|
|
198
|
+
try {
|
|
199
|
+
await request(`/${encodeURIComponent(connection.name)}`, "DELETE"); setNotice(`已删除连接 ${connection.name}。`);
|
|
200
|
+
setHealth((current) => { const next = { ...current }; delete next[connection.name]; return next; });
|
|
201
|
+
if (editingName === connection.name) resetForm(); await load();
|
|
202
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
203
|
+
finally { setBusyName(null); }
|
|
204
|
+
}
|
|
205
|
+
async function exportConnections() {
|
|
206
|
+
setError(null);
|
|
207
|
+
try {
|
|
208
|
+
const response = await fetch(endpoint("/export"), { credentials: "same-origin" });
|
|
209
|
+
const payload = await response.json() as ApiError & { document?: ConnectionDocument };
|
|
210
|
+
if (!response.ok || !payload.document) throw new Error(payload.error?.message ?? "导出失败");
|
|
211
|
+
const blob = new Blob([JSON.stringify(payload.document, null, 2) + "\n"], { type: "application/json" });
|
|
212
|
+
const url = URL.createObjectURL(blob); const anchor = document.createElement("a"); anchor.href = url;
|
|
213
|
+
anchor.download = `zero-db-tool-connections-${new Date().toISOString().slice(0, 10)}.json`; anchor.click(); URL.revokeObjectURL(url);
|
|
214
|
+
setNotice(`已导出 ${payload.document.connections.length} 个连接;密码不会导出。`);
|
|
215
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : String(cause)); }
|
|
216
|
+
}
|
|
217
|
+
async function importConnections(file: File) {
|
|
218
|
+
setBusyName("__import__"); setError(null); setNotice(null);
|
|
219
|
+
try {
|
|
220
|
+
const document = JSON.parse(await file.text()) as unknown;
|
|
221
|
+
const payload = await request("/import", "POST", { document, conflict: importConflict });
|
|
222
|
+
const result = payload.result as { imported: number; updated: number; skipped: number };
|
|
223
|
+
setNotice(`导入完成:新增 ${result.imported},更新 ${result.updated},跳过 ${result.skipped}。运行时密码需重新填写。`); await load();
|
|
224
|
+
} catch (cause) { setError(cause instanceof Error ? cause.message : "导入文件不是有效 JSON"); }
|
|
225
|
+
finally { setBusyName(null); if (importInputRef.current) importInputRef.current.value = ""; }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
async function loadTablePage(connectionName: string, table: string, page: number, pageSize = browserPageSize, database = browserDatabase) {
|
|
230
|
+
setBrowserLoading(true); setBrowserError(null); setSchemaOpen(false);
|
|
231
|
+
try {
|
|
232
|
+
const base = endpoint(`/${encodeURIComponent(connectionName)}/browse`);
|
|
233
|
+
const url = base + (base.includes("?") ? "&" : "?") + `table=${encodeURIComponent(table)}&page=${page}&pageSize=${pageSize}${database ? `&database=${encodeURIComponent(database)}` : ""}`;
|
|
234
|
+
const response = await fetch(url, { credentials: "same-origin" });
|
|
235
|
+
const payload = await response.json() as ApiError & { result?: DbTablePage };
|
|
236
|
+
if (!response.ok || !payload.result) throw new Error(payload.error?.message ?? "加载表数据失败");
|
|
237
|
+
setBrowserTable(table); setBrowserPage(payload.result);
|
|
238
|
+
} catch (cause) { setBrowserError(cause instanceof Error ? cause.message : String(cause)); }
|
|
239
|
+
finally { setBrowserLoading(false); }
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
async function browseConnection(connection: DbConnection, forceRefresh = false, database = browserDatabase, keepWorkbenchMode = false) {
|
|
243
|
+
if (!forceRefresh && browserConnection === connection.name) { setBrowserConnection(null); return; }
|
|
244
|
+
const opening = browserConnection !== connection.name;
|
|
245
|
+
const effectiveDatabase = opening ? (connection.database ?? "") : database;
|
|
246
|
+
setBrowserConnection(connection.name); setBrowserTables([]); setBrowserTable(""); setBrowserPage(null);
|
|
247
|
+
setQueryResult(null); setQueryError(null); setSqlFocusedTable(""); setWorkbenchMode(keepWorkbenchMode ? workbenchMode : "table");
|
|
248
|
+
if (opening) { setBrowserDatabases(connection.database ? [connection.database] : []); setBrowserDatabase(effectiveDatabase); }
|
|
249
|
+
else { setBrowserDatabase(effectiveDatabase); }
|
|
250
|
+
setBrowserLoading(true); setBrowserError(null); setSchemaOpen(false);
|
|
251
|
+
try {
|
|
252
|
+
const catalogBase = endpoint(`/${encodeURIComponent(connection.name)}/browse`);
|
|
253
|
+
const catalogUrl = catalogBase + (effectiveDatabase ? (catalogBase.includes("?") ? "&" : "?") + `database=${encodeURIComponent(effectiveDatabase)}` : "");
|
|
254
|
+
const response = await fetch(catalogUrl, { credentials: "same-origin" });
|
|
255
|
+
const payload = await response.json() as ApiError & DbCatalog;
|
|
256
|
+
if (!response.ok) throw new Error(payload.error?.message ?? "加载数据表失败");
|
|
257
|
+
const databases = Array.from(new Set([...(payload.databases ?? []), ...(connection.database ? [connection.database] : [])]));
|
|
258
|
+
setBrowserDatabases(databases);
|
|
259
|
+
if (!effectiveDatabase && databases.length === 1) { setBrowserDatabase(databases[0]!); }
|
|
260
|
+
|
|
261
|
+
const tables = payload.tables ?? []; setBrowserTables(tables);
|
|
262
|
+
if (tables[0]) await loadTablePage(connection.name, tables[0].schema ? `${tables[0].schema}.${tables[0].name}` : tables[0].name, 1, browserPageSize, effectiveDatabase);
|
|
263
|
+
} catch (cause) { setBrowserError(cause instanceof Error ? cause.message : String(cause)); }
|
|
264
|
+
finally { setBrowserLoading(false); }
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
function cellText(value: unknown): string {
|
|
268
|
+
if (value === null) return "NULL";
|
|
269
|
+
if (value === undefined) return "";
|
|
270
|
+
if (typeof value === "object") return JSON.stringify(value);
|
|
271
|
+
return String(value);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function refreshSqlSuggestions(value: string, caret: number) {
|
|
275
|
+
const token = sqlTokenAt(value, caret);
|
|
276
|
+
setSqlSuggestions(buildSqlSuggestions(token.text, browserTables, browserPage?.columns));
|
|
277
|
+
setSqlSuggestionIndex(0);
|
|
278
|
+
setSqlSuggestionOpen(token.text.length > 0);
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
function applySqlSuggestion(suggestion: SqlSuggestion) {
|
|
282
|
+
const input = sqlInputRef.current;
|
|
283
|
+
if (!input) return;
|
|
284
|
+
const token = sqlTokenAt(input.value, input.selectionStart ?? input.value.length);
|
|
285
|
+
const nextValue = input.value.slice(0, token.start) + suggestion.label + input.value.slice(token.end);
|
|
286
|
+
const nextCaret = token.start + suggestion.label.length;
|
|
287
|
+
setSqlText(nextValue);
|
|
288
|
+
setSqlSuggestionIndex(0);
|
|
289
|
+
setSqlSuggestions((current) => buildSqlSuggestions(suggestion.label, browserTables, browserPage?.columns));
|
|
290
|
+
setSqlSuggestionOpen(false);
|
|
291
|
+
requestAnimationFrame(() => {
|
|
292
|
+
input.focus();
|
|
293
|
+
input.setSelectionRange(nextCaret, nextCaret);
|
|
294
|
+
});
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function insertTableSelect(table: DbTable, qualifiedName = table.schema ? `${table.schema}.${table.name}` : table.name) {
|
|
298
|
+
const nextSql = `SELECT *\nFROM ${qualifiedName}\nLIMIT 50;\n`;
|
|
299
|
+
setSqlText(nextSql);
|
|
300
|
+
setSqlFocusedTable(qualifiedName);
|
|
301
|
+
setSqlSuggestionOpen(false);
|
|
302
|
+
setWorkbenchMode("sql");
|
|
303
|
+
requestAnimationFrame(() => {
|
|
304
|
+
const input = sqlInputRef.current;
|
|
305
|
+
input?.focus();
|
|
306
|
+
input?.setSelectionRange(nextSql.length, nextSql.length);
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
async function runSqlQuery(connectionName: string) {
|
|
311
|
+
setQueryRunning(true); setQueryError(null);
|
|
312
|
+
try {
|
|
313
|
+
const response = await fetch(endpoint(`/${encodeURIComponent(connectionName)}/query`), {
|
|
314
|
+
method: "POST", credentials: "same-origin",
|
|
315
|
+
headers: { [CONFIRMATION_HEADER]: confirmationToken(), "Content-Type": "application/json" },
|
|
316
|
+
body: JSON.stringify({ sql: sqlText, database: browserDatabase || undefined, maxRows: 500 }),
|
|
317
|
+
});
|
|
318
|
+
const payload = await response.json() as ApiError & { result?: DbQueryResult };
|
|
319
|
+
if (!response.ok || !payload.result) throw new Error(payload.error?.message ?? "SQL 查询失败");
|
|
320
|
+
setQueryResult(payload.result);
|
|
321
|
+
} catch (cause) { setQueryError(cause instanceof Error ? cause.message : String(cause)); }
|
|
322
|
+
finally { setQueryRunning(false); }
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
function renderDataBrowser(connection: DbConnection): React.JSX.Element | null {
|
|
327
|
+
if (browserConnection !== connection.name) return null;
|
|
328
|
+
const displayColumns = browserPage?.columns.length ? browserPage.columns.map((column) => column.name)
|
|
329
|
+
: browserPage?.rows[0] ? Object.keys(browserPage.rows[0]) : [];
|
|
330
|
+
return <section className="database-data-browser" aria-label={`浏览 ${connection.name} 数据`}>
|
|
331
|
+
<div className="database-workbench-toolbar">
|
|
332
|
+
<div className="database-mode-switch" role="tablist" aria-label="数据访问模式">
|
|
333
|
+
<button type="button" role="tab" aria-selected={workbenchMode === "table"} className={workbenchMode === "table" ? "is-active" : ""} onClick={() => setWorkbenchMode("table")}>表数据</button>
|
|
334
|
+
<button type="button" role="tab" aria-selected={workbenchMode === "sql"} className={workbenchMode === "sql" ? "is-active" : ""} onClick={() => setWorkbenchMode("sql")}>SQL 查询</button>
|
|
335
|
+
</div>
|
|
336
|
+
{connection.engine !== "sqlite" ? <label className="database-browser-database">数据库<select value={browserDatabase} disabled={browserLoading} onChange={(event) => { setBrowserDatabase(event.target.value); setBrowserTable(""); setBrowserPage(null); void browseConnection(connection, true, event.target.value, true); }}><option value="">请选择数据库</option>{browserDatabases.map((database) => <option key={database} value={database}>{database}</option>)}</select></label> : null}
|
|
337
|
+
{workbenchMode === "sql" ? <label className="database-browser-table database-sql-table-select">表和视图<select aria-label="选择 SQL 表或视图" value={sqlFocusedTable} disabled={browserLoading || browserTables.length === 0} onChange={(event) => { const value = event.target.value; const table = browserTables.find((item) => (item.schema ? `${item.schema}.${item.name}` : item.name) === value); if (table) insertTableSelect(table, value); }}><option value="">选择表或视图</option>{browserTables.map((table) => { const value = table.schema ? `${table.schema}.${table.name}` : table.name; return <option key={value} value={value}>{value} · {table.type === "view" ? "视图" : "表"}</option>; })}</select></label> : null}
|
|
338
|
+
{workbenchMode === "table" ? <>
|
|
339
|
+
<label className="database-browser-table">表<select value={browserTable} disabled={browserLoading || browserTables.length === 0} onChange={(event) => void loadTablePage(connection.name, event.target.value, 1)}>
|
|
340
|
+
{browserTables.map((table) => { const value = table.schema ? `${table.schema}.${table.name}` : table.name; return <option key={value} value={value}>{value}{table.type === "view" ? "(视图)" : ""}</option>; })}
|
|
341
|
+
</select></label>
|
|
342
|
+
<label className="database-browser-page-size">每页<select value={browserPageSize} onChange={(event) => { const size = Number(event.target.value); setBrowserPageSize(size); if (browserTable) void loadTablePage(connection.name, browserTable, 1, size); }}><option value="20">20</option><option value="50">50</option><option value="100">100</option></select></label>
|
|
343
|
+
</> : null}
|
|
344
|
+
{workbenchMode === "table" ? <>
|
|
345
|
+
<button type="button" className="btn btn-secondary" disabled={!browserPage} onClick={() => setSchemaOpen(true)}>查看字段</button>
|
|
346
|
+
<button type="button" className="btn btn-secondary" disabled={browserLoading} onClick={() => browserTable ? void loadTablePage(connection.name, browserTable, browserPage?.page ?? 1) : void browseConnection(connection, true)}>刷新</button>
|
|
347
|
+
</> : null}
|
|
348
|
+
</div>
|
|
349
|
+
{workbenchMode === "sql" ? <div className="database-sql-workbench">
|
|
350
|
+
<section className="database-query-panel" aria-label="SQL 查询">
|
|
351
|
+
<header className="database-query-panel-head">
|
|
352
|
+
<div><strong>SQL 查询</strong><span>{connection.engine === "sqlite" ? "SQLite" : browserDatabase || connection.database || "未选择数据库"}</span></div>
|
|
353
|
+
<div className="database-query-panel-actions">
|
|
354
|
+
<button type="button" className="btn btn-secondary" disabled={!browserPage} onClick={() => setSchemaOpen(true)}>字段</button>
|
|
355
|
+
<button type="button" className="btn btn-primary database-query-run" disabled={queryRunning || sqlText.trim() === ""} onClick={() => void runSqlQuery(connection.name)}><RiPlayLine size={14} aria-hidden="true" />{queryRunning ? "查询中…" : "执行查询"}</button>
|
|
356
|
+
</div>
|
|
357
|
+
</header>
|
|
358
|
+
<label className="database-sql-editor">
|
|
359
|
+
<textarea ref={sqlInputRef} id={sqlEditorId} value={sqlText} spellCheck={false} placeholder={"SELECT *\nFROM table_name\nLIMIT 50"} onChange={(event) => { setSqlText(event.target.value); refreshSqlSuggestions(event.target.value, event.target.selectionStart); }} onSelect={(event) => refreshSqlSuggestions(event.currentTarget.value, event.currentTarget.selectionStart)} onFocus={(event) => refreshSqlSuggestions(event.currentTarget.value, event.currentTarget.selectionStart)} onBlur={() => window.setTimeout(() => setSqlSuggestionOpen(false), 120)} onKeyDown={(event) => {
|
|
360
|
+
if (sqlSuggestionOpen && sqlSuggestions.length > 0) {
|
|
361
|
+
if (event.key === "ArrowDown") { event.preventDefault(); setSqlSuggestionIndex((index) => (index + 1) % sqlSuggestions.length); return; }
|
|
362
|
+
if (event.key === "ArrowUp") { event.preventDefault(); setSqlSuggestionIndex((index) => (index - 1 + sqlSuggestions.length) % sqlSuggestions.length); return; }
|
|
363
|
+
if (event.key === "Enter" || event.key === "Tab") { event.preventDefault(); const suggestion = sqlSuggestions[sqlSuggestionIndex]; if (suggestion) applySqlSuggestion(suggestion); return; }
|
|
364
|
+
if (event.key === "Escape") { event.preventDefault(); setSqlSuggestionOpen(false); return; }
|
|
365
|
+
}
|
|
366
|
+
if ((event.ctrlKey || event.metaKey) && event.key === "Enter") void runSqlQuery(connection.name);
|
|
367
|
+
}} />
|
|
368
|
+
{sqlSuggestionOpen && sqlSuggestions.length > 0 ? <div className="database-suggestion-list" role="listbox" aria-label="SQL 输入提示">
|
|
369
|
+
{sqlSuggestions.map((suggestion, index) => <button type="button" key={`${suggestion.kind}:${suggestion.label}`} role="option" aria-selected={index === sqlSuggestionIndex} className={index === sqlSuggestionIndex ? "is-active" : ""} onMouseDown={(event) => event.preventDefault()} onClick={() => applySqlSuggestion(suggestion)}>
|
|
370
|
+
<span className="database-suggestion-label">{suggestion.label}</span>
|
|
371
|
+
<span className={`database-suggestion-kind is-${suggestion.kind}`}>{suggestion.kind === "keyword" ? "关键字" : suggestion.kind === "table" ? "表" : "字段"}</span>
|
|
372
|
+
<span className="database-suggestion-detail">{suggestion.detail}</span>
|
|
373
|
+
</button>)}
|
|
374
|
+
</div> : null}
|
|
375
|
+
</label>
|
|
376
|
+
<div className="database-query-meta">
|
|
377
|
+
<span>只读单条语句</span>
|
|
378
|
+
<span>最多 500 行</span>
|
|
379
|
+
<span>Ctrl + Enter</span>
|
|
380
|
+
</div>
|
|
381
|
+
{browserError ? <p className="database-health is-error">{browserError}</p> : null}
|
|
382
|
+
{queryError ? <p className="database-health is-error">{queryError}</p> : null}
|
|
383
|
+
{queryResult ? <div className="database-query-result">
|
|
384
|
+
<div className="database-query-summary">
|
|
385
|
+
<span>{queryResult.rowCount} 行{queryResult.truncated ? "(已截断)" : ""}</span>
|
|
386
|
+
<button type="button" className="btn btn-secondary" onClick={() => { setQueryResult(null); setQueryError(null); }}>清空结果</button>
|
|
387
|
+
</div>
|
|
388
|
+
{queryResult.rows.length === 0 ? <p className="database-connections-empty">查询执行成功,没有返回数据。</p> :
|
|
389
|
+
<div className="database-data-table-wrap"><table className="database-data-table"><thead><tr>{(queryResult.columns.length ? queryResult.columns : Object.keys(queryResult.rows[0] ?? {})).map((column) => <th key={column}>{column || "(空)"}</th>)}</tr></thead><tbody>
|
|
390
|
+
{queryResult.rows.map((row, index) => <tr key={index}>{(queryResult.columns.length ? queryResult.columns : Object.keys(queryResult.rows[0] ?? {})).map((column) => <td key={column} title={cellText(row[column])}>{cellText(row[column])}</td>)}</tr>)}
|
|
391
|
+
</tbody></table></div>}
|
|
392
|
+
</div> : null}
|
|
393
|
+
</section>
|
|
394
|
+
</div> : browserError ? <p className="database-health is-error">{browserError}</p> : browserLoading && !browserPage ? <p className="muted">正在读取数据库结构和数据…</p> : connection.engine !== "sqlite" && !browserDatabase && !connection.database ? <p className="database-connections-empty">请先从上方选择一个数据库,再选择数据表。</p> : browserTables.length === 0 ? <p className="database-connections-empty">当前数据库中没有可浏览的表或视图。</p> : browserPage ? <>
|
|
395
|
+
<div className="database-data-table-wrap"><table className="database-data-table"><thead><tr>{displayColumns.map((column) => <th key={column}>{column}</th>)}</tr></thead><tbody>
|
|
396
|
+
{browserPage.rows.length === 0 ? <tr><td colSpan={Math.max(displayColumns.length, 1)}>该表当前没有数据。</td></tr> : browserPage.rows.map((row, index) => <tr key={index}>{displayColumns.map((column) => <td key={column} title={cellText(row[column])}>{cellText(row[column])}</td>)}</tr>)}
|
|
397
|
+
</tbody></table></div>
|
|
398
|
+
<div className="database-browser-pagination"><span>第 {browserPage.page} 页 · 本页 {browserPage.rows.length} 行</span><div><button type="button" className="btn btn-secondary" disabled={browserLoading || browserPage.page <= 1} onClick={() => void loadTablePage(connection.name, browserPage.table, browserPage.page - 1)}>上一页</button><button type="button" className="btn btn-secondary" disabled={browserLoading || !browserPage.hasNext} onClick={() => void loadTablePage(connection.name, browserPage.table, browserPage.page + 1)}>下一页</button></div></div>
|
|
399
|
+
</> : null}
|
|
400
|
+
{schemaOpen && browserPage ? <div className="database-modal-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) setSchemaOpen(false); }}><div className="database-schema-modal" role="dialog" aria-modal="true" aria-labelledby="database-schema-title"><div className="database-schema-heading"><div><h3 id="database-schema-title">字段结构</h3><p><code>{browserPage.table}</code> · {browserPage.columns.length} 个字段</p></div><button type="button" className="btn btn-secondary" onClick={() => setSchemaOpen(false)}>关闭</button></div><div className="database-schema-table-wrap"><table className="database-schema-table"><thead><tr><th>字段</th><th>类型</th><th>约束</th></tr></thead><tbody>{browserPage.columns.map((column) => <tr key={column.name}><td><code>{column.name}</code></td><td>{column.type || "未知类型"}</td><td>{[column.primaryKey ? "主键" : "", column.nullable ? "可空" : "非空"].filter(Boolean).join(" · ")}</td></tr>)}</tbody></table></div></div></div> : null}
|
|
401
|
+
</section>;
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
const defaultPort = engine === "postgres" ? DEFAULT_PORTS.postgres : DEFAULT_PORTS.mysql;
|
|
405
|
+
const activeConnection = browserConnection ? connections.find((connection) => connection.name === browserConnection) : undefined;
|
|
406
|
+
return <section className="panel database-connections-page" aria-labelledby="database-connections-title">
|
|
407
|
+
<div className="database-connections-header"><div><h2 id="database-connections-title">数据库工作台</h2><p className="panel-lead">安全连接数据库,浏览结构、数据并执行只读 SQL</p></div><div className="database-header-actions"><input ref={importInputRef} hidden type="file" accept="application/json,.json" onChange={(event) => { const file = event.target.files?.[0]; if (file) void importConnections(file); }} /><select value={importConflict} onChange={(event) => setImportConflict(event.target.value as "skip" | "overwrite")} aria-label="导入同名连接策略"><option value="skip">跳过同名</option><option value="overwrite">覆盖同名</option></select><button type="button" className="btn btn-secondary" onClick={() => importInputRef.current?.click()} disabled={busyName !== null}><RiUpload2Line size={15} aria-hidden="true" />导入</button><button type="button" className="btn btn-secondary" onClick={() => void exportConnections()} disabled={connections.length === 0}><RiDownload2Line size={15} aria-hidden="true" />导出</button><button type="button" className="btn btn-secondary" onClick={() => void load()} disabled={loading}><RiRefreshLine size={15} aria-hidden="true" />{loading ? "刷新中…" : "刷新"}</button><button type="button" className="btn btn-secondary" onClick={() => void testAll()} disabled={connections.length === 0 || busyName === "__all__"}><RiShieldCheckLine size={15} aria-hidden="true" />{busyName === "__all__" ? "检查中…" : "全部测试"}</button><button type="button" className="btn btn-primary" onClick={() => { resetForm(); setFormOpen(true); }}><RiDatabase2Line size={15} aria-hidden="true" />新增连接</button></div></div>
|
|
408
|
+
{error ? <p className="error" role="alert">{error}</p> : null}{notice ? <p className="database-connections-notice" role="status">{notice}</p> : null}
|
|
409
|
+
{formOpen ? <div className="database-modal-backdrop" role="presentation" onMouseDown={(event) => { if (event.target === event.currentTarget) { resetForm(); setFormOpen(false); } }}><div className="database-modal" role="dialog" aria-modal="true" aria-labelledby="database-connection-editor-title"><form className="database-connection-form" onSubmit={(event) => void saveConnection(event)}>
|
|
410
|
+
<div className="database-form-heading"><h3 id="database-connection-editor-title">{editingName ? `编辑 ${editingName}` : "新增连接"}</h3><button type="button" className="btn btn-secondary" onClick={() => { resetForm(); setFormOpen(false); }}>关闭</button></div>
|
|
411
|
+
<label>连接名称 <span className="field-required">必填</span><input value={name} onChange={(event) => setName(event.target.value)} required placeholder="例如:订单生产库" /><small>这是对话中引用连接时使用的名称,例如“查询订单生产库”。</small></label>
|
|
412
|
+
<label>数据库类型 <span className="field-required">必填</span><select value={engine} onChange={(event) => { const value = event.target.value as DbEngine; setEngine(value); setMode(value === "sqlite" ? "parameters" : "parameters"); setPort(""); }}><option value="sqlite">SQLite</option><option value="postgres">PostgreSQL</option><option value="mysql">MySQL</option></select></label>
|
|
413
|
+
{engine === "sqlite" ? <label>数据库文件绝对路径 <span className="field-required">必填</span><input value={path} onChange={(event) => setPath(event.target.value)} required placeholder="D:\data\app.db" /><small>文件必须已存在。Windows 示例:D:\data\app.db;Linux/macOS 示例:/data/app.db。</small></label> : <>
|
|
414
|
+
<fieldset className="database-connection-mode"><legend>连接方式</legend><label className="database-radio"><input type="radio" name="connection-mode" checked={mode === "parameters"} onChange={() => setMode("parameters")} />填写地址和账号(推荐)</label><label className="database-radio"><input type="radio" name="connection-mode" checked={mode === "url-env"} onChange={() => setMode("url-env")} />完整 DSN 环境变量(高级)</label></fieldset>
|
|
415
|
+
{mode === "parameters" ? <>
|
|
416
|
+
<div className="database-server-fields">
|
|
417
|
+
<label className="database-host-field">主机地址 <span className="field-required">必填</span><input value={host} onChange={(event) => setHost(event.target.value)} required placeholder="127.0.0.1 或 db.example.com" /></label>
|
|
418
|
+
<label className="database-port-field">端口 <span className="field-optional">可选</span><input type="number" min="1" max="65535" inputMode="numeric" value={port} onChange={(event) => setPort(event.target.value)} placeholder={String(defaultPort)} /></label>
|
|
419
|
+
<small>本机数据库通常填写 127.0.0.1;远程数据库填写域名或 IP。端口留空时使用{engine === "postgres" ? " PostgreSQL 默认端口 5432" : " MySQL 默认端口 3306"}。</small>
|
|
420
|
+
</div>
|
|
421
|
+
<label>数据库名 <span className="field-optional">可选</span><input value={database} onChange={(event) => setDatabase(event.target.value)} placeholder={engine === "postgres" ? "留空使用账号默认数据库" : "留空则连接服务器"} /><small>需要固定访问某个数据库时再填写;留空会使用驱动和数据库账号的默认行为。</small></label>
|
|
422
|
+
<label>用户名 <span className="field-required">必填</span><input value={username} onChange={(event) => setUsername(event.target.value)} required autoComplete="username" placeholder={engine === "postgres" ? "例如:postgres" : "例如:root"} /><small>建议使用最小权限账号;只查询时优先使用只读账号。</small></label>
|
|
423
|
+
<fieldset className="database-password-mode"><legend>密码保存方式</legend><label className="database-radio"><input type="radio" name="password-mode" checked={passwordMode === "encrypted"} onChange={() => setPasswordMode("encrypted")} />保存到本地加密凭据库(默认)</label><label className="database-radio"><input type="radio" name="password-mode" checked={passwordMode === "runtime"} onChange={() => setPasswordMode("runtime")} />本次运行直接输入</label><label className="database-radio"><input type="radio" name="password-mode" checked={passwordMode === "environment"} onChange={() => setPasswordMode("environment")} />从环境变量读取</label></fieldset>
|
|
424
|
+
{passwordMode === "runtime" ? <label>密码 {editingName && !editingPasswordRequired ? <span className="field-optional">留空则保留本次运行中的密码</span> : <span className="field-required">必填</span>}<input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required={!editingName || editingPasswordRequired} autoComplete="new-password" placeholder={editingName ? "留空不修改;重启后需重新输入" : "输入数据库密码"} /><small>密码只保存在当前 Console 进程内存中,不写入连接文件、不显示、不导出;Console 重启后需重新输入。</small></label> : passwordMode === "environment" ? <label>密码环境变量名 <span className="field-required">必填</span><input value={passwordEnv} onChange={(event) => setPasswordEnv(event.target.value)} required placeholder="例如:DB_PASSWORD" /><small>填写变量名,不是密码本身。启动 Console 前设置该环境变量,密码不会写入连接文件。</small></label> : <label>本地凭据密码 <span className="field-required">必填</span><input type="password" value={password} onChange={(event) => setPassword(event.target.value)} required={!editingName || editingPasswordRequired} autoComplete="new-password" placeholder="输入后使用 AES-256-GCM 加密保存" /><small>密码写入 Console 全局加密凭据库,不会写入 connections.json、列表或导出文件;加密密钥由当前操作系统用户、主机和应用目录派生。</small></label>}
|
|
425
|
+
<label className="database-checkbox"><input type="checkbox" checked={ssl} onChange={(event) => setSsl(event.target.checked)} />启用 SSL/TLS 加密连接<small>云数据库和跨网络连接通常应开启;本机开发库通常可关闭。启用后使用数据库驱动的标准证书校验,私有 CA 环境需在系统或 Node 运行环境中配置信任链。</small></label>
|
|
426
|
+
</> : <label>完整 DSN 环境变量名 <span className="field-required">必填</span><input value={urlEnv} onChange={(event) => setUrlEnv(event.target.value)} required placeholder={engine === "postgres" ? "例如:DATABASE_URL" : "例如:MYSQL_URL"} /><small>这里填写环境变量名称,不是连接串。变量值示例:{engine === "postgres" ? "postgresql://user:password@host:5432/db" : "mysql://user:password@host:3306/db"}。适合已有部署或集中管理密钥的环境。</small></label>}
|
|
427
|
+
</>}
|
|
428
|
+
<div className="database-form-security-note"><strong>保存说明</strong><span>地址、端口、数据库名、用户名、SSL 设置会保存到 Console 全局 app-data;实际密码或完整 DSN 不会写入、回显或导出。</span></div>
|
|
429
|
+
<button type="submit" className="btn btn-primary database-add-submit" disabled={!props.workspaceId || busyName !== null}>{busyName === "__save__" ? "保存中…" : editingName ? "保存修改" : "保存连接"}</button>
|
|
430
|
+
</form></div></div> : null}
|
|
431
|
+
<section className="database-workbench-shell" aria-label="数据库浏览工作区">
|
|
432
|
+
<aside className="database-connection-rail" aria-label="数据库连接列表">
|
|
433
|
+
<div className="database-connection-rail-title"><b>数据库连接</b><small>{connections.length} 个 · 全局共享</small></div>
|
|
434
|
+
<div className="database-connection-rail-list">
|
|
435
|
+
{connections.length === 0 ? <div className="database-connection-empty"><strong>暂无连接</strong><span>点击“新增连接”开始</span></div> : connections.map((connection) => {
|
|
436
|
+
const healthState = health[connection.name];
|
|
437
|
+
const selected = browserConnection === connection.name;
|
|
438
|
+
return <button type="button" key={connection.name} className={selected ? "database-connection-item is-active" : "database-connection-item"} onClick={() => void browseConnection(connection, true, connection.database ?? "")}>
|
|
439
|
+
<span className="database-connection-item-identity"><strong>{connection.name}</strong><small>{connection.engine === "sqlite" ? connection.path : connection.mode === "url-env" ? `DSN: ${connection.urlEnv}` : `${connection.host}:${connection.port ?? ""}`}</small></span>
|
|
440
|
+
<i className={healthState?.status === "ok" ? "is-ready" : healthState?.status === "error" ? "is-error" : ""} aria-label={healthState?.status === "ok" ? "连接正常" : healthState?.status === "error" ? "连接异常" : "未测试"} />
|
|
441
|
+
</button>;
|
|
442
|
+
})}
|
|
443
|
+
</div>
|
|
444
|
+
</aside>
|
|
445
|
+
<main className="database-workbench-main">{activeConnection ? <>
|
|
446
|
+
<div className="database-active-head">
|
|
447
|
+
<div className="database-profile-title"><h3>{activeConnection.name}</h3><span className="database-engine-badge">{ENGINE_LABELS[activeConnection.engine]}</span></div>
|
|
448
|
+
<p>{activeConnection.engine === "sqlite" ? activeConnection.path : activeConnection.mode === "parameters" ? `${activeConnection.host}:${activeConnection.port ?? ""} / ${browserDatabase || activeConnection.database || "未选择数据库"}` : `DSN: ${activeConnection.urlEnv}`}</p>
|
|
449
|
+
<div className="database-active-actions"><button type="button" className="btn btn-secondary" onClick={() => void testConnection(activeConnection)} disabled={busyName !== null}>{busyName === activeConnection.name ? "测试中…" : "测试连接"}</button><button type="button" className="btn btn-secondary" onClick={() => beginEdit(activeConnection)} disabled={busyName !== null}>编辑连接</button><button type="button" className="btn btn-danger" onClick={() => void removeConnection(activeConnection)} disabled={busyName !== null}>删除</button></div>
|
|
450
|
+
</div>
|
|
451
|
+
<div className="database-workbench-scroll">{renderDataBrowser(activeConnection)}</div>
|
|
452
|
+
</> : <div className="database-workbench-empty"><strong>选择一个数据库</strong><span>然后浏览表数据、查看字段或执行只读 SQL</span></div>}</main>
|
|
453
|
+
</section>
|
|
454
|
+
</section>;
|
|
455
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
/** 与 /zero-db-tool/api 对话的最小客户端。 */
|
|
2
|
+
export type DbEngine = "sqlite" | "postgres" | "mysql";
|
|
3
|
+
export type ConnectionMode = "parameters" | "url-env";
|
|
4
|
+
export type PasswordMode = "runtime" | "environment" | "encrypted";
|
|
5
|
+
|
|
6
|
+
export type Connection = {
|
|
7
|
+
name: string;
|
|
8
|
+
engine: DbEngine;
|
|
9
|
+
path?: string;
|
|
10
|
+
mode?: ConnectionMode;
|
|
11
|
+
urlEnv?: string;
|
|
12
|
+
host?: string;
|
|
13
|
+
port?: number;
|
|
14
|
+
database?: string;
|
|
15
|
+
username?: string;
|
|
16
|
+
passwordMode?: PasswordMode;
|
|
17
|
+
passwordRef?: string;
|
|
18
|
+
passwordEnv?: string;
|
|
19
|
+
passwordStatus?: "runtime" | "environment" | "encrypted" | "required";
|
|
20
|
+
ssl?: boolean;
|
|
21
|
+
createdAt: string;
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
export type TableSummary = { name: string; type: "table" | "view"; schema?: string };
|
|
25
|
+
export type ColumnSummary = { name: string; type: string; nullable: boolean; primaryKey: boolean };
|
|
26
|
+
export type TablePage = {
|
|
27
|
+
connection: string;
|
|
28
|
+
table: string;
|
|
29
|
+
columns: ColumnSummary[];
|
|
30
|
+
rows: Array<Record<string, unknown>>;
|
|
31
|
+
page: number;
|
|
32
|
+
pageSize: number;
|
|
33
|
+
hasNext: boolean;
|
|
34
|
+
};
|
|
35
|
+
export type QueryResult = { connection: string; sql: string; columns: string[]; rows: Array<Record<string, unknown>>; rowCount: number; truncated: boolean };
|
|
36
|
+
export type ConnectionDocument = { schemaVersion: 1; exportedAt: string; connections: Connection[] };
|
|
37
|
+
|
|
38
|
+
const BASE = "/zero-db-tool/api";
|
|
39
|
+
|
|
40
|
+
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|
41
|
+
const response = await fetch(BASE + path, {
|
|
42
|
+
credentials: "same-origin",
|
|
43
|
+
...init,
|
|
44
|
+
headers: { ...(init?.body ? { "Content-Type": "application/json" } : {}), ...(init?.headers ?? {}) },
|
|
45
|
+
});
|
|
46
|
+
let payload: unknown = null;
|
|
47
|
+
try { payload = await response.json(); } catch { payload = null; }
|
|
48
|
+
const body = payload as { ok?: boolean; error?: { message?: string } } | null;
|
|
49
|
+
if (!response.ok || body?.ok === false) {
|
|
50
|
+
throw new Error(body?.error?.message ?? `HTTP ${response.status}`);
|
|
51
|
+
}
|
|
52
|
+
return payload as T;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export const api = {
|
|
56
|
+
version: () => request<{ version: string }>("/version"),
|
|
57
|
+
list: () => request<{ connections: Connection[] }>("/connections"),
|
|
58
|
+
add: (input: Record<string, unknown>) => request<{ connection: Connection }>("/connections", { method: "POST", body: JSON.stringify(input) }),
|
|
59
|
+
update: (name: string, input: Record<string, unknown>) => request<{ connection: Connection }>(`/connections/${encodeURIComponent(name)}`, { method: "PATCH", body: JSON.stringify(input) }),
|
|
60
|
+
remove: (name: string) => request<Record<string, never>>(`/connections/${encodeURIComponent(name)}`, { method: "DELETE" }),
|
|
61
|
+
test: (name: string) => request<{ result: { elapsedMs?: number } }>(`/connections/${encodeURIComponent(name)}/test`, { method: "POST", body: "{}" }),
|
|
62
|
+
catalog: (name: string, database?: string) => request<{ databases: string[]; tables: TableSummary[] }>(
|
|
63
|
+
`/connections/${encodeURIComponent(name)}/browse${database ? `?database=${encodeURIComponent(database)}` : ""}`),
|
|
64
|
+
browse: (name: string, table: string, page: number, pageSize: number, database?: string) => request<{ result: TablePage }>(
|
|
65
|
+
`/connections/${encodeURIComponent(name)}/browse?table=${encodeURIComponent(table)}&page=${page}&pageSize=${pageSize}${database ? `&database=${encodeURIComponent(database)}` : ""}`),
|
|
66
|
+
query: (name: string, sql: string, database?: string) => request<{ result: QueryResult }>(
|
|
67
|
+
`/connections/${encodeURIComponent(name)}/query`, { method: "POST", body: JSON.stringify({ sql, maxRows: 500, ...(database ? { database } : {}) }) }),
|
|
68
|
+
exportAll: () => request<{ document: ConnectionDocument }>("/export"),
|
|
69
|
+
importAll: (document: unknown, conflict: "skip" | "overwrite") => request<{ result: { imported: number; updated: number; skipped: number } }>(
|
|
70
|
+
"/import", { method: "POST", body: JSON.stringify({ document, conflict }) }),
|
|
71
|
+
};
|