@oakzhong/dsh-mysql-client 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/README.md +79 -2
- package/README.zh.md +80 -0
- package/client.js +642 -0
- package/cordis.patch.yml +4 -0
- package/icon.svg +7 -0
- package/index.js +210 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +35 -4
package/README.md
CHANGED
|
@@ -1,3 +1,80 @@
|
|
|
1
|
-
#
|
|
1
|
+
# DSH MySQL Client
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A MySQL client plugin for DeepSeek Harness (DSH). It adds a **MySQL Client** entry to the left sidebar, where you can manage connections, open multiple query tabs, run SQL statements, inspect and edit table structures and indexes, and export results — all from inside the Harness Web UI.
|
|
4
|
+
|
|
5
|
+
SQL execution runs on the Host through the local `mysql` CLI. Connection details are sent per request from the Client and are never persisted on the Host; on the Client they are kept in `localStorage`.
|
|
6
|
+
|
|
7
|
+
## Plugin Info
|
|
8
|
+
|
|
9
|
+
| Field | Value |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| Package | `@oakzhong/dsh-mysql-client` |
|
|
12
|
+
| Version | `1.0.0` |
|
|
13
|
+
| Entry | `index.js` (Host) · `client.js` (Client) |
|
|
14
|
+
| Type | DSH bundle plugin, ES module (`"type": "module"`, private) |
|
|
15
|
+
| Description | A MySQL client with connection management, query tabs and SQL execution. |
|
|
16
|
+
|
|
17
|
+
## Tech Stack
|
|
18
|
+
|
|
19
|
+
| Layer | Technology | Role |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| Client UI | React (via `window.__ModuleLoader__`) | Sidebar entry and the main React panel. |
|
|
22
|
+
| Host runtime | Node.js `child_process.execFile` | Runs the `mysql` CLI for every operation. |
|
|
23
|
+
| Database engine | `mysql` CLI (path via `MYSQL_CLI_PATH`, default `/usr/local/mysql/bin/mysql`) | Executes SQL and returns tabular output. |
|
|
24
|
+
| Plugin framework | Cordis (`slots`, `locale`, `connection`) | UI injection, i18n dictionaries and HTTP routes. |
|
|
25
|
+
| Client storage | `window.localStorage` | Persists connections, active selection and query tabs. |
|
|
26
|
+
| Module format | ES Modules | Package entry points declared in `exports`. |
|
|
27
|
+
|
|
28
|
+
## Features
|
|
29
|
+
|
|
30
|
+
### Connection Management
|
|
31
|
+
- Create, edit and delete saved connections (`name`, `host`, `port`, `user`, `password`).
|
|
32
|
+
- Test a connection with `SELECT 1`; refresh the database list (`SHOW DATABASES`).
|
|
33
|
+
- Connections and the active selection are stored in `localStorage` on the Client only.
|
|
34
|
+
|
|
35
|
+
### Query Tabs & SQL Execution
|
|
36
|
+
- Open and close multiple query tabs; each tab keeps its own SQL, database selection and result.
|
|
37
|
+
- Run SQL with the **Run** button or **⌘/Ctrl+Enter**.
|
|
38
|
+
- Pick a database, browse its tables (`SHOW TABLES`), and click a table to insert a `SELECT * ... LIMIT 100;` template.
|
|
39
|
+
- Results render in a scrollable table with row counts and a truncation notice (the Host caps output at 500 rows).
|
|
40
|
+
|
|
41
|
+
### Table Structure Management
|
|
42
|
+
- Inspect table columns (`DESCRIBE`) and index definitions (`SHOW INDEX`).
|
|
43
|
+
- Add, modify and drop columns via generated `ALTER TABLE ... ADD/MODIFY/DROP COLUMN` statements.
|
|
44
|
+
- Column options include name, type, length, NOT NULL, default, comment, primary key and auto-increment.
|
|
45
|
+
|
|
46
|
+
### Index Management
|
|
47
|
+
- List existing indexes with their columns, type and UNIQUE flag.
|
|
48
|
+
- Create indexes (`ADD [UNIQUE] INDEX ... USING <type>`) and drop indexes (`DROP INDEX`).
|
|
49
|
+
|
|
50
|
+
### Result Export
|
|
51
|
+
- Export the current result to CSV (**Export CSV**).
|
|
52
|
+
- Export the current result as SQL `INSERT` statements (**Export SQL**).
|
|
53
|
+
|
|
54
|
+
### Host API
|
|
55
|
+
Registered under `/api/dsh-mysql-client` via the `connection` service: `test`, `databases`, `tables`, `describe`, `indexes`, `query`. SQL is passed to the CLI as a single `-e` argument and is never interpreted by a shell.
|
|
56
|
+
|
|
57
|
+
## Directory Structure
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
dsh-mysql-client/
|
|
61
|
+
├── index.js # Host half: mysql CLI routes
|
|
62
|
+
├── client.js # Client half: sidebar entry + React panel and styles
|
|
63
|
+
├── cordis.patch.yml # DSH bundle patch
|
|
64
|
+
├── icon.svg # Plugin icon
|
|
65
|
+
├── locale/
|
|
66
|
+
│ ├── zh.json # Chinese metadata
|
|
67
|
+
│ └── en.json # English metadata
|
|
68
|
+
├── package.json
|
|
69
|
+
├── README.md # This document (English)
|
|
70
|
+
└── README.zh.md # Chinese documentation
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## Installation & Usage
|
|
74
|
+
|
|
75
|
+
1. Install this bundle plugin into the target DSH profile and reload the Harness Web UI. It is marked to mount immediately.
|
|
76
|
+
2. Make sure the `mysql` CLI is available on the Host. The default path is `/usr/local/mysql/bin/mysql`; set the `MYSQL_CLI_PATH` environment variable to override it.
|
|
77
|
+
3. Open the **MySQL Client** entry in the left sidebar.
|
|
78
|
+
4. Create a connection (host, port, user, password), then click **Test connection**.
|
|
79
|
+
5. Refresh databases, click **New query**, choose a database, write SQL and press **⌘/Ctrl+Enter** to run it.
|
|
80
|
+
6. To manage a table's structure or indexes, click the gear icon next to a table and switch between the **Columns** and **Indexes** tabs.
|
package/README.zh.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# DSH MySQL 客户端
|
|
2
|
+
|
|
3
|
+
DeepSeek Harness(DSH)的 MySQL 客户端插件。它在左侧栏新增 **MySQL 客户端** 入口,可在 Harness Web UI 内管理连接、打开多个查询页面、执行 SQL 语句、查看与编辑表结构和索引,并导出结果。
|
|
4
|
+
|
|
5
|
+
SQL 执行在 Host 端通过本机 `mysql` 命令行完成。连接信息由 Client 按请求传入,Host 端不做持久化;Client 端将连接与查询页保存在 `localStorage`。
|
|
6
|
+
|
|
7
|
+
## 插件信息
|
|
8
|
+
|
|
9
|
+
| 字段 | 值 |
|
|
10
|
+
| --- | --- |
|
|
11
|
+
| 包名 | `@oakzhong/dsh-mysql-client` |
|
|
12
|
+
| 版本 | `1.0.0` |
|
|
13
|
+
| 入口 | `index.js`(Host)· `client.js`(Client) |
|
|
14
|
+
| 类型 | DSH bundle 插件,ES module(`"type": "module"`,private) |
|
|
15
|
+
| 描述 | A MySQL client with connection management, query tabs and SQL execution. |
|
|
16
|
+
|
|
17
|
+
## 技术栈
|
|
18
|
+
|
|
19
|
+
| 层 | 技术 | 作用 |
|
|
20
|
+
| --- | --- | --- |
|
|
21
|
+
| Client UI | React(通过 `window.__ModuleLoader__`) | 侧边栏入口与主 React 面板。 |
|
|
22
|
+
| Host 运行时 | Node.js `child_process.execFile` | 每次操作调用 `mysql` 命令行。 |
|
|
23
|
+
| 数据库引擎 | `mysql` CLI(路径由 `MYSQL_CLI_PATH` 指定,默认 `/usr/local/mysql/bin/mysql`) | 执行 SQL 并返回表格输出。 |
|
|
24
|
+
| 插件框架 | Cordis(`slots`、`locale`、`connection`) | UI 注入、国际化词典与 HTTP 路由。 |
|
|
25
|
+
| Client 存储 | `window.localStorage` | 保存连接、当前选中连接与查询页。 |
|
|
26
|
+
| 模块格式 | ES Modules | `exports` 中声明包入口。 |
|
|
27
|
+
|
|
28
|
+
## 功能
|
|
29
|
+
|
|
30
|
+
### 连接管理
|
|
31
|
+
- 新建、编辑、删除已保存的连接(`name`、`host`、`port`、`user`、`password`)。
|
|
32
|
+
- 通过 `SELECT 1` 测试连接;刷新数据库列表(`SHOW DATABASES`)。
|
|
33
|
+
- 连接与当前选中项仅保存在 Client 端 `localStorage`。
|
|
34
|
+
|
|
35
|
+
### 查询页与 SQL 执行
|
|
36
|
+
- 新建并关闭多个查询页;每页各自保存 SQL、所选数据库与结果。
|
|
37
|
+
- 通过 **执行** 按钮或 **⌘/Ctrl+Enter** 运行 SQL。
|
|
38
|
+
- 选择数据库、浏览其数据表(`SHOW TABLES`),点击表名可插入 `SELECT * ... LIMIT 100;` 模板。
|
|
39
|
+
- 结果以可滚动表格展示,含行数统计与截断提示(Host 端最多返回 500 行)。
|
|
40
|
+
|
|
41
|
+
### 表结构管理
|
|
42
|
+
- 查看字段(`DESCRIBE`)与索引定义(`SHOW INDEX`)。
|
|
43
|
+
- 通过生成的 `ALTER TABLE ... ADD/MODIFY/DROP COLUMN` 语句增加、修改、删除字段。
|
|
44
|
+
- 字段选项包含名称、类型、长度、非空、默认值、备注、主键与自增。
|
|
45
|
+
|
|
46
|
+
### 索引管理
|
|
47
|
+
- 列出已有索引及其字段、类型与 UNIQUE 标志。
|
|
48
|
+
- 创建索引(`ADD [UNIQUE] INDEX ... USING <type>`)与删除索引(`DROP INDEX`)。
|
|
49
|
+
|
|
50
|
+
### 结果导出
|
|
51
|
+
- 将当前结果导出为 CSV(**导出 CSV**)。
|
|
52
|
+
- 将当前结果导出为 SQL `INSERT` 语句(**导出 SQL**)。
|
|
53
|
+
|
|
54
|
+
### Host 接口
|
|
55
|
+
通过 `connection` 服务注册在 `/api/dsh-mysql-client` 下:`test`、`databases`、`tables`、`describe`、`indexes`、`query`。SQL 作为单个 `-e` 参数传给命令行,不经过 shell 解释。
|
|
56
|
+
|
|
57
|
+
## 目录结构
|
|
58
|
+
|
|
59
|
+
```
|
|
60
|
+
dsh-mysql-client/
|
|
61
|
+
├── index.js # Host 端:mysql 命令行路由
|
|
62
|
+
├── client.js # Client 端:侧边栏入口 + React 面板与样式
|
|
63
|
+
├── cordis.patch.yml # DSH bundle patch
|
|
64
|
+
├── icon.svg # 插件图标
|
|
65
|
+
├── locale/
|
|
66
|
+
│ ├── zh.json # 中文元数据
|
|
67
|
+
│ └── en.json # 英文元数据
|
|
68
|
+
├── package.json
|
|
69
|
+
├── README.md # 本文档(英文)
|
|
70
|
+
└── README.zh.md # 中文文档
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
## 安装与使用
|
|
74
|
+
|
|
75
|
+
1. 将该 bundle 插件安装到目标 DSH profile,并刷新 Harness Web UI。该插件标记为立即挂载。
|
|
76
|
+
2. 确保 Host 端存在 `mysql` 命令行工具。默认路径为 `/usr/local/mysql/bin/mysql`;可通过环境变量 `MYSQL_CLI_PATH` 覆盖。
|
|
77
|
+
3. 打开左侧栏的 **MySQL 客户端** 入口。
|
|
78
|
+
4. 新建连接(地址、端口、用户名、密码),点击 **测试连接**。
|
|
79
|
+
5. 刷新数据库,点击 **新建查询**,选择数据库,编写 SQL 后按 **⌘/Ctrl+Enter** 执行。
|
|
80
|
+
6. 管理表结构或索引时,点击表名旁的齿轮图标,在 **字段** 与 **索引** 标签间切换。
|
package/client.js
ADDED
|
@@ -0,0 +1,642 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client half of the MySQL client bundle.
|
|
3
|
+
* Left sidebar entry + panel: connection manager and multiple query tabs.
|
|
4
|
+
*/
|
|
5
|
+
window.__ModuleLoader__.load({
|
|
6
|
+
id: '@oakzhong/dsh-mysql-client',
|
|
7
|
+
factory(require) {
|
|
8
|
+
const React = require('react')
|
|
9
|
+
const h = React.createElement
|
|
10
|
+
const { useState, useEffect, useRef, useCallback, useMemo } = React
|
|
11
|
+
|
|
12
|
+
const NS = 'dsh-mysql-client'
|
|
13
|
+
const PANEL_ID = 'mysql-client'
|
|
14
|
+
const STYLE_ID = 'dsh-mysql-client/css'
|
|
15
|
+
const API = '/api/dsh-mysql-client'
|
|
16
|
+
const CONN_KEY = 'dsh-mysql-client.connections.v1'
|
|
17
|
+
const ACTIVE_KEY = 'dsh-mysql-client.active.v1'
|
|
18
|
+
const TABS_KEY = 'dsh-mysql-client.tabs.v1'
|
|
19
|
+
|
|
20
|
+
const zh = {
|
|
21
|
+
title: 'MySQL 客户端', subtitle: '管理连接,新建查询页面,执行 SQL 语句。',
|
|
22
|
+
connections: '连接', newConn: '新建连接', edit: '编辑', del: '删除', save: '保存', cancel: '取消',
|
|
23
|
+
name: '名称', host: '地址', port: '端口', user: '用户名', password: '密码',
|
|
24
|
+
test: '测试连接', ok: '连接成功', fail: '连接失败',
|
|
25
|
+
queries: '查询', newTab: '新建查询', closeTab: '关闭', db: '数据库',
|
|
26
|
+
run: '执行 (⌘/Ctrl+Enter)', result: '结果', rows: '{n} 行', truncated: '仅显示前 {n} 行',
|
|
27
|
+
noConn: '请先新建并选择一个连接。', noTab: '点「新建查询」打开一个查询页面。',
|
|
28
|
+
sqlPlaceholder: 'SELECT * FROM table LIMIT 100;', databases: '刷新库', tables: '表',
|
|
29
|
+
structure: '结构', addField: '加字段', modifyField: '修改', dropField: '删除',
|
|
30
|
+
fieldName: '字段名', fieldType: '类型', fieldLen: '长度', notNull: '非空',
|
|
31
|
+
defaultValue: '默认值', comment: '备注', primary: '主键', autoInc: '自增',
|
|
32
|
+
applySql: '执行变更', structureTitle: '表结构', noStructure: '暂无结构信息',
|
|
33
|
+
exportCsv: '导出 CSV', exportSql: '导出 SQL', confirmDropField: '确定删除该字段?',
|
|
34
|
+
indexes: '索引', indexName: '索引名', indexColumns: '字段(逗号分隔)', indexType: '类型',
|
|
35
|
+
unique: '唯一', addIndex: '创建索引', dropIndex: '删除索引', noIndexes: '暂无索引',
|
|
36
|
+
confirmDropIndex: '确定删除该索引?', tabColumns: '字段', tabIndexes: '索引',
|
|
37
|
+
noWorkspace: '', listFailed: '操作失败', confirmDel: '确定删除该连接?',
|
|
38
|
+
affected: '执行完成', error: '错误',
|
|
39
|
+
}
|
|
40
|
+
const en = {
|
|
41
|
+
title: 'MySQL client', subtitle: 'Manage connections, open query tabs and run SQL.',
|
|
42
|
+
connections: 'Connections', newConn: 'New connection', edit: 'Edit', del: 'Delete', save: 'Save', cancel: 'Cancel',
|
|
43
|
+
name: 'Name', host: 'Host', port: 'Port', user: 'User', password: 'Password',
|
|
44
|
+
test: 'Test connection', ok: 'Connected', fail: 'Connection failed',
|
|
45
|
+
queries: 'Queries', newTab: 'New query', closeTab: 'Close', db: 'Database',
|
|
46
|
+
run: 'Run (⌘/Ctrl+Enter)', result: 'Result', rows: '{n} rows', truncated: 'Showing first {n} rows',
|
|
47
|
+
noConn: 'Create and select a connection first.', noTab: 'Click "New query" to open a query tab.',
|
|
48
|
+
sqlPlaceholder: 'SELECT * FROM table LIMIT 100;', databases: 'Refresh DBs', tables: 'Tables',
|
|
49
|
+
structure: 'Structure', addField: 'Add column', modifyField: 'Modify', dropField: 'Drop',
|
|
50
|
+
fieldName: 'Field', fieldType: 'Type', fieldLen: 'Length', notNull: 'Not null',
|
|
51
|
+
defaultValue: 'Default', comment: 'Comment', primary: 'Primary', autoInc: 'Auto increment',
|
|
52
|
+
applySql: 'Apply', structureTitle: 'Table structure', noStructure: 'No structure info',
|
|
53
|
+
exportCsv: 'Export CSV', exportSql: 'Export SQL', confirmDropField: 'Drop this column?',
|
|
54
|
+
indexes: 'Indexes', indexName: 'Index name', indexColumns: 'Columns (comma separated)', indexType: 'Type',
|
|
55
|
+
unique: 'Unique', addIndex: 'Create index', dropIndex: 'Drop index', noIndexes: 'No indexes',
|
|
56
|
+
confirmDropIndex: 'Delete this index?', tabColumns: 'Columns', tabIndexes: 'Indexes',
|
|
57
|
+
noWorkspace: '', listFailed: 'Operation failed', confirmDel: 'Delete this connection?',
|
|
58
|
+
affected: 'Done', error: 'Error',
|
|
59
|
+
}
|
|
60
|
+
let t = (k) => (zh[k] || k)
|
|
61
|
+
const fmt = (s, v) => String(s || '').replace(/\{(\w+)\}/g, (_, k) => (v && v[k] != null ? v[k] : ''))
|
|
62
|
+
|
|
63
|
+
function readJSON(key, fallback) { try { const r = window.localStorage.getItem(key); return r ? JSON.parse(r) : fallback } catch (_) { return fallback } }
|
|
64
|
+
function writeJSON(key, v) { try { window.localStorage.setItem(key, JSON.stringify(v)) } catch (_) {} }
|
|
65
|
+
function makeId() { return 'x-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 7) }
|
|
66
|
+
|
|
67
|
+
async function api(path, body) {
|
|
68
|
+
const res = await fetch(API + path, {
|
|
69
|
+
method: body === undefined ? 'GET' : 'POST',
|
|
70
|
+
credentials: 'same-origin',
|
|
71
|
+
headers: { 'content-type': 'application/json' },
|
|
72
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
73
|
+
})
|
|
74
|
+
let data = null
|
|
75
|
+
try { data = await res.json() } catch (_) {}
|
|
76
|
+
if (!res.ok) throw new Error((data && data.error) || ('HTTP ' + res.status))
|
|
77
|
+
return data
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function SidebarIcon(props) {
|
|
81
|
+
const size = typeof props.size === 'number' ? props.size : 20
|
|
82
|
+
return h('svg', {
|
|
83
|
+
viewBox: '0 0 24 24', width: size, height: size, fill: 'none',
|
|
84
|
+
stroke: 'currentColor', strokeWidth: 1.6, 'aria-hidden': true,
|
|
85
|
+
style: { opacity: props.active ? 1 : 0.82 },
|
|
86
|
+
},
|
|
87
|
+
h('ellipse', { cx: 12, cy: 6, rx: 8, ry: 3 }),
|
|
88
|
+
h('path', { d: 'M4 6v6c0 1.7 3.6 3 8 3s8-1.3 8-3V6' }),
|
|
89
|
+
h('path', { d: 'M4 12v6c0 1.7 3.6 3 8 3s8-1.3 8-3v-6' })
|
|
90
|
+
)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function MysqlPanel({ ctx }) {
|
|
94
|
+
const [conns, setConns] = useState(() => readJSON(CONN_KEY, []))
|
|
95
|
+
const [activeId, setActiveId] = useState(() => { try { return window.localStorage.getItem(ACTIVE_KEY) || '' } catch (_) { return '' } })
|
|
96
|
+
const [editing, setEditing] = useState(null)
|
|
97
|
+
const [form, setForm] = useState({ name: '', host: '127.0.0.1', port: 3306, user: 'root', password: '' })
|
|
98
|
+
const [ping, setPing] = useState('')
|
|
99
|
+
const [tabs, setTabs] = useState(() => readJSON(TABS_KEY, []))
|
|
100
|
+
const [activeTab, setActiveTab] = useState('')
|
|
101
|
+
const [databases, setDatabases] = useState([])
|
|
102
|
+
const [tables, setTables] = useState([])
|
|
103
|
+
const [busy, setBusy] = useState(false)
|
|
104
|
+
const [err, setErr] = useState('')
|
|
105
|
+
const [structTable, setStructTable] = useState('')
|
|
106
|
+
const [structColumns, setStructColumns] = useState([])
|
|
107
|
+
const [structTab, setStructTab] = useState('columns')
|
|
108
|
+
const [indexes, setIndexes] = useState([])
|
|
109
|
+
const [indexForm, setIndexForm] = useState({ name: '', columns: '', unique: false, type: 'BTREE' })
|
|
110
|
+
const [fieldForm, setFieldForm] = useState({ name: '', type: 'VARCHAR', len: '255', notNull: false, def: '', comment: '', primary: false, autoInc: false })
|
|
111
|
+
|
|
112
|
+
const active = useMemo(() => conns.find((c) => c.id === activeId) || null, [conns, activeId])
|
|
113
|
+
const tab = useMemo(() => tabs.find((x) => x.id === activeTab) || null, [tabs, activeTab])
|
|
114
|
+
const connCfg = active ? { host: active.host, port: active.port, user: active.user, password: active.password } : null
|
|
115
|
+
|
|
116
|
+
useEffect(() => { writeJSON(CONN_KEY, conns) }, [conns])
|
|
117
|
+
useEffect(() => { writeJSON(TABS_KEY, tabs) }, [tabs])
|
|
118
|
+
useEffect(() => { try { window.localStorage.setItem(ACTIVE_KEY, activeId) } catch (_) {} }, [activeId])
|
|
119
|
+
|
|
120
|
+
const patchTab = useCallback((id, patch) => setTabs((prev) => prev.map((x) => x.id === id ? { ...x, ...patch } : x)), [])
|
|
121
|
+
|
|
122
|
+
const saveConn = useCallback(() => {
|
|
123
|
+
const c = {
|
|
124
|
+
id: editing || makeId(),
|
|
125
|
+
name: form.name.trim() || (form.user + '@' + form.host),
|
|
126
|
+
host: form.host.trim() || '127.0.0.1',
|
|
127
|
+
port: Number(form.port) || 3306,
|
|
128
|
+
user: form.user.trim(), password: form.password || '',
|
|
129
|
+
}
|
|
130
|
+
setConns((prev) => editing ? prev.map((x) => x.id === editing ? c : x) : [...prev, c])
|
|
131
|
+
setActiveId(c.id)
|
|
132
|
+
setEditing(null)
|
|
133
|
+
setPing(''); setErr('')
|
|
134
|
+
}, [form, editing])
|
|
135
|
+
|
|
136
|
+
const editConn = useCallback((c) => {
|
|
137
|
+
setEditing(c.id)
|
|
138
|
+
setForm({ name: c.name, host: c.host, port: c.port, user: c.user, password: c.password || '' })
|
|
139
|
+
}, [])
|
|
140
|
+
|
|
141
|
+
const removeConn = useCallback((id) => {
|
|
142
|
+
if (!window.confirm(t('confirmDel'))) return
|
|
143
|
+
setConns((prev) => prev.filter((c) => c.id !== id))
|
|
144
|
+
if (activeId === id) { setActiveId(''); setPing(''); setDatabases([]); setTables([]) }
|
|
145
|
+
}, [activeId])
|
|
146
|
+
|
|
147
|
+
const testConn = useCallback(async () => {
|
|
148
|
+
if (!connCfg) return
|
|
149
|
+
setBusy(true); setErr(''); setPing('')
|
|
150
|
+
try {
|
|
151
|
+
const d = await api('/test', { connection: connCfg })
|
|
152
|
+
setPing(d.ok ? t('ok') : t('fail'))
|
|
153
|
+
} catch (e) { setPing(t('fail')); setErr(e.message) }
|
|
154
|
+
finally { setBusy(false) }
|
|
155
|
+
}, [connCfg])
|
|
156
|
+
|
|
157
|
+
const loadDatabases = useCallback(async (cfgOverride) => {
|
|
158
|
+
const cfg = cfgOverride || connCfg
|
|
159
|
+
if (!cfg) return
|
|
160
|
+
setBusy(true); setErr('')
|
|
161
|
+
try {
|
|
162
|
+
const d = await api('/databases', { connection: cfg })
|
|
163
|
+
setDatabases(d.databases || [])
|
|
164
|
+
} catch (e) { setErr(e.message) }
|
|
165
|
+
finally { setBusy(false) }
|
|
166
|
+
}, [connCfg])
|
|
167
|
+
|
|
168
|
+
// Auto-load databases whenever the selected connection changes.
|
|
169
|
+
const autoDbKey = activeId + '|' + (active ? active.host + ':' + active.port + ':' + active.user : '')
|
|
170
|
+
useEffect(() => {
|
|
171
|
+
if (!active) { setDatabases([]); setTables([]); return }
|
|
172
|
+
loadDatabases({ host: active.host, port: active.port, user: active.user, password: active.password })
|
|
173
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
174
|
+
}, [autoDbKey])
|
|
175
|
+
|
|
176
|
+
const loadTables = useCallback(async (db) => {
|
|
177
|
+
if (!connCfg || !db) { setTables([]); return }
|
|
178
|
+
setErr('')
|
|
179
|
+
try {
|
|
180
|
+
const d = await api('/tables', { connection: connCfg, database: db })
|
|
181
|
+
setTables(d.tables || [])
|
|
182
|
+
} catch (e) { setErr(e.message); setTables([]) }
|
|
183
|
+
}, [connCfg])
|
|
184
|
+
|
|
185
|
+
const addTab = useCallback(() => {
|
|
186
|
+
const id = makeId()
|
|
187
|
+
setTabs((prev) => [...prev, { id, title: 'Query ' + (prev.length + 1), sql: '', database: '', result: null, message: '' }])
|
|
188
|
+
setActiveTab(id)
|
|
189
|
+
}, [])
|
|
190
|
+
|
|
191
|
+
const closeTab = useCallback((id) => {
|
|
192
|
+
setTabs((prev) => {
|
|
193
|
+
const next = prev.filter((x) => x.id !== id)
|
|
194
|
+
if (activeTab === id) setActiveTab(next.length ? next[next.length - 1].id : '')
|
|
195
|
+
return next
|
|
196
|
+
})
|
|
197
|
+
}, [activeTab])
|
|
198
|
+
|
|
199
|
+
const runSql = useCallback(async () => {
|
|
200
|
+
if (!connCfg || !tab || !tab.sql.trim()) return
|
|
201
|
+
setBusy(true); setErr('')
|
|
202
|
+
try {
|
|
203
|
+
const d = await api('/query', { connection: connCfg, database: tab.database, sql: tab.sql })
|
|
204
|
+
patchTab(tab.id, {
|
|
205
|
+
result: { columns: d.columns || [], rows: d.rows || [], truncated: !!d.truncated },
|
|
206
|
+
message: d.message || t('affected'),
|
|
207
|
+
})
|
|
208
|
+
if (tab.database) loadTables(tab.database)
|
|
209
|
+
} catch (e) {
|
|
210
|
+
setErr(e.message)
|
|
211
|
+
patchTab(tab.id, { result: null, message: t('error') + ': ' + e.message })
|
|
212
|
+
}
|
|
213
|
+
finally { setBusy(false) }
|
|
214
|
+
}, [connCfg, tab, patchTab, loadTables])
|
|
215
|
+
|
|
216
|
+
// ---- table structure management ----
|
|
217
|
+
const qid = (s) => '`' + String(s).replace(/`/g, '``') + '`'
|
|
218
|
+
const dbNow = () => (tab && tab.database) || ''
|
|
219
|
+
|
|
220
|
+
const loadStructure = useCallback(async (tableName) => {
|
|
221
|
+
const db = (tab && tab.database) || ''
|
|
222
|
+
if (!connCfg || !db || !tableName) return
|
|
223
|
+
setStructTable(tableName)
|
|
224
|
+
setBusy(true); setErr('')
|
|
225
|
+
try {
|
|
226
|
+
const d = await api('/describe', { connection: connCfg, database: db, table: tableName })
|
|
227
|
+
setStructColumns(d.columns || [])
|
|
228
|
+
const first = (d.columns || [])[0]
|
|
229
|
+
if (first) setFieldForm({
|
|
230
|
+
name: first.field, type: (first.type || 'VARCHAR').split('(')[0].toUpperCase(),
|
|
231
|
+
len: (first.type.match(/\(([^)]+)\)/) || [])[1] || '255',
|
|
232
|
+
notNull: first.nullable === 'NO', def: first.default || '',
|
|
233
|
+
comment: '', primary: first.key === 'PRI', autoInc: /auto_increment/i.test(first.extra),
|
|
234
|
+
})
|
|
235
|
+
// load indexes alongside columns
|
|
236
|
+
try {
|
|
237
|
+
const ix = await api('/indexes', { connection: connCfg, database: db, table: tableName })
|
|
238
|
+
setIndexes(ix.indexes || [])
|
|
239
|
+
} catch (_) { setIndexes([]) }
|
|
240
|
+
} catch (e) { setErr(e.message); setStructColumns([]) }
|
|
241
|
+
finally { setBusy(false) }
|
|
242
|
+
}, [connCfg, tab])
|
|
243
|
+
|
|
244
|
+
const columnDef = useCallback((f, includeName) => {
|
|
245
|
+
const type = String(f.type || 'VARCHAR').toUpperCase()
|
|
246
|
+
const withLen = ['VARCHAR', 'CHAR', 'DECIMAL', 'NUMERIC', 'INT', 'BIGINT', 'TINYINT', 'TEXT', 'BLOB'].indexOf(type) >= 0 && f.len
|
|
247
|
+
? type + '(' + f.len + ')' : type
|
|
248
|
+
let def = (includeName ? qid(f.name) + ' ' : '') + withLen
|
|
249
|
+
if (f.notNull) def += ' NOT NULL'
|
|
250
|
+
else def += ' NULL'
|
|
251
|
+
if (f.autoInc) def += ' AUTO_INCREMENT'
|
|
252
|
+
if (f.def !== '' && f.def != null && !f.autoInc) def += ' DEFAULT ' + (/^(NULL|CURRENT_TIMESTAMP)$/i.test(String(f.def)) ? String(f.def) : "'" + String(f.def).replace(/'/g, "''") + "'")
|
|
253
|
+
if (f.comment) def += " COMMENT '" + String(f.comment).replace(/'/g, "''") + "'"
|
|
254
|
+
if (f.primary) def += ' PRIMARY KEY'
|
|
255
|
+
return def
|
|
256
|
+
}, [])
|
|
257
|
+
|
|
258
|
+
const execStructureSql = useCallback(async (sql) => {
|
|
259
|
+
const db = dbNow()
|
|
260
|
+
if (!connCfg || !db || !sql) return
|
|
261
|
+
setBusy(true); setErr('')
|
|
262
|
+
try {
|
|
263
|
+
const d = await api('/query', { connection: connCfg, database: db, sql })
|
|
264
|
+
if (d.error) throw new Error(d.error)
|
|
265
|
+
patchTab(tab.id, { message: t('affected') + ' · ' + (d.message || ''), result: (d.columns && d.columns.length) ? { columns: d.columns, rows: d.rows, truncated: d.truncated } : null })
|
|
266
|
+
await loadStructure(structTable)
|
|
267
|
+
} catch (e) { setErr(e.message) }
|
|
268
|
+
finally { setBusy(false) }
|
|
269
|
+
}, [connCfg, tab, dbNow, loadStructure, structTable, patchTab])
|
|
270
|
+
|
|
271
|
+
const addField = useCallback(() => {
|
|
272
|
+
if (!structTable || !fieldForm.name.trim()) return
|
|
273
|
+
const db = dbNow()
|
|
274
|
+
const sql = 'ALTER TABLE ' + qid(db) + '.' + qid(structTable) + ' ADD COLUMN ' + columnDef(fieldForm, true)
|
|
275
|
+
execStructureSql(sql)
|
|
276
|
+
}, [structTable, fieldForm, dbNow, columnDef, execStructureSql])
|
|
277
|
+
|
|
278
|
+
const modifyField = useCallback((oldCol) => {
|
|
279
|
+
if (!structTable || !oldCol || !oldCol.field) return
|
|
280
|
+
const db = dbNow()
|
|
281
|
+
const sql = 'ALTER TABLE ' + qid(db) + '.' + qid(structTable) + ' MODIFY COLUMN ' + columnDef(fieldForm, true)
|
|
282
|
+
execStructureSql(sql)
|
|
283
|
+
}, [structTable, dbNow, columnDef, execStructureSql])
|
|
284
|
+
|
|
285
|
+
const dropField = useCallback((col) => {
|
|
286
|
+
if (!structTable || !col) return
|
|
287
|
+
if (!window.confirm(t('confirmDropField'))) return
|
|
288
|
+
const db = dbNow()
|
|
289
|
+
const sql = 'ALTER TABLE ' + qid(db) + '.' + qid(structTable) + ' DROP COLUMN ' + qid(col.field)
|
|
290
|
+
execStructureSql(sql)
|
|
291
|
+
}, [structTable, dbNow, execStructureSql])
|
|
292
|
+
|
|
293
|
+
// ---- index management ----
|
|
294
|
+
const addIndex = useCallback(() => {
|
|
295
|
+
if (!structTable || !indexForm.name.trim() || !indexForm.columns.trim()) return
|
|
296
|
+
const db = dbNow()
|
|
297
|
+
const cols = indexForm.columns.split(',').map((s) => qid(s.trim())).filter((s) => s !== '``').join(', ')
|
|
298
|
+
if (!cols) return
|
|
299
|
+
const uniq = indexForm.unique ? 'UNIQUE ' : ''
|
|
300
|
+
const sql = 'ALTER TABLE ' + qid(db) + '.' + qid(structTable) + ' ADD ' + uniq + 'INDEX ' + qid(indexForm.name.trim()) + ' (' + cols + ') USING ' + indexForm.type
|
|
301
|
+
execStructureSql(sql)
|
|
302
|
+
setIndexForm({ name: '', columns: '', unique: false, type: 'BTREE' })
|
|
303
|
+
}, [structTable, indexForm, dbNow, execStructureSql])
|
|
304
|
+
|
|
305
|
+
const dropIndex = useCallback((ix) => {
|
|
306
|
+
if (!structTable || !ix) return
|
|
307
|
+
if (!window.confirm(t('confirmDropIndex'))) return
|
|
308
|
+
const db = dbNow()
|
|
309
|
+
const sql = 'ALTER TABLE ' + qid(db) + '.' + qid(structTable) + ' DROP INDEX ' + qid(ix.name)
|
|
310
|
+
execStructureSql(sql)
|
|
311
|
+
}, [structTable, dbNow, execStructureSql])
|
|
312
|
+
|
|
313
|
+
// ---- export results ----
|
|
314
|
+
const download = useCallback((filename, content, mime) => {
|
|
315
|
+
try {
|
|
316
|
+
const blob = new Blob([content], { type: mime || 'text/plain;charset=utf-8' })
|
|
317
|
+
const url = URL.createObjectURL(blob)
|
|
318
|
+
const a = document.createElement('a')
|
|
319
|
+
a.href = url; a.download = filename
|
|
320
|
+
document.body.appendChild(a); a.click(); a.remove()
|
|
321
|
+
setTimeout(() => URL.revokeObjectURL(url), 1000)
|
|
322
|
+
} catch (e) { setErr(e.message) }
|
|
323
|
+
}, [])
|
|
324
|
+
|
|
325
|
+
const exportCsv = useCallback(() => {
|
|
326
|
+
if (!tab || !tab.result || !tab.result.columns.length) return
|
|
327
|
+
const esc = (v) => {
|
|
328
|
+
const s = v == null ? '' : String(v)
|
|
329
|
+
return /[",\n\r]/.test(s) ? '"' + s.replace(/"/g, '""') + '"' : s
|
|
330
|
+
}
|
|
331
|
+
const lines = [tab.result.columns.map(esc).join(',')]
|
|
332
|
+
for (const row of tab.result.rows) lines.push(row.map(esc).join(','))
|
|
333
|
+
download((tab.title || 'result').replace(/[^\w\u4e00-\u9fa5-]/g, '_') + '.csv', '\ufeff' + lines.join('\n'), 'text/csv;charset=utf-8')
|
|
334
|
+
}, [tab, download])
|
|
335
|
+
|
|
336
|
+
const exportSql = useCallback(() => {
|
|
337
|
+
if (!tab || !tab.result || !tab.result.columns.length) return
|
|
338
|
+
const table = structTable || 'exported_table'
|
|
339
|
+
const esc = (v) => v == null ? 'NULL' : "'" + String(v).replace(/'/g, "''") + "'"
|
|
340
|
+
const cols = tab.result.columns.map(qid).join(', ')
|
|
341
|
+
const lines = tab.result.rows.map((row) =>
|
|
342
|
+
'INSERT INTO ' + qid(table) + ' (' + cols + ') VALUES (' + row.map(esc).join(', ') + ');'
|
|
343
|
+
)
|
|
344
|
+
download((structTable || 'result').replace(/[^\w\u4e00-\u9fa5-]/g, '_') + '.sql', lines.join('\n'), 'application/sql;charset=utf-8')
|
|
345
|
+
}, [tab, structTable, download])
|
|
346
|
+
|
|
347
|
+
const goBack = useCallback(() => {
|
|
348
|
+
try { if (ctx && ctx.layout) ctx.layout.selectPanel('conversation') } catch (_) {}
|
|
349
|
+
}, [ctx])
|
|
350
|
+
|
|
351
|
+
const formRow = (label, key, type) =>
|
|
352
|
+
h('label', { className: 'dshMy-field' },
|
|
353
|
+
h('span', null, t(label)),
|
|
354
|
+
h('input', {
|
|
355
|
+
className: 'dshMy-input', type: type || 'text', value: form[key],
|
|
356
|
+
onChange: (e) => setForm((f) => ({ ...f, [key]: e.target.value })),
|
|
357
|
+
})
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
const resultTable = tab && tab.result && tab.result.columns.length
|
|
361
|
+
? h('div', { className: 'dshMy-tableWrap' },
|
|
362
|
+
h('table', { className: 'dshMy-table' },
|
|
363
|
+
h('thead', null, h('tr', null,
|
|
364
|
+
h('th', null, '#'),
|
|
365
|
+
tab.result.columns.map((c, i) => h('th', { key: i }, c))
|
|
366
|
+
)),
|
|
367
|
+
h('tbody', null, tab.result.rows.map((row, ri) =>
|
|
368
|
+
h('tr', { key: ri },
|
|
369
|
+
h('td', { className: 'dshMy-idx' }, ri + 1),
|
|
370
|
+
row.map((cell, ci) => h('td', { key: ci, title: cell == null ? '' : String(cell) }, cell == null ? 'NULL' : String(cell)))
|
|
371
|
+
)
|
|
372
|
+
))
|
|
373
|
+
),
|
|
374
|
+
tab.result.truncated ? h('div', { className: 'dshMy-note' }, fmt(t('truncated'), { n: tab.result.rows.length })) : null
|
|
375
|
+
)
|
|
376
|
+
: h('div', { className: 'dshMy-note' }, tab && tab.message ? tab.message : t('noTab'))
|
|
377
|
+
|
|
378
|
+
return h('div', { className: 'dshMy-root' },
|
|
379
|
+
h('div', { className: 'dshMy-head' },
|
|
380
|
+
h('div', null,
|
|
381
|
+
h('div', { className: 'dshMy-title' }, t('title')),
|
|
382
|
+
h('div', { className: 'dshMy-sub' }, t('subtitle'))
|
|
383
|
+
),
|
|
384
|
+
h('button', { type: 'button', className: 'dshMy-back', onClick: goBack }, t('back'))
|
|
385
|
+
),
|
|
386
|
+
err ? h('div', { className: 'dshMy-err' }, err) : null,
|
|
387
|
+
h('div', { className: 'dshMy-cols' },
|
|
388
|
+
// left: connections + query tabs
|
|
389
|
+
h('div', { className: 'dshMy-col' },
|
|
390
|
+
h('div', { className: 'dshMy-card' },
|
|
391
|
+
h('div', { className: 'dshMy-cardTitle' }, t('connections')),
|
|
392
|
+
h('div', { className: 'dshMy-connList' },
|
|
393
|
+
conns.length === 0
|
|
394
|
+
? h('div', { className: 'dshMy-note' }, t('noConn'))
|
|
395
|
+
: conns.map((c) =>
|
|
396
|
+
h('div', {
|
|
397
|
+
key: c.id,
|
|
398
|
+
className: 'dshMy-conn' + (activeId === c.id ? ' dshMy-connOn' : ''),
|
|
399
|
+
onClick: () => { setActiveId(c.id); setPing(''); setDatabases([]); setTables([]) },
|
|
400
|
+
},
|
|
401
|
+
h('span', { className: 'dshMy-name' }, c.name),
|
|
402
|
+
h('span', { className: 'dshMy-addr' }, `${c.user}@${c.host}:${c.port}`),
|
|
403
|
+
h('button', { type: 'button', className: 'dshMy-mini', onClick: (e) => { e.stopPropagation(); editConn(c) } }, t('edit')),
|
|
404
|
+
h('button', { type: 'button', className: 'dshMy-mini dshMy-del', onClick: (e) => { e.stopPropagation(); removeConn(c.id) } }, '×')
|
|
405
|
+
)
|
|
406
|
+
)
|
|
407
|
+
),
|
|
408
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnPrimary', onClick: () => { setEditing(null); setForm({ name: '', host: '127.0.0.1', port: 3306, user: 'root', password: '' }) } }, '+ ' + t('newConn')),
|
|
409
|
+
active ? h('button', { type: 'button', className: 'dshMy-btn', disabled: busy, onClick: testConn }, t('test')) : null,
|
|
410
|
+
active ? h('button', { type: 'button', className: 'dshMy-btn', disabled: busy, onClick: () => loadDatabases() }, t('databases')) : null,
|
|
411
|
+
ping ? h('div', { className: 'dshMy-note' }, ping) : null
|
|
412
|
+
),
|
|
413
|
+
h('div', { className: 'dshMy-card' },
|
|
414
|
+
h('div', { className: 'dshMy-cardTitle' }, editing ? t('edit') : t('newConn')),
|
|
415
|
+
h('div', { className: 'dshMy-form' },
|
|
416
|
+
formRow('name', 'name'), formRow('host', 'host'),
|
|
417
|
+
formRow('port', 'port', 'number'), formRow('user', 'user'), formRow('password', 'password', 'password'),
|
|
418
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnPrimary', onClick: saveConn }, t('save'))
|
|
419
|
+
)
|
|
420
|
+
),
|
|
421
|
+
h('div', { className: 'dshMy-card dshMy-grow' },
|
|
422
|
+
h('div', { className: 'dshMy-cardTitle' }, t('queries')),
|
|
423
|
+
h('div', { className: 'dshMy-tabs' },
|
|
424
|
+
tabs.length === 0
|
|
425
|
+
? h('div', { className: 'dshMy-note' }, t('noTab'))
|
|
426
|
+
: tabs.map((x) =>
|
|
427
|
+
h('div', {
|
|
428
|
+
key: x.id,
|
|
429
|
+
className: 'dshMy-tab' + (activeTab === x.id ? ' dshMy-tabOn' : ''),
|
|
430
|
+
onClick: () => setActiveTab(x.id),
|
|
431
|
+
},
|
|
432
|
+
h('span', null, x.title),
|
|
433
|
+
h('button', { type: 'button', className: 'dshMy-mini', onClick: (e) => { e.stopPropagation(); closeTab(x.id) } }, '×')
|
|
434
|
+
)
|
|
435
|
+
)
|
|
436
|
+
),
|
|
437
|
+
h('button', { type: 'button', className: 'dshMy-btn', onClick: addTab }, '+ ' + t('newTab'))
|
|
438
|
+
)
|
|
439
|
+
),
|
|
440
|
+
// right: query editor + result
|
|
441
|
+
h('div', { className: 'dshMy-col dshMy-main' },
|
|
442
|
+
tab
|
|
443
|
+
? h('div', { className: 'dshMy-card dshMy-grow' },
|
|
444
|
+
h('div', { className: 'dshMy-toolbar' },
|
|
445
|
+
h('span', null, t('db') + ':'),
|
|
446
|
+
h('select', {
|
|
447
|
+
className: 'dshMy-select', value: tab.database,
|
|
448
|
+
onChange: (e) => { patchTab(tab.id, { database: e.target.value }); loadTables(e.target.value) },
|
|
449
|
+
},
|
|
450
|
+
h('option', { value: '' }, '-'),
|
|
451
|
+
databases.map((db) => h('option', { key: db, value: db }, db))
|
|
452
|
+
),
|
|
453
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnPrimary', disabled: busy || !connCfg, onClick: runSql }, t('run'))
|
|
454
|
+
),
|
|
455
|
+
h('textarea', {
|
|
456
|
+
className: 'dshMy-sql', value: tab.sql, spellCheck: false,
|
|
457
|
+
placeholder: t('sqlPlaceholder'),
|
|
458
|
+
onChange: (e) => patchTab(tab.id, { sql: e.target.value }),
|
|
459
|
+
onKeyDown: (e) => { if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { e.preventDefault(); runSql() } },
|
|
460
|
+
}),
|
|
461
|
+
tables.length
|
|
462
|
+
? h('div', { className: 'dshMy-tables' },
|
|
463
|
+
h('span', { className: 'dshMy-cardTitle' }, t('tables') + ':'),
|
|
464
|
+
tables.map((tb) =>
|
|
465
|
+
h('span', { key: tb, className: 'dshMy-chipWrap' },
|
|
466
|
+
h('button', {
|
|
467
|
+
type: 'button', className: 'dshMy-chip',
|
|
468
|
+
onClick: () => patchTab(tab.id, { sql: `SELECT * FROM \`${tb}\` LIMIT 100;` }),
|
|
469
|
+
}, tb),
|
|
470
|
+
h('button', {
|
|
471
|
+
type: 'button', className: 'dshMy-chip dshMy-chipStruct',
|
|
472
|
+
title: t('structure'),
|
|
473
|
+
onClick: () => loadStructure(tb),
|
|
474
|
+
}, '⚙')
|
|
475
|
+
)
|
|
476
|
+
)
|
|
477
|
+
)
|
|
478
|
+
: null,
|
|
479
|
+
h('div', { className: 'dshMy-toolbar dshMy-resultBar' },
|
|
480
|
+
h('span', { className: 'dshMy-cardTitle' }, t('result') + (tab.result ? ' · ' + fmt(t('rows'), { n: tab.result.rows.length }) : '')),
|
|
481
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm', disabled: !tab.result || !tab.result.columns.length, onClick: exportCsv }, t('exportCsv')),
|
|
482
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm', disabled: !tab.result || !tab.result.columns.length, onClick: exportSql }, t('exportSql'))
|
|
483
|
+
),
|
|
484
|
+
resultTable
|
|
485
|
+
)
|
|
486
|
+
: h('div', { className: 'dshMy-card dshMy-grow dshMy-empty' }, t('noTab')),
|
|
487
|
+
// structure panel: shown when a table is selected for editing
|
|
488
|
+
structTable
|
|
489
|
+
? h('div', { className: 'dshMy-card dshMy-struct' },
|
|
490
|
+
h('div', { className: 'dshMy-toolbar' },
|
|
491
|
+
h('span', { className: 'dshMy-cardTitle' }, t('structureTitle') + ': ' + structTable),
|
|
492
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm' + (structTab === 'columns' ? ' dshMy-tabOn' : ''), onClick: () => setStructTab('columns') }, t('tabColumns')),
|
|
493
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm' + (structTab === 'indexes' ? ' dshMy-tabOn' : ''), onClick: () => setStructTab('indexes') }, t('tabIndexes')),
|
|
494
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm', onClick: () => setStructTable('') }, '×')
|
|
495
|
+
),
|
|
496
|
+
structTab === 'columns'
|
|
497
|
+
? h('div', null,
|
|
498
|
+
structColumns.length
|
|
499
|
+
? h('div', { className: 'dshMy-structList' },
|
|
500
|
+
structColumns.map((c) =>
|
|
501
|
+
h('div', { key: c.field, className: 'dshMy-structRow' },
|
|
502
|
+
h('span', { className: 'dshMy-sf' }, c.field),
|
|
503
|
+
h('span', { className: 'dshMy-st' }, c.type),
|
|
504
|
+
c.key ? h('span', { className: 'dshMy-sk' }, c.key) : null,
|
|
505
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm',
|
|
506
|
+
onClick: () => setFieldForm({ name: c.field, type: (c.type || 'VARCHAR').split('(')[0].toUpperCase(), len: (c.type.match(/\(([^)]+)\)/) || [])[1] || '255', notNull: c.nullable === 'NO', def: c.default || '', comment: '', primary: c.key === 'PRI', autoInc: /auto_increment/i.test(c.extra) }),
|
|
507
|
+
}, t('modifyField')),
|
|
508
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm dshMy-del', onClick: () => dropField(c) }, t('dropField'))
|
|
509
|
+
)
|
|
510
|
+
)
|
|
511
|
+
)
|
|
512
|
+
: h('div', { className: 'dshMy-note' }, t('noStructure')),
|
|
513
|
+
h('div', { className: 'dshMy-structForm' },
|
|
514
|
+
h('input', { className: 'dshMy-input', value: fieldForm.name, placeholder: t('fieldName'), onChange: (e) => setFieldForm((f) => ({ ...f, name: e.target.value })) }),
|
|
515
|
+
h('input', { className: 'dshMy-input dshMy-typeInput', value: fieldForm.type, placeholder: t('fieldType'), onChange: (e) => setFieldForm((f) => ({ ...f, type: e.target.value })) }),
|
|
516
|
+
h('input', { className: 'dshMy-input dshMy-lenInput', value: fieldForm.len, placeholder: t('fieldLen'), onChange: (e) => setFieldForm((f) => ({ ...f, len: e.target.value })) }),
|
|
517
|
+
h('label', { className: 'dshMy-cb' }, h('input', { type: 'checkbox', checked: fieldForm.notNull, onChange: (e) => setFieldForm((f) => ({ ...f, notNull: e.target.checked })) }), t('notNull')),
|
|
518
|
+
h('label', { className: 'dshMy-cb' }, h('input', { type: 'checkbox', checked: fieldForm.primary, onChange: (e) => setFieldForm((f) => ({ ...f, primary: e.target.checked })) }), t('primary')),
|
|
519
|
+
h('label', { className: 'dshMy-cb' }, h('input', { type: 'checkbox', checked: fieldForm.autoInc, onChange: (e) => setFieldForm((f) => ({ ...f, autoInc: e.target.checked })) }), t('autoInc')),
|
|
520
|
+
h('input', { className: 'dshMy-input', value: fieldForm.def, placeholder: t('defaultValue'), onChange: (e) => setFieldForm((f) => ({ ...f, def: e.target.value })) }),
|
|
521
|
+
h('input', { className: 'dshMy-input', value: fieldForm.comment, placeholder: t('comment'), onChange: (e) => setFieldForm((f) => ({ ...f, comment: e.target.value })) }),
|
|
522
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnPrimary', disabled: busy || !fieldForm.name.trim(), onClick: addField }, '+ ' + t('addField')),
|
|
523
|
+
h('button', { type: 'button', className: 'dshMy-btn', disabled: busy || !fieldForm.name.trim(), onClick: () => modifyField(structColumns.find((c) => c.field === fieldForm.name)) }, t('modifyField'))
|
|
524
|
+
)
|
|
525
|
+
)
|
|
526
|
+
: h('div', null,
|
|
527
|
+
indexes.length
|
|
528
|
+
? h('div', { className: 'dshMy-structList' },
|
|
529
|
+
indexes.map((ix) =>
|
|
530
|
+
h('div', { key: ix.name, className: 'dshMy-structRow' },
|
|
531
|
+
h('span', { className: 'dshMy-sf' }, ix.name),
|
|
532
|
+
h('span', { className: 'dshMy-st' }, ix.columns.join(', ') + ' · ' + ix.type + (ix.unique ? ' · UNIQUE' : '')),
|
|
533
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnSm dshMy-del', onClick: () => dropIndex(ix) }, t('dropIndex'))
|
|
534
|
+
)
|
|
535
|
+
)
|
|
536
|
+
)
|
|
537
|
+
: h('div', { className: 'dshMy-note' }, t('noIndexes')),
|
|
538
|
+
h('div', { className: 'dshMy-structForm' },
|
|
539
|
+
h('input', { className: 'dshMy-input', value: indexForm.name, placeholder: t('indexName'), onChange: (e) => setIndexForm((f) => ({ ...f, name: e.target.value })) }),
|
|
540
|
+
h('input', { className: 'dshMy-input', value: indexForm.columns, placeholder: t('indexColumns'), onChange: (e) => setIndexForm((f) => ({ ...f, columns: e.target.value })) }),
|
|
541
|
+
h('label', { className: 'dshMy-cb' }, h('input', { type: 'checkbox', checked: indexForm.unique, onChange: (e) => setIndexForm((f) => ({ ...f, unique: e.target.checked })) }), t('unique')),
|
|
542
|
+
h('button', { type: 'button', className: 'dshMy-btn dshMy-btnPrimary', disabled: busy || !indexForm.name.trim() || !indexForm.columns.trim(), onClick: addIndex }, '+ ' + t('addIndex'))
|
|
543
|
+
)
|
|
544
|
+
)
|
|
545
|
+
)
|
|
546
|
+
: null
|
|
547
|
+
),
|
|
548
|
+
|
|
549
|
+
)
|
|
550
|
+
)
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function apply(ctx) {
|
|
554
|
+
ctx.effect(() => installStyles(), 'dsh-mysql-client: styles')
|
|
555
|
+
if (ctx.locale !== undefined) {
|
|
556
|
+
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'dsh-mysql-client: dictionaries')
|
|
557
|
+
t = ctx.locale.bind(NS)
|
|
558
|
+
}
|
|
559
|
+
ctx.effect(() => ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
|
|
560
|
+
name: 'sidebar.panellist', id: PANEL_ID, order: 27, label: () => t('title'), locale: NS,
|
|
561
|
+
}, SidebarIcon)), 'dsh-mysql-client: sidebar entry')
|
|
562
|
+
ctx.effect(() => ctx.slots.inject('main', () => ctx.slots.register({
|
|
563
|
+
name: 'main', key: PANEL_ID, locale: NS,
|
|
564
|
+
}, (props) => h(MysqlPanel, { ctx }))), 'dsh-mysql-client: panel')
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
function installStyles() {
|
|
568
|
+
if (typeof document === 'undefined') return () => {}
|
|
569
|
+
const existing = document.querySelector('style[data-plugin-css="' + STYLE_ID + '"]')
|
|
570
|
+
if (existing) return () => {}
|
|
571
|
+
const style = document.createElement('style')
|
|
572
|
+
style.dataset.plugin = NS
|
|
573
|
+
style.dataset.pluginCss = STYLE_ID
|
|
574
|
+
style.textContent = `
|
|
575
|
+
.dshMy-root{display:flex;flex-direction:column;height:100%;box-sizing:border-box;padding:14px 18px 18px;gap:10px;overflow:hidden;color:var(--dsw-alias-label-primary);background:var(--dsw-alias-bg-base)}
|
|
576
|
+
.dshMy-head{display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex:0 0 auto}
|
|
577
|
+
.dshMy-title{font-size:20px;font-weight:700;line-height:1.3}
|
|
578
|
+
.dshMy-sub{font-size:12px;color:var(--dsw-alias-label-secondary);margin-top:3px}
|
|
579
|
+
.dshMy-back{display:inline-flex;align-items:center;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;padding:5px 11px;border-radius:8px;cursor:pointer;font-family:inherit;white-space:nowrap}
|
|
580
|
+
.dshMy-err{font-size:11px;color:var(--dsw-alias-state-error-primary);flex:0 0 auto}
|
|
581
|
+
.dshMy-cols{display:grid;grid-template-columns:minmax(240px,320px) minmax(0,1fr);gap:12px;flex:1 1 auto;min-height:0}
|
|
582
|
+
.dshMy-col{display:flex;flex-direction:column;gap:10px;min-height:0;overflow-y:auto}
|
|
583
|
+
.dshMy-main{overflow-y:auto}
|
|
584
|
+
.dshMy-card{padding:12px;border:1px solid var(--dsw-alias-border-l1);border-radius:10px;background:var(--dsw-alias-bg-layer-1);display:flex;flex-direction:column;gap:8px}
|
|
585
|
+
.dshMy-grow{flex:1 1 auto;min-height:0}
|
|
586
|
+
.dshMy-empty{align-items:center;justify-content:center;color:var(--dsw-alias-label-secondary);font-size:13px}
|
|
587
|
+
.dshMy-cardTitle{font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}
|
|
588
|
+
.dshMy-note{font-size:11px;color:var(--dsw-alias-label-secondary);line-height:1.5}
|
|
589
|
+
.dshMy-err{font-size:11px;color:var(--dsw-alias-state-error-primary)}
|
|
590
|
+
.dshMy-btn{padding:7px 11px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font-size:12px;cursor:pointer;font-family:inherit;white-space:nowrap}
|
|
591
|
+
.dshMy-btn:hover{border-color:var(--dsw-alias-brand-primary)}
|
|
592
|
+
.dshMy-btn:disabled{opacity:.45;cursor:not-allowed}
|
|
593
|
+
.dshMy-btnPrimary{background:#e48b2b;color:#fff;border-color:transparent;font-weight:600}
|
|
594
|
+
.dshMy-del{color:var(--dsw-alias-state-error-primary)}
|
|
595
|
+
.dshMy-connList{display:flex;flex-direction:column;gap:4px}
|
|
596
|
+
.dshMy-conn{display:flex;align-items:center;gap:6px;padding:7px 8px;border-radius:7px;border:1px solid var(--dsw-alias-border-l1);cursor:pointer;font-size:12px;flex-wrap:wrap}
|
|
597
|
+
.dshMy-connOn{border-color:#e48b2b;background:var(--dsw-alias-bg-layer-2)}
|
|
598
|
+
.dshMy-name{font-weight:600;flex:1 1 auto}
|
|
599
|
+
.dshMy-addr{font-size:10px;color:var(--dsw-alias-label-secondary)}
|
|
600
|
+
.dshMy-mini{border:0;background:transparent;color:var(--dsw-alias-label-secondary);font-size:11px;cursor:pointer;padding:0 3px;font-family:inherit}
|
|
601
|
+
.dshMy-form{display:flex;flex-direction:column;gap:7px}
|
|
602
|
+
.dshMy-field{display:flex;flex-direction:column;gap:3px;font-size:11px;color:var(--dsw-alias-label-secondary)}
|
|
603
|
+
.dshMy-input,.dshMy-select{padding:6px 9px;border-radius:7px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-size:12px;outline:none;font-family:inherit;min-width:0}
|
|
604
|
+
.dshMy-input:focus,.dshMy-select:focus{border-color:var(--dsw-alias-brand-primary)}
|
|
605
|
+
.dshMy-tabs{display:flex;flex-direction:column;gap:3px;max-height:160px;overflow-y:auto}
|
|
606
|
+
.dshMy-tab{display:flex;align-items:center;gap:6px;padding:6px 8px;border-radius:7px;background:var(--dsw-alias-bg-layer-2);font-size:12px;cursor:pointer}
|
|
607
|
+
.dshMy-tabOn{outline:1px solid #e48b2b}
|
|
608
|
+
.dshMy-tab span{flex:1 1 auto}
|
|
609
|
+
.dshMy-toolbar{display:flex;align-items:center;gap:7px;font-size:12px;flex-wrap:wrap}
|
|
610
|
+
.dshMy-sql{flex:0 0 auto;height:130px;width:100%;box-sizing:border-box;resize:vertical;padding:10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-family:ui-monospace,monospace;font-size:12px;line-height:1.5;outline:none}
|
|
611
|
+
.dshMy-sql:focus{border-color:var(--dsw-alias-brand-primary)}
|
|
612
|
+
.dshMy-tables{display:flex;gap:5px;flex-wrap:wrap;align-items:center}
|
|
613
|
+
.dshMy-chip{border:1px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-base);color:var(--dsw-alias-label-primary);font-size:11px;padding:3px 8px;border-radius:12px;cursor:pointer;font-family:inherit}
|
|
614
|
+
.dshMy-tableWrap{flex:1 1 auto;min-height:120px;overflow:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-base)}
|
|
615
|
+
.dshMy-table{border-collapse:collapse;width:100%;font-size:11.5px;font-family:ui-monospace,monospace}
|
|
616
|
+
.dshMy-table th,.dshMy-table td{padding:5px 8px;text-align:left;border-bottom:1px solid var(--dsw-alias-border-l1);white-space:nowrap;max-width:280px;overflow:hidden;text-overflow:ellipsis}
|
|
617
|
+
.dshMy-table th{position:sticky;top:0;background:var(--dsw-alias-bg-layer-2);font-weight:600;z-index:1}
|
|
618
|
+
.dshMy-idx{color:var(--dsw-alias-label-secondary);width:34px}
|
|
619
|
+
.dshMy-btnSm{padding:4px 8px;font-size:11px}
|
|
620
|
+
.dshMy-resultBar{justify-content:flex-start}
|
|
621
|
+
.dshMy-chipWrap{display:inline-flex;align-items:center;gap:2px}
|
|
622
|
+
.dshMy-chipStruct{padding:3px 6px;border-radius:8px}
|
|
623
|
+
.dshMy-struct{flex:0 0 auto;min-height:180px;max-height:360px;overflow-y:auto}
|
|
624
|
+
.dshMy-structList{display:flex;flex-direction:column;gap:3px;max-height:200px;overflow-y:auto;border:1px solid var(--dsw-alias-border-l1);border-radius:8px;background:var(--dsw-alias-bg-base);padding:4px}
|
|
625
|
+
.dshMy-structRow{display:flex;align-items:center;gap:8px;padding:4px 6px;border-radius:6px;background:var(--dsw-alias-bg-layer-2);font-size:11.5px;flex-wrap:nowrap;min-width:0}
|
|
626
|
+
.dshMy-sf{font-weight:600;min-width:100px;max-width:160px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:0 1 auto}
|
|
627
|
+
.dshMy-st{color:var(--dsw-alias-label-secondary);flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
628
|
+
.dshMy-sk{flex:0 0 auto;color:var(--dsw-alias-brand-primary);font-size:10px}
|
|
629
|
+
.dshMy-structRow .dshMy-btn{flex:0 0 auto}
|
|
630
|
+
.dshMy-sk{color:var(--dsw-alias-brand-primary);font-size:10px}
|
|
631
|
+
.dshMy-structForm{display:grid;grid-template-columns:repeat(auto-fill,minmax(130px,1fr));gap:6px;align-items:center;padding-top:6px;border-top:1px solid var(--dsw-alias-border-l1)}
|
|
632
|
+
.dshMy-cb{display:flex;align-items:center;gap:4px;font-size:11px;color:var(--dsw-alias-label-secondary)}
|
|
633
|
+
.dshMy-cb input{accent-color:var(--dsw-alias-brand-primary)}
|
|
634
|
+
@media(max-width:900px){.dshMy-cols{grid-template-columns:1fr;overflow-y:auto}.dshMy-col{overflow:visible}}
|
|
635
|
+
`
|
|
636
|
+
document.head.appendChild(style)
|
|
637
|
+
return () => { style.remove() }
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
return { inject: ['slots', 'locale'], apply }
|
|
641
|
+
},
|
|
642
|
+
})
|
package/cordis.patch.yml
ADDED
package/icon.svg
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|
2
|
+
<ellipse cx="32" cy="18" rx="26" ry="10" fill="#e48b2b"/>
|
|
3
|
+
<path d="M6 18v28c0 5.5 11.6 10 26 10s26-4.5 26-10V18" fill="#c96a1e"/>
|
|
4
|
+
<path d="M6 32c0 5.5 11.6 10 26 10s26-4.5 26-10" fill="none" stroke="#a85111" stroke-width="2"/>
|
|
5
|
+
<ellipse cx="32" cy="18" rx="26" ry="10" fill="none" stroke="#a85111" stroke-width="2"/>
|
|
6
|
+
<text x="32" y="23" text-anchor="middle" font-family="sans-serif" font-size="11" font-weight="700" fill="#fff">MySQL</text>
|
|
7
|
+
</svg>
|
package/index.js
ADDED
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the MySQL client bundle.
|
|
3
|
+
*
|
|
4
|
+
* Runs the mysql CLI via child_process for each operation. Connection details
|
|
5
|
+
* come per request from the Client; nothing is persisted on the Host. SQL is
|
|
6
|
+
* passed as a single argv value to `-e` so it is never interpreted by a shell.
|
|
7
|
+
*/
|
|
8
|
+
import { execFile } from 'node:child_process'
|
|
9
|
+
import { promisify } from 'node:util'
|
|
10
|
+
|
|
11
|
+
export const name = 'dsh-mysql-client'
|
|
12
|
+
export const inject = ['connection']
|
|
13
|
+
|
|
14
|
+
const execFileAsync = promisify(execFile)
|
|
15
|
+
const API = '/api/dsh-mysql-client'
|
|
16
|
+
const CLI = process.env.MYSQL_CLI_PATH || '/usr/local/mysql/bin/mysql'
|
|
17
|
+
const TIMEOUT = 15000
|
|
18
|
+
const MAX_ROWS = 500
|
|
19
|
+
|
|
20
|
+
class SqlError extends Error {
|
|
21
|
+
constructor(message, status = 400) { super(message); this.status = status }
|
|
22
|
+
}
|
|
23
|
+
function json(value, status = 200) {
|
|
24
|
+
return Response.json(value, { status, headers: { 'cache-control': 'no-store' } })
|
|
25
|
+
}
|
|
26
|
+
function failure(error, fallback) {
|
|
27
|
+
const message = error instanceof SqlError ? error.message : fallback
|
|
28
|
+
const status = error instanceof SqlError ? error.status : 500
|
|
29
|
+
return json({ error: message }, status)
|
|
30
|
+
}
|
|
31
|
+
function route(path, methods, fetch) {
|
|
32
|
+
return { path: `${API}/${path}`, methods, requestBody: 'buffered', fetch }
|
|
33
|
+
}
|
|
34
|
+
async function readBody(request) {
|
|
35
|
+
try { return JSON.parse((await request.text()) || '{}') }
|
|
36
|
+
catch (_) { throw new SqlError('请求内容不是合法的 JSON。') }
|
|
37
|
+
}
|
|
38
|
+
function connArgs(cfg) {
|
|
39
|
+
const args = []
|
|
40
|
+
if (cfg.host) args.push('-h', String(cfg.host))
|
|
41
|
+
if (cfg.port) args.push('-P', String(cfg.port))
|
|
42
|
+
if (cfg.user) args.push('-u', String(cfg.user))
|
|
43
|
+
if (cfg.password) args.push('-p' + String(cfg.password)) // mysql requires -ppass (no space)
|
|
44
|
+
return args
|
|
45
|
+
}
|
|
46
|
+
// mysql prints an unavoidable warning to stderr when a password is supplied
|
|
47
|
+
// on the CLI; strip these noise lines so they never surface as errors/messages.
|
|
48
|
+
function cleanWarning(text) {
|
|
49
|
+
return String(text == null ? '' : text)
|
|
50
|
+
.split('\n')
|
|
51
|
+
.filter((line) => !/Using a password on the command line interface can be insecure/i.test(line))
|
|
52
|
+
.join('\n')
|
|
53
|
+
.trim()
|
|
54
|
+
}
|
|
55
|
+
// Run SQL via mysql --batch --raw -e "<sql>". Returns stdout text.
|
|
56
|
+
async function runSql(cfg, database, sql) {
|
|
57
|
+
const args = [...connArgs(cfg), '--batch', '--raw']
|
|
58
|
+
if (database) args.push(String(database))
|
|
59
|
+
args.push('-e', String(sql))
|
|
60
|
+
try {
|
|
61
|
+
const { stdout, stderr } = await execFileAsync(CLI, args, { timeout: TIMEOUT, maxBuffer: 16 * 1024 * 1024 })
|
|
62
|
+
return { out: stdout, err: cleanWarning(stderr) }
|
|
63
|
+
} catch (error) {
|
|
64
|
+
const msg = (error && error.message) || String(error)
|
|
65
|
+
if (msg.includes('ENOENT')) throw new SqlError('找不到 mysql 客户端,请确认路径。', 500)
|
|
66
|
+
if (msg.includes('timed out') || msg.includes('ETIMEDOUT')) throw new SqlError('查询超时。', 504)
|
|
67
|
+
const detail = (error && error.stderr) ? cleanWarning(error.stderr) : msg
|
|
68
|
+
throw new SqlError(detail || 'SQL 执行失败。')
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
// Parse mysql --batch output (tab-separated, first line = headers).
|
|
72
|
+
function parseTable(text) {
|
|
73
|
+
const lines = String(text || '').replace(/\r/g, '').split('\n').filter((l, i, arr) => !(i === arr.length - 1 && l === ''))
|
|
74
|
+
if (!lines.length) return { columns: [], rows: [], truncated: false, message: '' }
|
|
75
|
+
// A single line without tabs is a status message (e.g. "Query OK, 1 row affected").
|
|
76
|
+
// Anything with multiple lines is a result set — even a single-column one
|
|
77
|
+
// such as SHOW DATABASES / SHOW TABLES, whose lines contain no tabs.
|
|
78
|
+
const hasTab = lines[0].includes('\t')
|
|
79
|
+
if (lines.length === 1 && !hasTab) return { columns: [], rows: [], truncated: false, message: lines[0] }
|
|
80
|
+
const split = (l) => l.split('\t').map((v) => v === 'NULL' ? null : v)
|
|
81
|
+
const columns = split(lines[0])
|
|
82
|
+
const all = lines.slice(1).map(split)
|
|
83
|
+
const truncated = all.length > MAX_ROWS
|
|
84
|
+
const rows = truncated ? all.slice(0, MAX_ROWS) : all
|
|
85
|
+
return { columns, rows, truncated, message: '' }
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function apply(ctx) {
|
|
89
|
+
ctx.effect(() => {
|
|
90
|
+
const disposers = []
|
|
91
|
+
const register = (entry) => {
|
|
92
|
+
try {
|
|
93
|
+
const dispose = ctx.connection.fetch.register(entry)
|
|
94
|
+
if (typeof dispose === 'function') disposers.push(dispose)
|
|
95
|
+
} catch (error) {
|
|
96
|
+
console.warn(`[dsh-mysql-client] route ${entry.path} rejected: ${(error && error.message) || error}`)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Test connection with SELECT 1.
|
|
101
|
+
register(route('test', ['POST'], async (request) => {
|
|
102
|
+
try {
|
|
103
|
+
const body = await readBody(request)
|
|
104
|
+
const { out } = await runSql(body.connection || '', '', 'SELECT 1 AS ok')
|
|
105
|
+
const t = parseTable(out)
|
|
106
|
+
return json({ ok: t.rows.length > 0 && t.rows[0][0] === '1', columns: t.columns, rows: t.rows })
|
|
107
|
+
} catch (error) { return failure(error, '连接测试失败。') }
|
|
108
|
+
}))
|
|
109
|
+
|
|
110
|
+
// List databases.
|
|
111
|
+
register(route('databases', ['POST'], async (request) => {
|
|
112
|
+
try {
|
|
113
|
+
const body = await readBody(request)
|
|
114
|
+
const { out } = await runSql(body.connection || '', '', 'SHOW DATABASES')
|
|
115
|
+
const t = parseTable(out)
|
|
116
|
+
const databases = t.rows.map((r) => r[0]).filter(Boolean)
|
|
117
|
+
return json({ databases })
|
|
118
|
+
} catch (error) { return failure(error, '无法读取数据库列表。') }
|
|
119
|
+
}))
|
|
120
|
+
|
|
121
|
+
// List tables of a database.
|
|
122
|
+
register(route('tables', ['POST'], async (request) => {
|
|
123
|
+
try {
|
|
124
|
+
const body = await readBody(request)
|
|
125
|
+
const db = body.database
|
|
126
|
+
if (typeof db !== 'string' || !db) throw new SqlError('缺少数据库名。')
|
|
127
|
+
const { out } = await runSql(body.connection || '', db, 'SHOW TABLES')
|
|
128
|
+
const t = parseTable(out)
|
|
129
|
+
return json({ tables: t.rows.map((r) => r[0]).filter(Boolean) })
|
|
130
|
+
} catch (error) { return failure(error, '无法读取数据表。') }
|
|
131
|
+
}))
|
|
132
|
+
|
|
133
|
+
// Describe a table's columns.
|
|
134
|
+
register(route('describe', ['POST'], async (request) => {
|
|
135
|
+
try {
|
|
136
|
+
const body = await readBody(request)
|
|
137
|
+
const db = body.database
|
|
138
|
+
const table = body.table
|
|
139
|
+
if (typeof db !== 'string' || !db) throw new SqlError('缺少数据库名。')
|
|
140
|
+
if (typeof table !== 'string' || !table) throw new SqlError('缺少表名。')
|
|
141
|
+
const safeDb = '`' + db.replace(/`/g, '``') + '`'
|
|
142
|
+
const safeTable = '`' + table.replace(/`/g, '``') + '`'
|
|
143
|
+
const { out } = await runSql(body.connection || '', db, 'DESCRIBE ' + safeDb + '.' + safeTable)
|
|
144
|
+
const t = parseTable(out)
|
|
145
|
+
// DESCRIBE columns: Field, Type, Null, Key, Default, Extra
|
|
146
|
+
const columns = t.rows.map((r) => ({
|
|
147
|
+
field: r[0] || '', type: r[1] || '', nullable: r[2] || '',
|
|
148
|
+
key: r[3] || '', default: r[4] == null ? '' : String(r[4]), extra: r[5] || '',
|
|
149
|
+
}))
|
|
150
|
+
return json({ columns })
|
|
151
|
+
} catch (error) { return failure(error, '无法读取表结构。') }
|
|
152
|
+
}))
|
|
153
|
+
|
|
154
|
+
// List indexes of a table: SHOW INDEX (one row per indexed column).
|
|
155
|
+
register(route('indexes', ['POST'], async (request) => {
|
|
156
|
+
try {
|
|
157
|
+
const body = await readBody(request)
|
|
158
|
+
const db = body.database
|
|
159
|
+
const table = body.table
|
|
160
|
+
if (typeof db !== 'string' || !db) throw new SqlError('缺少数据库名。')
|
|
161
|
+
if (typeof table !== 'string' || !table) throw new SqlError('缺少表名。')
|
|
162
|
+
const safeDb = '`' + db.replace(/`/g, '``') + '`'
|
|
163
|
+
const safeTable = '`' + table.replace(/`/g, '``') + '`'
|
|
164
|
+
const { out } = await runSql(body.connection || '', db, 'SHOW INDEX FROM ' + safeDb + '.' + safeTable)
|
|
165
|
+
const t = parseTable(out)
|
|
166
|
+
// SHOW INDEX columns: Table, Non_unique, Key_name, Seq_in_index,
|
|
167
|
+
// Column_name, Collation, Cardinality, Sub_part, Packed, Null, Index_type, Comment, Index_comment
|
|
168
|
+
const map = {}
|
|
169
|
+
for (const r of t.rows) {
|
|
170
|
+
const name = r[2] || ''
|
|
171
|
+
if (!name) continue
|
|
172
|
+
if (!map[name]) map[name] = {
|
|
173
|
+
name, unique: String(r[1]) === '0', type: r[10] || 'BTREE',
|
|
174
|
+
columns: [], comment: r[12] || '',
|
|
175
|
+
}
|
|
176
|
+
map[name].columns.push({ seq: Number(r[3]) || 0, column: r[4] || '', subPart: r[7] || '' })
|
|
177
|
+
}
|
|
178
|
+
const indexes = Object.values(map).map((ix) => ({
|
|
179
|
+
...ix, columns: ix.columns.sort((a, b) => a.seq - b.seq).map((c) => c.column),
|
|
180
|
+
}))
|
|
181
|
+
return json({ indexes })
|
|
182
|
+
} catch (error) { return failure(error, '无法读取索引。') }
|
|
183
|
+
}))
|
|
184
|
+
|
|
185
|
+
// Execute arbitrary SQL against an optional database.
|
|
186
|
+
register(route('query', ['POST'], async (request) => {
|
|
187
|
+
try {
|
|
188
|
+
const body = await readBody(request)
|
|
189
|
+
const sql = typeof body.sql === 'string' ? body.sql.trim() : ''
|
|
190
|
+
if (!sql) throw new SqlError('请输入 SQL。')
|
|
191
|
+
const { out, err } = await runSql(body.connection || '', body.database || '', sql)
|
|
192
|
+
const table = parseTable(out)
|
|
193
|
+
return json({
|
|
194
|
+
columns: table.columns, rows: table.rows, truncated: table.truncated,
|
|
195
|
+
message: table.message || (err ? String(err).trim() : '') || '执行成功',
|
|
196
|
+
affectedRows: null,
|
|
197
|
+
})
|
|
198
|
+
} catch (error) { return failure(error, 'SQL 执行失败。') }
|
|
199
|
+
}))
|
|
200
|
+
|
|
201
|
+
return () => {
|
|
202
|
+
for (const dispose of disposers) {
|
|
203
|
+
try {
|
|
204
|
+
const result = dispose()
|
|
205
|
+
if (result && typeof result.then === 'function') result.catch(() => {})
|
|
206
|
+
} catch (_) {}
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}, 'dsh-mysql-client: routes')
|
|
210
|
+
}
|
package/locale/en.json
ADDED
package/locale/zh.json
ADDED
package/package.json
CHANGED
|
@@ -1,6 +1,37 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@oakzhong/dsh-mysql-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"private": false,
|
|
5
|
+
"publishConfig": {
|
|
6
|
+
"access": "public"
|
|
7
|
+
},
|
|
8
|
+
"type": "module",
|
|
9
|
+
"description": "A MySQL client with connection management, query tabs and SQL execution.",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": "./index.js",
|
|
12
|
+
"./client": "./client.js",
|
|
13
|
+
"./locale/*.json": "./locale/*.json",
|
|
14
|
+
"./icon": "./icon.svg"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"index.js",
|
|
18
|
+
"client.js",
|
|
19
|
+
"cordis.patch.yml",
|
|
20
|
+
"locale/*.json",
|
|
21
|
+
"icon.svg",
|
|
22
|
+
"README.md",
|
|
23
|
+
"README.zh.md"
|
|
24
|
+
],
|
|
25
|
+
"dsh": {
|
|
26
|
+
"bundle": {
|
|
27
|
+
"patch": "./cordis.patch.yml"
|
|
28
|
+
},
|
|
29
|
+
"client": {
|
|
30
|
+
"platform": "web",
|
|
31
|
+
"immediately": true,
|
|
32
|
+
"inject": [
|
|
33
|
+
"@deepseek-ai/dsh-client-locale"
|
|
34
|
+
]
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
}
|