@carllee1983/dbcli 1.19.1 → 1.20.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/CHANGELOG.md +29 -0
- package/README.md +42 -0
- package/README.zh-TW.md +40 -0
- package/assets/SKILL.md +39 -0
- package/assets/SKILL.zh-TW.md +392 -0
- package/assets/reference.md +87 -0
- package/dist/cli.mjs +2302 -239
- package/package.json +2 -1
package/CHANGELOG.md
CHANGED
|
@@ -6,6 +6,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
8
|
|
|
9
|
+
## [1.20.0] - 2026-05-17
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- **Agent-facing Audit Log**: every db-touching command writes a structured JSONL entry to `.dbcli/audit/<connection>.jsonl`. Entry shape locked as a contract test (`tests/integration/audit-contract.test.ts`) covering `ts` / `session_id` / `engine` / `command` / `side_effect_tier` / `target` / `success` / `recovery_ref` / `redacted_sql`. Redaction sourced from `tests/helpers/sensitive-output.ts` (single source of truth).
|
|
14
|
+
- `dbcli audit tail` / `audit show` / `audit clear` / `audit health` subcommands with `--n`, `--all`, `--for-agent`, `--brief`, `--recovery-ref <id>`, `--format table|json`, `--yes` flags. JSON output is a flat array suitable for agent direct consumption (CLI-01..06).
|
|
15
|
+
- `dbcli audit tail --all` cross-connection merged view; `audit show --recovery-ref <id>` bi-directional lookup; `audit health` reports writer state, lock state, rotation cap usage.
|
|
16
|
+
- Recovery envelope bi-directional linkage: audit entry `recovery_ref` points at `.dbcli/last-recovery.json`; envelope's new `audit_ref` points back at the audit entry id.
|
|
17
|
+
- `inspect` / `guide` / `recover` / `recover --apply` `--for-agent` JSON output embeds `audit_recent: AuditEntryBrief[]` (last 5 entries) for immediate cross-session context.
|
|
18
|
+
- `dbcli skill --install <platform> --lang en|zh-TW` (default `en`) to install Traditional Chinese SKILL.md content on agent platforms; target filename remains `SKILL.md` regardless of source.
|
|
19
|
+
- New `assets/SKILL.zh-TW.md` — full Traditional Chinese translation of `assets/SKILL.md`, including the new `## Audit Log 使用` section.
|
|
20
|
+
- New `## Audit Log usage` section in `assets/SKILL.md` (session handoff + forensics scenarios).
|
|
21
|
+
- New `### audit` subcommand block in `assets/reference.md` documenting all 4 subcommands with flag tables.
|
|
22
|
+
- `docs/feature-matrix.md` gains an `audit` row (engine-independent, N/A across all 6 engines) and the Side-effect tiers table examples now include `audit tail` / `audit show` / `audit health` (`readonly`) and `audit clear` (`local-write`).
|
|
23
|
+
- `scripts/release-check.sh` step `8/8 doc-presence` — release-blocking shell-grep check that the feature-matrix `audit` row and the matching `CHANGELOG.md ## [<version>]` heading both exist.
|
|
24
|
+
|
|
25
|
+
### Changed
|
|
26
|
+
|
|
27
|
+
- **Default-on, upgrade impact:** `audit.enabled = true` by default. Existing projects will begin creating `.dbcli/audit/<connection>.jsonl` on first command after upgrading. Set `audit.enabled = false` in `.dbcli` to opt out. The audit directory is gitignored by default; entries are metadata-only (D3) — never raw SQL bodies, `--param` values, or result cell contents. (D1)
|
|
28
|
+
- `inspect` / `guide` / `recover` / `recover --apply` agent JSON output adds an `audit_recent` field (additive; shape stable; not a breaking change). v1.19.x consumers ignore the field.
|
|
29
|
+
- _Known limitation (Phase 23-04 follow-up):_ Audit log captures `query`, `inspect`, and diagnostic-surface commands in v1.20.0; coverage for `insert / update / delete / export / q / schema` failure paths is tracked as Phase 23-04 follow-up (see `.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md`). Recovery envelope linkage from the envelope side is unaffected — those commands continue to emit `.dbcli/last-recovery.json` envelopes; only the `audit_ref` back-pointer is missing in v1.20.0.
|
|
30
|
+
|
|
31
|
+
### Internal
|
|
32
|
+
|
|
33
|
+
- New modules under `src/core/audit/`: `logger.ts`, `lock.ts`, `rotation.ts`, `reader.ts`, `recent.ts`, `session-id.ts`, `types.ts`, `integration-helper.ts`.
|
|
34
|
+
- New contract / integration tests: `tests/integration/audit-contract.test.ts`, `tests/integration/audit-envelope.test.ts`, `tests/integration/recovery-audit-link.test.ts` (J1 asymmetry guard).
|
|
35
|
+
- `scripts/release-check.sh` is now 8 steps (was 7); CONTRIBUTING.md §Release Process and `docs/feature-matrix.md` §Required CI validation block updated to match.
|
|
36
|
+
- `src/commands/skill.ts` adds a `resolveSkillSource(lang)` selector and `--lang en|zh-TW` commander option via `new Option(...).choices(['en','zh-TW']).default('en')`. `getInstallPath()` is unchanged (target filename stays `SKILL.md`).
|
|
37
|
+
|
|
9
38
|
## [1.19.1] - 2026-05-14
|
|
10
39
|
|
|
11
40
|
### Changed
|
package/README.md
CHANGED
|
@@ -1253,6 +1253,48 @@ If an installed primary skill file is older than the bundled `assets/SKILL.md`,
|
|
|
1253
1253
|
|
|
1254
1254
|
---
|
|
1255
1255
|
|
|
1256
|
+
## Audit Log
|
|
1257
|
+
|
|
1258
|
+
> **Default ON since v1.20.0.** Existing projects will begin creating
|
|
1259
|
+
> `.dbcli/audit/<connection>.jsonl` on first command after upgrading.
|
|
1260
|
+
> Set `audit.enabled = false` in `.dbcli` to opt out.
|
|
1261
|
+
|
|
1262
|
+
Every command that touches a database writes a structured JSONL entry to
|
|
1263
|
+
`.dbcli/audit/<connection>.jsonl`. Inspect the recent history with:
|
|
1264
|
+
|
|
1265
|
+
```bash
|
|
1266
|
+
dbcli audit tail --n 10 # last 10 entries on current connection
|
|
1267
|
+
dbcli audit tail --all --for-agent # cross-connection JSON envelope
|
|
1268
|
+
dbcli audit show <uuid-prefix> # full entry by id prefix (>=4 chars)
|
|
1269
|
+
dbcli audit show --recovery-ref <uuid> # find entry that emitted a recovery envelope
|
|
1270
|
+
dbcli audit health # writer state, rotation %, last write status
|
|
1271
|
+
dbcli audit clear # erase audit log for current connection (prompts y/N)
|
|
1272
|
+
```
|
|
1273
|
+
|
|
1274
|
+
Entries are **metadata-only** — never raw SQL bodies, never `--param` values,
|
|
1275
|
+
never result cell contents. Redaction comes from the same source as v1.19.1's
|
|
1276
|
+
agent-facing JSON contracts (`tests/helpers/sensitive-output.ts`).
|
|
1277
|
+
|
|
1278
|
+
**Recovery envelope linkage.** When a `--recovery` failure writes
|
|
1279
|
+
`.dbcli/last-recovery.json`, the audit entry's `recovery_ref` field and the
|
|
1280
|
+
envelope's `audit_ref` field reference each other. Agents can pivot between
|
|
1281
|
+
audit history and recovery envelopes from either direction. The
|
|
1282
|
+
`inspect` / `guide` / `recover` / `recover --apply` JSON output embeds
|
|
1283
|
+
`audit_recent: AuditEntryBrief[]` (last 5 entries) so a fresh session has
|
|
1284
|
+
immediate context.
|
|
1285
|
+
|
|
1286
|
+
**Known limitation (v1.20.0):** Bi-directional linkage is wired for `query`,
|
|
1287
|
+
`inspect`, and diagnostic surfaces. The DML commands `insert / update / delete /
|
|
1288
|
+
export / q / schema` emit single-direction recovery envelopes (no `audit_ref`)
|
|
1289
|
+
in v1.20.0; full coverage is tracked as Phase 23-04 follow-up. See
|
|
1290
|
+
[`.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md`](./.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md)
|
|
1291
|
+
for the full matrix.
|
|
1292
|
+
|
|
1293
|
+
For deeper agent workflows (session handoff, forensics walk-through), see
|
|
1294
|
+
[`assets/SKILL.md`](./assets/SKILL.md) §Audit Log usage.
|
|
1295
|
+
|
|
1296
|
+
---
|
|
1297
|
+
|
|
1256
1298
|
## Troubleshooting
|
|
1257
1299
|
|
|
1258
1300
|
### Connection Issues
|
package/README.zh-TW.md
CHANGED
|
@@ -1149,6 +1149,46 @@ dbcli skill --install gemini
|
|
|
1149
1149
|
|
|
1150
1150
|
---
|
|
1151
1151
|
|
|
1152
|
+
## 稽核日誌 (Audit Log)
|
|
1153
|
+
|
|
1154
|
+
> **自 v1.20.0 起預設啟用。** 既有專案在升級後第一次執行 dbcli 指令時,將會開始在
|
|
1155
|
+
> `.dbcli/audit/<connection>.jsonl` 寫入結構化稽核紀錄。
|
|
1156
|
+
> 如需停用,請在 `.dbcli` 設定 `audit.enabled = false`。
|
|
1157
|
+
|
|
1158
|
+
每個接觸資料庫的指令都會寫入一筆結構化 JSONL 紀錄至
|
|
1159
|
+
`.dbcli/audit/<connection>.jsonl`。可用以下指令檢視歷史:
|
|
1160
|
+
|
|
1161
|
+
```bash
|
|
1162
|
+
dbcli audit tail --n 10 # 當前連線最近 10 筆
|
|
1163
|
+
dbcli audit tail --all --for-agent # 跨連線合併(agent JSON envelope)
|
|
1164
|
+
dbcli audit show <uuid-prefix> # 完整單筆 entry(>=4 字元 prefix)
|
|
1165
|
+
dbcli audit show --recovery-ref <uuid> # 反向找出觸發 envelope 的 entry
|
|
1166
|
+
dbcli audit health # writer 狀態、rotation 用量、最近寫入結果
|
|
1167
|
+
dbcli audit clear # 清空當前連線的 audit log(互動確認)
|
|
1168
|
+
```
|
|
1169
|
+
|
|
1170
|
+
Entries 為 **metadata-only** — 不含原始 SQL body、不含 `--param` 值、不含 result cell。
|
|
1171
|
+
Redaction 沿用 v1.19.1 agent-facing JSON 合約的同一來源
|
|
1172
|
+
(`tests/helpers/sensitive-output.ts`),不重複定義。
|
|
1173
|
+
|
|
1174
|
+
**與 recovery envelope 的雙向連結。** 當 `--recovery` 路徑失敗寫入
|
|
1175
|
+
`.dbcli/last-recovery.json` 時,audit entry 的 `recovery_ref` 與 envelope 的
|
|
1176
|
+
`audit_ref` 互為指標。Agent 可從任一側跳到另一側。`inspect` / `guide` / `recover` /
|
|
1177
|
+
`recover --apply` 的 JSON 輸出會內嵌 `audit_recent: AuditEntryBrief[]`(最近 5 筆),
|
|
1178
|
+
讓新 session 立即擁有歷史脈絡。
|
|
1179
|
+
|
|
1180
|
+
**已知限制(v1.20.0):** Bi-directional 連結僅在 `query` / `inspect` / diagnostic
|
|
1181
|
+
表面寫入;DML 指令 `insert / update / delete / export / q / schema` 失敗時
|
|
1182
|
+
emit 的 envelope 暫未含 `audit_ref`,追蹤於 Phase 23-04 follow-up。完整對照表見
|
|
1183
|
+
[`.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md`](./.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md)。
|
|
1184
|
+
Recovery envelope 自身的 linkage 不受影響。
|
|
1185
|
+
|
|
1186
|
+
進階 agent 工作流程(session handoff、forensics walk-through)詳見
|
|
1187
|
+
[`assets/SKILL.md`](./assets/SKILL.md) §Audit Log usage(英文)或
|
|
1188
|
+
[`assets/SKILL.zh-TW.md`](./assets/SKILL.zh-TW.md) §Audit Log 使用。
|
|
1189
|
+
|
|
1190
|
+
---
|
|
1191
|
+
|
|
1152
1192
|
## 故障排除
|
|
1153
1193
|
|
|
1154
1194
|
### 連線問題
|
package/assets/SKILL.md
CHANGED
|
@@ -71,6 +71,45 @@ Tasks live under `assets/tasks/` (builtin), `.dbcli-shared/tasks/` (shared), and
|
|
|
71
71
|
|
|
72
72
|
Full flags, per-command copy-paste blocks, `migrate` DDL, interactive `shell`, and MongoDB/Redis/ES walkthroughs are in [reference.md](reference.md) (installed next to this file).
|
|
73
73
|
|
|
74
|
+
## Audit Log usage
|
|
75
|
+
|
|
76
|
+
Use the audit log when you need cross-session history or forensics on what dbcli
|
|
77
|
+
has done on this database, rather than re-querying live DB state from scratch.
|
|
78
|
+
|
|
79
|
+
**Scenario 1 — Session handoff (picking up where another agent left off):**
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
dbcli audit tail --for-agent --n 10 # last 10 entries as JSON envelope
|
|
83
|
+
dbcli audit tail --all --for-agent --n 20 # cross-connection merged view (D4)
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Returns an agent-facing JSON envelope with `session_id` / `engine` / `command` /
|
|
87
|
+
`target` / `success` per entry. Metadata-only by design — never raw SQL bodies,
|
|
88
|
+
`--param` values, or result cell contents (D3 lock).
|
|
89
|
+
|
|
90
|
+
**Scenario 2 — Forensics (reconstructing a failure):**
|
|
91
|
+
|
|
92
|
+
```bash
|
|
93
|
+
dbcli recover --format json # inspect audit_recent embed + recovery_ref
|
|
94
|
+
dbcli audit show <id-prefix> # full entry by id prefix (>=4 chars)
|
|
95
|
+
dbcli audit show --recovery-ref <envelope-id> # find entry that emitted an envelope
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
The `inspect` / `guide` / `recover` / `recover --apply` agent JSON output embeds
|
|
99
|
+
`audit_recent: AuditEntryBrief[]` (last 5 entries) — a fresh session has immediate
|
|
100
|
+
history context. The envelope's `audit_ref` and the audit entry's `recovery_ref`
|
|
101
|
+
point at each other; agents can pivot either direction.
|
|
102
|
+
|
|
103
|
+
**Known limitation (v1.20.0):** Bi-directional linkage is wired for `query`,
|
|
104
|
+
`inspect`, and diagnostic surfaces. The commands `insert / update / delete /
|
|
105
|
+
export / q / schema` emit single-direction recovery envelopes (no `audit_ref`)
|
|
106
|
+
in v1.20.0; full coverage is tracked as Phase 23-04 follow-up. Recovery envelope
|
|
107
|
+
linkage from the envelope side is unaffected.
|
|
108
|
+
|
|
109
|
+
Audit entries are written to `.dbcli/audit/<connection>.jsonl` with rotation at
|
|
110
|
+
~10 MB or 1000 entries. `audit.enabled = false` in `.dbcli` opts out (default ON
|
|
111
|
+
since v1.20.0). For flag reference see [`reference.md`](./reference.md) §audit.
|
|
112
|
+
|
|
74
113
|
## Quick start
|
|
75
114
|
|
|
76
115
|
```bash
|
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: dbcli
|
|
3
|
+
description: 為 AI 代理設計、具權限控管的資料庫 CLI。可用於建立連線、查詢、檢視 schema、insert/update/delete、匯出結果,以及對敏感欄位/資料表設定 blacklist。支援 MySQL、PostgreSQL、MariaDB、MongoDB、Redis 與 Elasticsearch,並可在單一專案中管理多個命名連線與自訂 env 檔。當需要設定資料庫連線(`.dbcli` / `.env`)、在 v1 單一連線與 v2 多連線格式之間選擇、挑選認證方式(URI、env 參照、Cloud ID、API key)、執行 SQL / MongoDB JSON / Redis 指令 / Elasticsearch DSL、探索表格 / collection / key / index 結構、切換資料庫環境、保護敏感資料免受 AI 存取,或在指令失敗後執行自動化復原與引導修復時,觸發此 skill。完整旗標與範例請閱讀同層的 `reference.md`。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
**Languages:** [English](./SKILL.md) | [繁體中文](./SKILL.zh-TW.md)
|
|
7
|
+
|
|
8
|
+
# dbcli
|
|
9
|
+
|
|
10
|
+
為 AI 代理設計、具權限控管的資料庫 CLI。
|
|
11
|
+
|
|
12
|
+
## AI 代理工作流程(依序執行)
|
|
13
|
+
|
|
14
|
+
1. `dbcli inspect --for-agent` — 有界快照:連線、權限、blacklist、物件、snippets、建議的下一個指令。
|
|
15
|
+
2. `dbcli report --format json` — 使用內建 snippets 產出診斷報告(health / capacity / perf)。
|
|
16
|
+
3. `dbcli guide <goal> --format json` — 針對固定目標產出確定性的下一步指令計畫(`slow-query`、`capacity`、`health`、`index-usage`、`permissions`、`schema-overview`)。執行 `dbcli guide --list` 查看所有目標。
|
|
17
|
+
4. `dbcli recovery --code <CODE>` — 針對已知錯誤代碼(如 `CONN_REFUSED`、`PERMISSION_DENIED`、`SNIPPET_NOT_FOUND`)查詢結構化的復原指令。把 `--recovery` 傳給 `dbcli query` / `dbcli q`,失敗時可直接得到 `RecoveryEnvelope`。在 v1.16.0 中,`--recovery` 旗標也被 `dbcli insert`、`dbcli update`、`dbcli delete`、`dbcli export`、`dbcli schema` 與 `dbcli inspect` 支援(後者另新增 `--require-schema-cache` 對應 `SCHEMA_CACHE_MISSING` 路徑)。
|
|
18
|
+
- **v1.17.0** `dbcli recover` 讀取由先前 `--recovery` 失敗自動寫入的信封(`.dbcli/last-recovery.json`)。可單純檢視(預設 Markdown),或用 `--apply` 在風險門控下執行儲存的計畫。
|
|
19
|
+
- **v1.17.0** `dbcli recover --apply` 預設只執行 `risk=readonly` 與 `risk=dry-run` 步驟。可用 `--allow-write=readonly-cmd` 開放一層門控(執行本機端寫入,如 `blacklist remove`),或 `--allow-write=write-cmd`(也允許異動所連資料庫的步驟)。`--from <file>` 指定外部信封,取代自動儲存的那一個。`--format json` 輸出彙整後的機器可讀結果。
|
|
20
|
+
- 退出碼:`0` 成功、`1` 步驟失敗、`2` 信封缺失或格式錯誤、`3` 所有步驟皆被跳過(請開啟 `--allow-write` 或修正 interactive / placeholder)。
|
|
21
|
+
- 代理應遵守的 GuideStep 可選欄位:
|
|
22
|
+
- `interactive: true` — 步驟需要 TTY(`dbcli init` 家族)。`dbcli recover --apply` 會以 `skipped:interactive` 略過。
|
|
23
|
+
- `dbWrite: true` — 步驟會異動所連資料庫。鎖定最高風險層;保留給未來的寫入端復原步驟。
|
|
24
|
+
- `placeholders: ['<token>', ...]` — 代理必須在 `--apply` 執行前替換這些 token,否則會以 `skipped:placeholder` 略過。
|
|
25
|
+
- **v1.17.0 P4 Verification(驗證)。** `--apply` 主要計畫結束後,dbcli 會多跑 **一個唯讀步驟**(`envelope.verify`),偵測原始失敗是否已修復。輸出新增 `verifyResult`(執行的步驟)與 `verifyStatus`:
|
|
26
|
+
- `passed` — 驗證器以 0 退出,且(適用時)符合預期的 JSON 形狀。
|
|
27
|
+
- `failed` — 驗證器以非零退出或逾時。
|
|
28
|
+
- `indeterminate` — 驗證器以 0 退出,但啟發式判斷無法確認修復(JSON 解析失敗、欄位缺失、門控略過)。
|
|
29
|
+
Verify **僅在** `finalStatus === 'ok'` 時執行。傳 `--no-verify` 可略過。啟發式刻意輕量;正確性重要時,代理仍應自行對原始失敗操作再驗證一次。
|
|
30
|
+
- **v1.17.0 P2 Multi-turn `--next`(多輪逐步執行)。** 當 `--apply` 顆粒度過粗(interactive 卡住、計畫需要逐步檢視,或代理希望用自有工具驅動復原)時,可逐步執行步驟並向 dbcli 詢問下一步:
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# 代理從信封讀取 step 1,執行後向 dbcli 取得 step 2:
|
|
34
|
+
dbcli recover --next --after-step 1 --result '{"status":"ok","exitCode":0}'
|
|
35
|
+
# 回傳 NextResult 信封:
|
|
36
|
+
# {
|
|
37
|
+
# "schemaVersion": 1,
|
|
38
|
+
# "kind": "step",
|
|
39
|
+
# "errorCode": "BLACKLIST_TABLE",
|
|
40
|
+
# "cursor": 2,
|
|
41
|
+
# "totalSteps": 3,
|
|
42
|
+
# "step": { "order": 2, "command": "dbcli inspect --for-agent", ... }
|
|
43
|
+
# }
|
|
44
|
+
# 最後一步結束後,dbcli 回傳 kind: "done"。
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`--result` 接受 inline JSON `StepResultSummary`,或 `@<path>` 從檔案讀取。`stdoutSummary` 與 `stderrSummary` 各上限 4 KB — 請先把結果截到 **最後** 4 KB 再傳入。`--next` 與 `--apply` 互斥。每次呼叫獨立(不持久化 cursor)— 代理自行追蹤 `--after-step`。
|
|
48
|
+
5. `dbcli blacklist list` — 敏感資料邊界。
|
|
49
|
+
6. `dbcli schema <table> --format json` — 取得真實欄位名稱(SQL / Mongo / ES)或 `schema <key>`(Redis)。**禁止猜測。**
|
|
50
|
+
7. 在允許的權限範圍內執行 `query` / `insert` / `update` / `delete` / `export`。
|
|
51
|
+
8. 所有寫入:`--dry-run`(SQL / Mongo)→ 實際執行 → `query` 回讀確認。
|
|
52
|
+
|
|
53
|
+
代理友善的輸出請優先用 `--format json`。
|
|
54
|
+
|
|
55
|
+
## Agent Task Packs(代理任務套件)
|
|
56
|
+
|
|
57
|
+
當使用者要求一個資料庫工作流(例如「診斷這個慢查詢」、「審計權限」、「審視長時間執行的操作」),優先選用已發布的任務模板,而非憑記憶自行組合步驟。
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
dbcli skill tasks list --format json # 探索
|
|
61
|
+
dbcli skill tasks show <task> # 檢視
|
|
62
|
+
dbcli skill tasks plan <task> --param key=value --format json # 產生計畫
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
計畫輸出是一組附帶說明與風險標籤的 dbcli 指令序列。請逐一執行 — 任務計畫**不會**繞過 blacklist、schema、dry-run 或確認等要求。
|
|
66
|
+
|
|
67
|
+
任務檔放在 `assets/tasks/`(內建)、`.dbcli-shared/tasks/`(共享)與 `.dbcli/tasks/`(本地覆寫)。
|
|
68
|
+
|
|
69
|
+
## Audit Log 使用
|
|
70
|
+
|
|
71
|
+
當需要跨 session 或事後 forensics 重建工具歷史時,請優先使用 audit log,而非從零開始查詢 DB 狀態。
|
|
72
|
+
|
|
73
|
+
**情境 1 — Session handoff(接手前一個 agent 的工作):**
|
|
74
|
+
|
|
75
|
+
```bash
|
|
76
|
+
dbcli audit tail --for-agent --n 10 # 最近 10 筆(JSON envelope)
|
|
77
|
+
dbcli audit tail --all --for-agent --n 20 # 跨連線合併(D4)
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
取回 agent-facing JSON envelope,包含 `session_id` / `engine` / `command` / `target` / `success`,協助新 agent 快速掌握前一段工作脈絡。技術細節:metadata-only,**不**包含原始 SQL body / cell 值 / params(D3 鎖定)。
|
|
81
|
+
|
|
82
|
+
**情境 2 — Forensics(重建失敗現場):**
|
|
83
|
+
|
|
84
|
+
```bash
|
|
85
|
+
dbcli recover --format json # 觀察 audit_recent 嵌入 + recovery_ref
|
|
86
|
+
dbcli audit show <id-prefix> # 完整單筆 entry(≥4 字元 prefix)
|
|
87
|
+
dbcli audit show --recovery-ref <envelope-id> # 反向找出觸發 envelope 的 audit entry
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
`inspect` / `guide` / `recover` / `recover --apply` 的 agent JSON 內嵌 `audit_recent: AuditEntryBrief[]`(最近 5 筆),無須額外呼叫 audit CLI 即可看到歷史脈絡。Envelope 的 `audit_ref` 與 audit entry 的 `recovery_ref` 互為雙向指標。
|
|
91
|
+
|
|
92
|
+
**已知限制(v1.20.0):** Bi-directional 連結僅在 `query` / `inspect` / diagnostic 表面寫入;`insert` / `update` / `delete` / `export` / `q` / `schema` 失敗路徑暫未含 `audit_ref`,追蹤於 Phase 23-04 follow-up(見 `.planning/phases/25-recovery-envelope-bi-directional-linkage/25-J1-COVERAGE-MATRIX.md`)。Recovery envelope 既有 linkage 不受影響。
|
|
93
|
+
|
|
94
|
+
詳細指令參考:[`reference.md`](./reference.md) §audit(英文)。
|
|
95
|
+
|
|
96
|
+
完整旗標、每個指令的可貼上範例、`migrate` DDL、互動式 `shell` 與 MongoDB / Redis / ES 教學在 [reference.md](reference.md)(安裝時與本檔放在一起)。
|
|
97
|
+
|
|
98
|
+
## 快速開始
|
|
99
|
+
|
|
100
|
+
```bash
|
|
101
|
+
dbcli init # 建立 .dbcli 設定(自動解析 .env)
|
|
102
|
+
dbcli schema # 掃描所有資料表 → .dbcli/schemas/
|
|
103
|
+
dbcli query "SELECT * FROM users" # 執行 SQL(自動加上 LIMIT 1000)
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
如果 `.dbcli` 尚未存在,請先走下方的 **連線設定** 流程,再碰 `schema` / `query`。
|
|
107
|
+
|
|
108
|
+
## 連線設定(協助使用者把資料庫接上來)
|
|
109
|
+
|
|
110
|
+
當使用者問「我要怎麼連到 X?」、「幫我把 dbcli 接到 staging DB」,或 `doctor` / `status` 回報缺失或無效的設定時,依此流程處理。
|
|
111
|
+
|
|
112
|
+
> **預設「引導」而非「直接執行」。** `init` 會把憑證寫到磁碟。**僅在** 使用者明確授權且確認過實際值後再代為執行。
|
|
113
|
+
> 如果 `.dbcli` 中已含有 `{"$env": "..."}` 形式的環境變數參照,**不要** 為了「把它填好」而重跑 `init` — env-ref 形式是 CI / multi-env 的刻意設計。
|
|
114
|
+
|
|
115
|
+
### 決策樹(先問再寫)
|
|
116
|
+
|
|
117
|
+
1. **一個 DB 還是多個環境?** 一個 → v1(單一連線)。多環境 / tenant / replica → v2(`--conn-name <name>`,必要時搭配每個連線專屬的 `--env-file <path>`)。
|
|
118
|
+
2. **憑證放在哪裡?**
|
|
119
|
+
- 已在 `.env`(`DATABASE_URL` 或 `DB_HOST` / `DB_PORT` / `DB_USER` /
|
|
120
|
+
`DB_PASSWORD` / `DB_NAME` | `DB_DATABASE`)→ `init` 自動解析。
|
|
121
|
+
- 機密需要排除在 `.dbcli` 之外(CI/CD、multi-env)→ 使用 `--use-env-refs`,
|
|
122
|
+
並搭配 `--env-host` / `--env-port` / `--env-user` / `--env-password` / `--env-database`。
|
|
123
|
+
- 可以直接放明文 → 傳 `--host` / `--port` / `--user` / `--password` / `--name`(與 `--system`)。
|
|
124
|
+
3. **要哪一個權限層?** 預設取**最低**夠用的:
|
|
125
|
+
`query-only` → `read-write` → `data-admin` → `admin`。透過 `--permission` 設定。
|
|
126
|
+
4. **驗證、不要假設。** init 結束後跑 `dbcli status`(系統 + 權限 + blacklist 摘要、不含憑證)與 `dbcli doctor --format json`(env、設定形狀、連線、schema-cache 年齡、Mongo SRV 路徑)。
|
|
127
|
+
|
|
128
|
+
### 每個引擎的必備指令
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
# PostgreSQL / MySQL / MariaDB(v1,明文值)
|
|
132
|
+
dbcli init --system postgresql --host localhost --port 5432 \
|
|
133
|
+
--user app --password '<secret>' --name appdb --permission query-only
|
|
134
|
+
|
|
135
|
+
# 重用既有 .env(DATABASE_URL=postgresql://user:pw@host:5432/db)
|
|
136
|
+
dbcli init # 解析 cwd 的 .env
|
|
137
|
+
|
|
138
|
+
# MongoDB — 完整 URI(Atlas / replica sets / authSource)
|
|
139
|
+
dbcli init --system mongodb \
|
|
140
|
+
--uri "mongodb+srv://user:pw@cluster.example.mongodb.net/mydb?authSource=admin"
|
|
141
|
+
# MongoDB — 分項參數(無認證 = 省略 --user / --password)
|
|
142
|
+
dbcli init --system mongodb --host localhost --port 27017 --name mydb
|
|
143
|
+
|
|
144
|
+
# Redis — `--name` 是 LOGICAL DB INDEX("0".."15"),不是資料庫名稱
|
|
145
|
+
dbcli init --system redis --host localhost --port 6379 --password '<secret>' --name 0
|
|
146
|
+
|
|
147
|
+
# Elasticsearch — basic auth、Cloud ID 或 API key
|
|
148
|
+
dbcli init --system elasticsearch --host localhost --port 9200 \
|
|
149
|
+
--user elastic --password '<secret>'
|
|
150
|
+
dbcli init --system elasticsearch \
|
|
151
|
+
--cloud-id "myCluster:dXMtZWFzdC0xLmF3..." --api-key "<base64>"
|
|
152
|
+
# Multi-node / 自訂 CA / 自簽:請直接編輯 `.dbcli`,加上
|
|
153
|
+
# `nodes: [...]`、`protocol: https`、`caPath`、`rejectUnauthorized: false`。
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
### Multi-connection(v2 多連線)
|
|
157
|
+
|
|
158
|
+
```bash
|
|
159
|
+
dbcli init --conn-name staging --env-file .env.staging --permission query-only
|
|
160
|
+
dbcli init --conn-name prod --env-file .env.production --use-env-refs --skip-test
|
|
161
|
+
dbcli use --list # 顯示所有連線,* 標示預設
|
|
162
|
+
dbcli use prod # 切換預設
|
|
163
|
+
dbcli query --use staging "SELECT 1" # 單次覆寫
|
|
164
|
+
dbcli init --rename staging:stg # 重新命名
|
|
165
|
+
dbcli init --remove stg # 移除
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
每個連線的 schema cache 存於 `.dbcli/schemas/<connection>/`。在 `schema <table>` 前,每個連線都先跑一次 `dbcli schema --use <name>` — 否則 cache 可能回傳到其他連線的欄位。
|
|
169
|
+
|
|
170
|
+
### env-refs(把機密排除在 `.dbcli` 之外)
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
dbcli init --use-env-refs \
|
|
174
|
+
--env-host DB_HOST --env-port DB_PORT \
|
|
175
|
+
--env-user DB_USER --env-password DB_PASSWORD --env-database DB_NAME
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
會以 `{ "$env": "DB_HOST" }` 等形式存入,並在執行時解析。搭配 `--env-file <path>`(v2)讓每個連線有自己的 env 檔。
|
|
179
|
+
|
|
180
|
+
### 常見陷阱
|
|
181
|
+
|
|
182
|
+
- **MongoDB `mongodb+srv://`** — `dbcli doctor` 會回報 SRV 是用原生方式解析還是走 DoH fallback;在執行環境限制 DNS 時很有用。
|
|
183
|
+
- **MySQL/Postgres 密碼含 `@` `:` `/`** — 使用 `DATABASE_URL` 時要 percent-encode(`@` → `%40`);分項的 `--password` 旗標不需編碼。
|
|
184
|
+
- **Redis `--name`** — 僅接受 logical DB index 字串;非數字會被拒絕。
|
|
185
|
+
- **Elasticsearch TLS** — `caPath` 與 `rejectUnauthorized` 沒有對應旗標;`init` 後直接編輯 `.dbcli` 加上。
|
|
186
|
+
- **重跑 `init`** — 沒有 `--force` 拒絕覆寫;千萬不要為了「修好」一個含 `{ "$env": "..." }` 參照的設定而用 `--force`。
|
|
187
|
+
|
|
188
|
+
完整旗標與邊界案例見 [reference.md](reference.md) `init` 段落。
|
|
189
|
+
|
|
190
|
+
## 指令總覽 (Command overview)
|
|
191
|
+
|
|
192
|
+
| 指令 | 最低權限 | 摘要 |
|
|
193
|
+
|---------|-----------------|---------|
|
|
194
|
+
| `init` | n/a | 建立 `.dbcli`(v1 單一或 v2 多連線,透過 `--conn-name` / `--env-file`)。**通常由真人執行** — 不要為了清掉 `{"$env"}` 參照而重跑;該格式是刻意設計。 |
|
|
195
|
+
| `use` | n/a | 顯示 / 切換預設命名連線(僅 v2)。 |
|
|
196
|
+
| `list` | query-only+ | 資料表(SQL)、collections(MongoDB)、keys(Redis)或 indices(Elasticsearch)。 |
|
|
197
|
+
| `schema` | query-only+ | SQL:單表或全掃描存入 `.dbcli/schemas/`。MongoDB:sampled。ES:flattened mapping。Redis:僅單一 key(type / TTL / size)。支援 `--recovery`。 |
|
|
198
|
+
| `query` | query-only+ | SQL、Mongo JSON(`--collection`)、Redis 指令、ES DSL / Lucene(`--collection`)。`--format table\|json\|csv\|html`、`--ui` 開啟瀏覽器互動式 dashboard。支援 `--recovery`。 |
|
|
199
|
+
| `plan` | n/a | 靜態 SQL 風險分析器(`--format text\|json`);不連線即可分類語句。 |
|
|
200
|
+
| `q` | query-only+ | 以 `@name` 執行已儲存 snippet,搭配 `--param k=v`。支援 SQL / Elasticsearch DSL / 唯讀 Redis 內容;blacklist 強制套用。`--format table\|json\|csv\|html`、`--ui` 開啟互動式 dashboard。支援 `--recovery`。 |
|
|
201
|
+
| `queries` | n/a | 管理已儲存 snippet:`list` / `show` / `search` / `suggest` / `new` / `edit` / `check` / `delete` / `rename` / `copy` / `import` / `export`。 |
|
|
202
|
+
| `insert` / `update` | read-write+ | 僅 SQL 與 MongoDB。JSON `--data` / `--set`;`update` 必填 `--where`;先 `--dry-run`。Redis 寫入透過 `query`。支援 `--recovery`。 |
|
|
203
|
+
| `delete` | data-admin+ | 僅 SQL 與 MongoDB。必填 `--where`;先 `--dry-run`。支援 `--recovery`。 |
|
|
204
|
+
| `export` | query-only+ | 僅 SQL 與 MongoDB。Query → `--format json\|jsonl\|csv\|html` 檔案或 stdout。`html` 輸出獨立可互動 dashboard。支援 `--recovery`。 |
|
|
205
|
+
| `blacklist` | n/a | `list` / `table` / `column` 子指令,從查詢結果中遮蔽敏感資料。 |
|
|
206
|
+
| `check` | query-only+ | 僅 SQL(在 MySQL / MariaDB 最佳)。 |
|
|
207
|
+
| `diff` | query-only+ | 僅 SQL。儲存 / 比較 schema snapshot。 |
|
|
208
|
+
| `status` | query-only+ | 安全 JSON / 文字摘要(不含憑證)。 |
|
|
209
|
+
| `inspect` | query-only+ | 唯讀脈絡快照(連線、權限、blacklist、物件、snippets、建議指令)。`--for-agent` / `--no-connect` / `--require-schema-cache`。支援 `--recovery`。 |
|
|
210
|
+
| `report` | query-only+ | 以 `@diag/*` snippet 組成的診斷報告(health / capacity / perf)。`--section`、`--brief`、`--for-agent`、`--no-connect`。 |
|
|
211
|
+
| `guide` | query-only+ | 針對固定目標產出確定性下一步指令計畫(`slow-query`、`capacity`、`health`、`index-usage`、`permissions`、`schema-overview`)。`--list` 列舉所有目標。 |
|
|
212
|
+
| `recovery` | n/a | 對已知錯誤代碼查詢結構化 `RecoveryEnvelope`(`--code <CODE>` 或 `--list`)。獨立合成器;不需真實失敗。 |
|
|
213
|
+
| `recover` | n/a | 檢視(預設)或 `--apply` 執行 `.dbcli/last-recovery.json` 中自動儲存的復原計畫。`--allow-write=readonly-cmd\|write-cmd`、`--no-verify`、`--from <file>`、`--next --after-step <n> --result <json\|@file>` 多輪逐步執行。 |
|
|
214
|
+
| `doctor` | n/a | 環境、設定、連線、SRV 診斷(Mongo)、schema cache 年齡。 |
|
|
215
|
+
| `completion` | n/a | bash / zsh / fish 腳本。 |
|
|
216
|
+
| `upgrade` | n/a | 從 npm 自我更新;每個指令都帶 24h 快取的版本提示。 |
|
|
217
|
+
| `shell` | (與 query 同) | 互動式 REPL。僅支援 SQL 引擎與 MongoDB shell。 |
|
|
218
|
+
| `skill` | n/a | 產出 / 安裝 AI skill 文件(`--install <claude\|gemini\|copilot\|cursor>`);`skill tasks list/show/plan` 提供 Agent Task Packs。 |
|
|
219
|
+
| `migrate` | admin | 僅 SQL。**DDL;預設 dry-run** — 需 `--execute` 才會真的執行。 |
|
|
220
|
+
|
|
221
|
+
任何子指令上的 `--use <name>` 都會把目標切到對應的 v2 連線,但不改變預設值。
|
|
222
|
+
`--recovery` 被 `query`、`q`、`insert`、`update`、`delete`、`export`、`schema` 與 `inspect` 支援;失敗時這些指令會把 `RecoveryEnvelope` JSON 輸出到 stdout、抑制人類可讀的 stderr 訊息,並原子性地把信封寫入 `.dbcli/last-recovery.json` 供 `dbcli recover` 使用。
|
|
223
|
+
|
|
224
|
+
## 權限等級 (Permission levels)
|
|
225
|
+
|
|
226
|
+
| 等級 | 允許的操作 |
|
|
227
|
+
|-------|---------|
|
|
228
|
+
| query-only | SELECT、list、schema、export |
|
|
229
|
+
| read-write | + INSERT、UPDATE |
|
|
230
|
+
| data-admin | + DELETE(DML,不含 DDL) |
|
|
231
|
+
| admin | + 透過 `migrate` 執行 DDL,以及破壞性操作 |
|
|
232
|
+
|
|
233
|
+
## Multi-connection(v2 多連線)
|
|
234
|
+
|
|
235
|
+
- 每個命名連線都有自己的 schema 目錄:`.dbcli/schemas/<connection>/`。
|
|
236
|
+
- 在 `schema <table>` 之前,每個連線都先跑一次 `dbcli schema --use <name>` — 否則 cache 可能回傳到別的連線欄位。
|
|
237
|
+
- `schema --refresh` / `--reset` 管理 cache;詳見 reference.md。
|
|
238
|
+
|
|
239
|
+
## MongoDB
|
|
240
|
+
|
|
241
|
+
- 用 JSON filter 物件(`find`)或 JSON 陣列(`aggregate`);SQL 會被拒絕。`query` 必填 `--collection <name>`。
|
|
242
|
+
- **支援:** `init`、`list`、`schema`(sampled)、`query`、`insert`、`update`、`delete`、`export`、`status`、`use`、`shell`、`doctor`、`upgrade`、`completion`。
|
|
243
|
+
- **不支援:** `q`(saved queries)、`diff`、`migrate`、`check`。
|
|
244
|
+
- Schema 是**取樣**(預設 50 份文件);型別是 JS `typeof` 字串。
|
|
245
|
+
- 完整語法與範例見 reference.md MongoDB 段落。
|
|
246
|
+
|
|
247
|
+
## Redis
|
|
248
|
+
|
|
249
|
+
- 指令式執行;`query` 跑白名單內的 Redis 指令(例如 `GET`、`HSET`、`DEL`)。
|
|
250
|
+
- **支援:** `init`、`list`(透過 SCAN 列 keys)、`schema <key>`(type / TTL / size / sample)、`query`、`status`、`use`、`doctor`、`upgrade`、`completion`。
|
|
251
|
+
- **不支援:** `schema` 全掃描、`insert`、`update`、`delete`、`export`、`check`、`diff`、`migrate`、`q`。
|
|
252
|
+
寫入請走 `query "DEL <key>"` 等 — 同樣經過權限門檻。
|
|
253
|
+
- 權限分層對應指令:讀取類 → `query-only`;mutator(`SET`、`HSET`、...)→ `read-write`;`DEL` / `UNLINK` → `data-admin`。
|
|
254
|
+
- `database` 欄位是 logical DB index(預設 `0`);`list` 透過 SCAN 最多回傳 100 000 個 keys。
|
|
255
|
+
- 詳見 reference.md Redis 段落。
|
|
256
|
+
|
|
257
|
+
## Elasticsearch
|
|
258
|
+
|
|
259
|
+
- DSL(JSON body)或 Lucene query string;`query` 必填 `--collection <index>`。
|
|
260
|
+
- **支援:** `init`、`list`(含文件數的索引清單)、`schema [index]`(flattened mapping)、`query`、`status`、`use`、`doctor`、`upgrade`、`completion`。
|
|
261
|
+
- **不支援:** `insert`、`update`、`delete`、`export`、`check`、`diff`、`migrate`、`q`。
|
|
262
|
+
專屬寫入子指令尚未開放 — 若叢集允許,可用 `query` 或外部工具。
|
|
263
|
+
- Query-only 模式上限 1000 hits;`--no-limit` 也僅放寬到 10 000。
|
|
264
|
+
- Schema 會 flatten 巢狀欄位(`a.b.c`),並列出 `.fields` multi-fields。
|
|
265
|
+
- 詳見 reference.md Elasticsearch 段落。
|
|
266
|
+
|
|
267
|
+
## Saved queries(已儲存查詢)
|
|
268
|
+
|
|
269
|
+
執行可重用、帶參數的 SELECT 片段,存於你的 repo。
|
|
270
|
+
|
|
271
|
+
| 步驟 | 指令 |
|
|
272
|
+
|------|---------|
|
|
273
|
+
| 1. 探索 | `dbcli queries list` |
|
|
274
|
+
| 2. 檢視 | `dbcli queries show @<name>` |
|
|
275
|
+
| 3. 執行 | `dbcli q @<name> --param k=v` |
|
|
276
|
+
|
|
277
|
+
### 不知道要跑哪一個 query 時
|
|
278
|
+
|
|
279
|
+
1. `dbcli queries search <keywords>` — 自然關鍵字、fuzzy 排序
|
|
280
|
+
2. `dbcli queries suggest <intent>` — 依類別瀏覽
|
|
281
|
+
常見 intent:perf.slow-query、perf.cache-hit、capacity.size、
|
|
282
|
+
safety.connections、monitor.cluster-health
|
|
283
|
+
3. 找到後:`dbcli q @<name>`(blacklist 永遠強制)
|
|
284
|
+
|
|
285
|
+
Snippet 從三層解析,**local > shared > builtin**(本地優先):
|
|
286
|
+
- `builtin` — 內建於 dbcli(例如 `@diag/*`);執行時唯讀
|
|
287
|
+
- `.dbcli-shared/queries/` — 已 commit、團隊共享
|
|
288
|
+
- `.dbcli/queries/` — 已 gitignore、個人覆寫
|
|
289
|
+
|
|
290
|
+
管理本地 snippets 透過 `queries new | edit | delete | rename | copy | import | export`
|
|
291
|
+
(見 reference.md)。用 `copy` / `import` 把 builtin 或 shared snippet fork 到本地層編輯。
|
|
292
|
+
|
|
293
|
+
每個 `.sql` 檔可在 `-- ---` 區塊中宣告 YAML frontmatter
|
|
294
|
+
(name、description、engine、params、tags、可選 `intent`、可選 `visual`)。
|
|
295
|
+
`visual:` 區塊驅動互動式 dashboard(見下方「互動式 HTML dashboard」)。
|
|
296
|
+
機器可讀契約見 `dbcli queries show @<name> --format json`。
|
|
297
|
+
|
|
298
|
+
### 每個引擎的 body 格式
|
|
299
|
+
|
|
300
|
+
每個 snippet 的 body 格式由 `engine` frontmatter 欄位決定:
|
|
301
|
+
|
|
302
|
+
| 引擎 | Body 格式 | 備註 |
|
|
303
|
+
|-------------------|------------------------|-------|
|
|
304
|
+
| postgres / mysql | 單一 SELECT 或 WITH | `:name` → driver bind(`$1` / `?`) |
|
|
305
|
+
| elasticsearch | JSON DSL | `:name` → JSON-aware 取代;必填 `index:` |
|
|
306
|
+
| redis | 單一 Redis 指令 | `:name` → raw text;僅允許讀取指令 |
|
|
307
|
+
|
|
308
|
+
跨家族的 `engine` 陣列(例如 `[postgres, elasticsearch]`)在 parse 階段就被拒絕。
|
|
309
|
+
|
|
310
|
+
### 內建診斷 snippets
|
|
311
|
+
|
|
312
|
+
dbcli 內附現成的診斷查詢。用 `dbcli q @diag/<topic>` 執行:
|
|
313
|
+
|
|
314
|
+
| key | 用途 |
|
|
315
|
+
|-------------------------|-------------------------------------------|
|
|
316
|
+
| `@diag/connections` | 活躍 session |
|
|
317
|
+
| `@diag/long-running` | 超過 `min_seconds`(預設 30)的查詢 |
|
|
318
|
+
| `@diag/table-sizes` | 帶 row 數的 table data / index 大小 |
|
|
319
|
+
| `@diag/index-usage` | 依 scan 次數排序的索引 |
|
|
320
|
+
| `@diag/missing-indexes` | 以 sequential scan 為主的資料表 |
|
|
321
|
+
| `@diag/locks` | lock-wait chain |
|
|
322
|
+
| `@diag/db-size` | 資料庫大小摘要 |
|
|
323
|
+
| `@diag/cache-hit` | buffer cache 命中率 |
|
|
324
|
+
| `@diag/es-cluster-health` | 每個 index 的文件數(ES 連線) |
|
|
325
|
+
| `@diag/redis-key-stats` | keyspace 上的 SCAN 取樣(Redis 連線) |
|
|
326
|
+
|
|
327
|
+
依目前連線自動挑選引擎變體。把同名檔案放到 `.dbcli-shared/queries/`
|
|
328
|
+
或 `.dbcli/queries/` 即可覆寫任何一個。
|
|
329
|
+
|
|
330
|
+
## 互動式 HTML dashboard
|
|
331
|
+
|
|
332
|
+
`query`、`q` 與 `export` 可把結果渲染為獨立、自包含的 HTML 報表,由內建的 React + Recharts 模板(`assets/ui-template.html`)驅動,
|
|
333
|
+
經由硬化的 `window.__DBCLI_PAYLOAD__ = {...}` 區塊注入(`<` 會被跳脫以中和 `</script>` payload)。
|
|
334
|
+
|
|
335
|
+
```bash
|
|
336
|
+
# 在瀏覽器中開啟(先寫到 temp 檔,再 `open` / `xdg-open` / `start`)
|
|
337
|
+
dbcli query "SELECT day, dau FROM dau_daily" --ui
|
|
338
|
+
dbcli q @analytics/revenue --param days=30 --ui
|
|
339
|
+
|
|
340
|
+
# 把 HTML pipe 到 stdout(CI 產出、email、靜態主機)
|
|
341
|
+
dbcli query "SELECT * FROM orders" --format html > orders.html
|
|
342
|
+
|
|
343
|
+
# 匯出到檔案(與 json / jsonl / csv 可互換)
|
|
344
|
+
dbcli export "SELECT * FROM orders" --format html --output orders.html
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
`--ui` 隱含 `--format html` 並開啟檔案;`--format html` 單獨使用則寫到 stdout。Blacklist 遮蔽在渲染**之前**套用 — dashboard 永遠看不到被遮蔽的欄位。
|
|
348
|
+
|
|
349
|
+
### Snippet `visual:` 區塊
|
|
350
|
+
|
|
351
|
+
要在結果中得到 KPI 與圖表(而非僅 sortable table),請在 snippet 的 frontmatter 加上 `visual:` 區塊。column 名稱必須存在於結果列中。
|
|
352
|
+
|
|
353
|
+
```sql
|
|
354
|
+
-- ---
|
|
355
|
+
-- name: Revenue Trend
|
|
356
|
+
-- engine: postgres
|
|
357
|
+
-- params:
|
|
358
|
+
-- days: { type: int, default: 30 }
|
|
359
|
+
-- visual:
|
|
360
|
+
-- title: Revenue (last :days days)
|
|
361
|
+
-- kpis:
|
|
362
|
+
-- - { label: Total Revenue, value_column: total_revenue, format: currency }
|
|
363
|
+
-- - { label: Orders, value_column: order_count, format: number }
|
|
364
|
+
-- - { label: Conversion, value_column: conv_rate, format: percent }
|
|
365
|
+
-- charts:
|
|
366
|
+
-- - { type: line, title: Daily Revenue, x: day, y: [revenue] }
|
|
367
|
+
-- - { type: bar, title: By Channel, x: channel, y: [revenue, refunds] }
|
|
368
|
+
-- ---
|
|
369
|
+
SELECT ...
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
- `kpis[].format`:`currency` / `number` / `percent`(省略即顯示原值)。
|
|
373
|
+
- `charts[].type`:`line` / `bar` / `area` / `pie` / `scatter`。
|
|
374
|
+
- 不走 snippet 的原始 `query` 指令只能渲染 sortable / filterable table — 沒有 `visual:` 可掛載。
|
|
375
|
+
|
|
376
|
+
## 常見工作流程
|
|
377
|
+
|
|
378
|
+
- **除錯異常狀態:** `schema` → `check` → 帶緊湊 `WHERE` 的 `query` → 順著 schema JSON 的 FK 追蹤。證據先於理論。
|
|
379
|
+
- **INSERT / UPDATE 之後:** `--dry-run` → 實際執行 → `query` 回讀;用 triggers、預設值或 blacklist 解釋落差。
|
|
380
|
+
- **Migrations:** `diff --snapshot` → `migrate`(dry-run → `--execute`)→ `diff --against` → 對受影響資料表跑 `check`。DROP 需 `--force`。
|
|
381
|
+
- **健康 / 成長:** `check --all`(除非加 `--include-large`,否則略過巨大表);做 ad-hoc query 前先看 schema 的 `sizeCategory`。
|
|
382
|
+
- **從活線 DB 產生程式:** `schema --format json` 餵給 ORM;再用 `dbcli query` 交叉驗證一次。
|
|
383
|
+
- **整合事實:** 前 `query` → 跑應用 → 後 `query`。單元測試 mock 不能替代。
|
|
384
|
+
- **自然語言請求**(例如「把訂單更新為 shipped」):先決定要 `query` 還是 DML,透過 `schema` 把詞彙映到欄位(值用 enum),尊重 blacklist 與 `sizeCategory`,**寫入永遠先 `--dry-run`**。
|
|
385
|
+
|
|
386
|
+
## 備註
|
|
387
|
+
|
|
388
|
+
- Query-only 模式自動補 `LIMIT 1000`;查 `information_schema` 或會被 `LIMIT` 破壞的語句請加 `--no-limit`。
|
|
389
|
+
- 被 blacklist 的 table / column 會從查詢輸出中遮蔽。
|
|
390
|
+
- `schema` 回報 `estimatedRowCount` 與 `sizeCategory`(small / medium / large / huge)。大 / 巨大表要加 `WHERE` 或 `LIMIT` — 分界值見 reference.md。
|
|
391
|
+
- 對 `mongodb+srv://` 連線,`doctor` 會回報 SRV 是用原生解析或走 DoH fallback — 在執行環境限制 DNS 時很有用。
|
|
392
|
+
- **全域旗標:** `--config <path>`、`--use <name>`、`-v` / `-vv` / `-q`、`--no-color`(也尊重 `NO_COLOR`)。
|