dbgraph 0.1.1 → 0.1.2

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.
Files changed (3) hide show
  1. package/README.ZH-cn.md +91 -289
  2. package/README.md +106 -300
  3. package/package.json +2 -2
package/README.ZH-cn.md CHANGED
@@ -1,64 +1,100 @@
1
+ <div align="center">
2
+
1
3
  # DBGraph
2
4
 
5
+ ### 数据库知识图谱 — 将数据库 schema 提取为知识图谱,通过 MCP 供 AI 代理使用
6
+
7
+ **零猜测 SQL 生成 · 亚毫秒级 schema 查询 · 100% 本地运行**
8
+
3
9
  [![npm version](https://img.shields.io/npm/v/dbgraph)](https://www.npmjs.com/package/dbgraph)
4
- [![License](https://img.shields.io/npm/l/dbgraph)](LICENSE)
5
- [![Node](https://img.shields.io/node/v/dbgraph)](https://nodejs.org)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
11
+ [![Node](https://img.shields.io/badge/Node.js-%3E%3D22.5-brightgreen)](https://nodejs.org/)
6
12
 
7
- 数据库知识图谱 —— 将数据库 schema 提取为本地知识图谱,通过 MCP 供 LLM 理解库表结构,从而减少 SQL 生成错误。
13
+ [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-支持-blue)](#支持引擎)
14
+ [![MySQL](https://img.shields.io/badge/MySQL-支持-blue)](#支持引擎)
15
+ [![SQLite](https://img.shields.io/badge/SQLite-支持-blue)](#支持引擎)
8
16
 
9
- ## 原理
17
+ </div>
10
18
 
11
- LLM 写 SQL 犯错的最大原因是**不知道你的库有什么**——表名靠猜、列名靠蒙、JOIN 条件靠碰运气。DBGraph 把数据库的 schema 信息(表、列、类型、外键、约束、索引)全部提取成一个**可搜索的知识图谱**存在 `.dbgraph/` 目录下,LLM 通过 MCP 工具直接查询,不直接连数据库。
19
+ ## 快速开始
12
20
 
13
- ```
14
- 传统流程:
15
- LLM → 猜表名列名 → 写 SQL → 执行 → 报错 → 再猜 → 循环
21
+ ```bash
22
+ # 零安装(推荐)
23
+ npx dbgraph
16
24
 
17
- DBGraph 流程:
18
- LLM dbgraph_context("orders") → 拿到精确 schema
19
- → 写 SQL → dbgraph_execute → 成功
25
+ # 或全局安装
26
+ npm i -g dbgraph
20
27
  ```
21
28
 
22
- ## 快速安装
29
+ ### 初始化项目
23
30
 
24
31
  ```bash
25
- # 全局安装
26
- npm install -g dbgraph
32
+ cd your-project
33
+ npx dbgraph init -i # 一步完成初始化 + 索引
34
+ ```
35
+
36
+ <sub>`dbgraph init` 创建 `.dbgraph/` 目录和默认 `dbgraph-db.json` 配置。加上 `-i`(`--index`)会立即内省数据库。编辑 `dbgraph-db.json` 配置数据库连接。</sub>
27
37
 
28
- # 或直接用 npx(无需安装)
29
- npx dbgraph --help
38
+ ### 启动 MCP 服务器
39
+
40
+ ```bash
41
+ npx dbgraph serve
30
42
  ```
31
43
 
32
- ## 前置要求
44
+ AI 代理连接 MCP 后自动发现 `dbgraph_*` 工具,用于 schema 感知的 SQL 生成。
33
45
 
34
- - **Node.js >= 22.5.0**(需要内置 `node:sqlite` 支持 FTS5 + WAL)
46
+ ## 为什么用 DBGraph?
35
47
 
36
- ## 快速开始
48
+ LLM 写 SQL 出错的最大原因是**不知道库表结构**——表名靠猜、列名靠蒙、JOIN 条件靠碰运气。DBGraph 把数据库 schema(表、列、类型、外键、约束、索引)提取为**可搜索的知识图谱**存在 `.dbgraph/` 中。AI 代理通过 MCP 工具直接查询,无需数据库直连。
37
49
 
38
- > 安装后直接使用 `dbgraph` 命令。如需本地开发,可用 `npm run cli -- <命令>` 替代(自动先构建)。
50
+ ```
51
+ 传统流程:
52
+ LLM → 猜名列名 → 写 SQL → 报错 → 再猜 → 循环
39
53
 
40
- ### 1. 初始化项目
54
+ DBGraph 流程:
55
+ LLM → dbgraph_context("orders") → 拿到精确 schema
56
+ → 写 SQL → 成功
57
+ ```
41
58
 
42
- 所有命令默认使用当前目录,也可指定目录路径。
59
+ ## CLI 命令
43
60
 
44
- ```bash
45
- # 初始化当前目录
46
- dbgraph init
61
+ | 命令 | 说明 |
62
+ |---------|-------------|
63
+ | `init` | 初始化 `.dbgraph` 项目(`-i` 立即索引)|
64
+ | `index` | 运行数据库内省 |
65
+ | `serve` | 启动 MCP 服务器(`--auto-refresh` 自动检测 schema 变更)|
66
+ | `query` | 搜索表、列、视图、索引 |
67
+ | `context` | 查看完整表结构(写 SQL 前必调)|
68
+ | `trace` | 追踪外键关联路径 |
69
+ | `explore` | 批量查看多张表 schema |
70
+ | `sources` | 列出已配置的数据库源 |
71
+ | `status` | 知识图谱统计 |
72
+ | `test` | 测试数据库连接 |
73
+ | `config` | 查看或创建配置 |
47
74
 
48
- # 初始化并立即索引(一步完成)
49
- dbgraph init -i
75
+ 所有命令默认使用当前目录,也可指定目录:
50
76
 
51
- # 初始化指定目录
52
- dbgraph init ./demo-project
77
+ ```bash
78
+ npx dbgraph status # 当前目录
79
+ npx dbgraph status ./other-project # 其他项目
53
80
  ```
54
81
 
55
- 这会创建:
56
- - `.dbgraph/` —— 知识图谱数据目录
57
- - `dbgraph-db.json` —— 数据库连接配置(默认模板)
82
+ ## MCP 工具
58
83
 
59
- ### 2. 配置数据库连接
84
+ 启动 `dbgraph serve` 后,AI 代理可调用:
60
85
 
61
- 编辑 `demo-project/dbgraph-db.json`,填入你的数据库信息:
86
+ | 工具 | 用途 |
87
+ |------|---------|
88
+ | `dbgraph_search` | 按名称搜索 schema 对象 |
89
+ | `dbgraph_context` | **完整表结构** — 列、类型、主键、外键、索引 |
90
+ | `dbgraph_trace` | 追踪外键关联路径(orders → users)|
91
+ | `dbgraph_explore` | 批量查看多张表 |
92
+ | `dbgraph_sources` | 列出所有数据库源 |
93
+ | `dbgraph_status` | 图谱健康状态与统计 |
94
+
95
+ ## 配置说明
96
+
97
+ 编辑项目根目录的 `dbgraph-db.json`:
62
98
 
63
99
  ```json
64
100
  {
@@ -81,277 +117,43 @@ dbgraph init ./demo-project
81
117
  }
82
118
  ```
83
119
 
84
- ### 3. 提取 Schema
85
-
86
- ```bash
87
- dbgraph index
88
- ```
89
-
90
- 把数据库 schema 提取到知识图谱中。首次运行会连接所有配置的数据库,提取表/列/外键/索引/视图等信息。
91
-
92
- ### 4. 查询知识图谱
93
-
94
- ```bash
95
- # 搜索表/列
96
- dbgraph query orders
97
- dbgraph query users --kind table
98
-
99
- # 查看完整表结构
100
- dbgraph context public.orders
101
-
102
- # 查看状态
103
- dbgraph status
104
-
105
- # 列出数据源
106
- dbgraph sources
107
- ```
108
-
109
- ## 配置说明
110
-
111
- ### `dbgraph-db.json`
112
-
113
120
  | 字段 | 类型 | 必填 | 说明 |
114
- |------|------|------|------|
115
- | `alias` | string | 是 | 数据库别名,在知识图谱中用 `db://@alias` 标识 |
116
- | `engine` | string | 是 | 数据库引擎:`postgresql` / `mysql` / `mariadb` / `sqlite` |
117
- | `host` | string | 否 | 主机地址(SQLite 不需要)|
121
+ |-------|------|----------|-------------|
122
+ | `alias` | string | 是 | 数据库别名(图谱中以 `db://@alias` 标识)|
123
+ | `engine` | string | 是 | `postgresql` / `mysql` / `mariadb` / `sqlite` |
124
+ | `host` | string | 否 | 主机地址 |
118
125
  | `port` | number | 否 | 端口(默认根据引擎判断)|
119
- | `database` | string | 是(非SQLite) | 数据库名 |
126
+ | `database` | string | 视情况 | PostgreSQL/MySQL 必填 |
120
127
  | `schemas` | string[] | 否 | 要提取的 schema 列表(默认全部)|
121
- | `path` | string | 是(SQLite) | SQLite 文件路径 |
122
- | `auth` | string | 否 | 认证方式,如 `env:DB_PASSWORD`(环境变量)、`~/.pgpass` |
123
- | `ssl` | boolean | 否 | 是否启用 SSL 连接 |
124
-
125
- ## CLI 命令参考
126
-
127
- 所有命令格式:`dbgraph <命令> [选项] [目录]`
128
-
129
- 不填目录时默认为当前目录。
130
-
131
- | 命令 | 说明 |
132
- |------|------|
133
- | `init` | 初始化 .dbgraph 项目 + 配置 |
134
- | `index` | 运行数据库内省,提取 schema |
135
- | `serve` | 启动 MCP 服务器(供 AI Agent 使用)|
136
- | `query` | 搜索表/列/视图 |
137
- | `context` | 查看完整表结构 |
138
- | `status` | 知识图谱状态统计 |
139
- | `sources` | 列出数据源 |
140
- | `test` | 测试数据库连接 |
141
- | `config` | 查看/创建配置 |
142
-
143
- ### `init`
144
-
145
- ```bash
146
- # 初始化当前目录
147
- dbgraph init
148
-
149
- # 初始化并立即索引
150
- dbgraph init -i
151
-
152
- # 初始化指定目录
153
- dbgraph init ./my-project
154
-
155
- # 指定配置文件路径
156
- dbgraph init ./my-project -c ./my-project/custom-config.json
157
- ```
158
-
159
- ### `index`
160
-
161
- ```bash
162
- # 索引当前目录配置的数据库
163
- dbgraph index
164
-
165
- # 指定配置文件
166
- dbgraph index ./my-project -c ./my-project/custom-config.json
167
- ```
168
-
169
- ### `serve`(MCP 模式)
170
-
171
- ```bash
172
- # 启动 MCP stdio 服务器(当前目录)
173
- dbgraph serve
174
-
175
- # 指定项目目录
176
- dbgraph serve ./my-project
177
- ```
178
-
179
- AI Agent 连接到 MCP 后自动发现 `dbgraph_*` 工具。
180
-
181
- ### `query`
182
-
183
- ```bash
184
- # 搜索
185
- dbgraph query orders
186
-
187
- # 按类型过滤
188
- dbgraph query orders --kind table
189
- dbgraph query amount --kind column
190
-
191
- # JSON 格式输出
192
- dbgraph query orders --json
193
- ```
194
-
195
- ### `context`
196
-
197
- ```bash
198
- # 查看表结构
199
- dbgraph context orders
200
- dbgraph context public.orders
201
- ```
202
-
203
- 输出示例:
204
- ```
205
- ## Table: public.orders
206
-
207
- Database: prod (postgresql)
208
-
209
- | Column | Type | Nullable | Default | PK | FK |
210
- |-------------|-------------|----------|----------|----|-----------|
211
- | id | bigint | NO | | PK | |
212
- | user_id | integer | NO | | | users.id |
213
- | status | varchar(20) | NO | pending | | |
214
- | total_amount| numeric(10,2)| YES | 0.00 | | |
215
- | created_at | timestamp | NO | now() | | |
216
-
217
- Indexes:
218
- - idx_orders_status on (status)
219
- - pk_orders PRIMARY KEY using btree (id)
220
-
221
- Foreign Keys:
222
- - fk_orders_user → users(id) ON DELETE CASCADE
223
- ```
224
-
225
- ## MCP 工具
226
-
227
- 启动 `dbgraph serve` 后,AI Agent 可以调用以下工具:
228
-
229
- | 工具 | 用途 | 推荐时机 |
230
- |------|------|---------|
231
- | `dbgraph_search` | 搜索表/列/视图/索引 | 不确定名字时 |
232
- | `dbgraph_context` | **主要入口** —— 返回完整表结构 + 列 + FK + 索引 | 写 SQL 前 |
233
- | `dbgraph_trace` | 追踪 FK 关联路径(orders→users) | 需要写 JOIN 时 |
234
- | `dbgraph_explore` | 一次性探索多张相关表 | 复杂查询涉及多表时 |
235
- | `dbgraph_sources` | 列出所有已配置的数据库源 | 了解有哪些库可用 |
236
- | `dbgraph_status` | 知识图谱统计 | 检查是否已索引 |
237
-
238
- ### 推荐工具调用策略
239
-
240
- ```
241
- 写 SQL 前的标准流程:
242
- 1. dbgraph_search("order") → 找到 order 相关表
243
- 2. dbgraph_context("public.orders") → 获取完整 schema
244
- 3. dbgraph_context("public.users") → 获取关联表 schema
245
- 4. dbgraph_trace("orders", "users") → 验证 FK 关联
246
- 5. LLM 写出精确 SQL
247
- ```
128
+ | `path` | string | 视情况 | SQLite 必填 |
129
+ | `auth` | string | 否 | `env:VAR_NAME` 或 `~/.pgpass` |
130
+ | `ssl` | boolean | 否 | 启用 SSL |
248
131
 
249
132
  ## 支持引擎
250
133
 
251
- | 引擎 | 状态 | 说明 |
252
- |------|------|------|
253
- | PostgreSQL | ✅ 完整支持 | `information_schema` + `pg_catalog` |
254
- | MySQL / MariaDB | ✅ 完整支持 | `information_schema` |
255
- | SQLite | ✅ 完整支持 | `pragma table_info` / `foreign_key_list` |
256
- | SQL Server | 🔜 计划中 | |
257
- | Oracle | 🔜 计划中 | |
258
- | MongoDB | 🔜 计划中 | |
259
-
260
- ## 项目结构
261
-
262
- ```
263
- dbgraph/
264
- ├── src/
265
- │ ├── index.ts # DBGraph 主类
266
- │ ├── types.ts # 所有类型 (Node, Edge, TableSchema...)
267
- │ ├── config.ts # dbgraph-db.json 配置管理
268
- │ ├── directory.ts # .dbgraph 目录管理
269
- │ ├── errors.ts # 错误类型
270
- │ ├── utils.ts # 工具函数
271
- │ │
272
- │ ├── db/ # SQLite 存储层
273
- │ │ ├── schema.sql # 表结构 (nodes/edges FTS5)
274
- │ │ ├── sqlite-adapter.ts # node:sqlite 适配
275
- │ │ ├── migrations.ts # 版本迁移
276
- │ │ ├── queries.ts # CRUD + FTS5 搜索 + 评分 (LRU缓存)
277
- │ │ └── index.ts # 连接管理
278
- │ │
279
- │ ├── graph/
280
- │ │ └── traversal.ts # BFS/DFS/寻路/影响半径
281
- │ │
282
- │ ├── context/
283
- │ │ ├── index.ts # 表结构组装
284
- │ │ └── formatter.ts # Markdown 输出
285
- │ │
286
- │ ├── introspect/ # 数据库内省
287
- │ │ ├── base.ts # 基类 + Node/Edge 工厂
288
- │ │ ├── index.ts # 工厂方法
289
- │ │ ├── connection.ts # 连接管理
290
- │ │ ├── postgres.ts # PostgreSQL
291
- │ │ ├── mysql.ts # MySQL
292
- │ │ └── sqlite.ts # SQLite
293
- │ │
294
- │ ├── mcp/ # MCP 服务器
295
- │ │ ├── transport.ts # JSON-RPC 传输
296
- │ │ ├── session.ts # 会话管理
297
- │ │ ├── engine.ts # 引擎 + 生命周期
298
- │ │ ├── tools.ts # 6 个 dbgraph_* 工具
299
- │ │ ├── server-instructions.ts # LLM 指引
300
- │ │ └── index.ts # MCPServer
301
- │ │
302
- │ └── bin/
303
- │ └── dbgraph.ts # CLI
304
- ```
134
+ | 引擎 | 状态 |
135
+ |--------|------|
136
+ | PostgreSQL | ✅ 完整支持 |
137
+ | MySQL / MariaDB | ✅ 完整支持 |
138
+ | SQLite | ✅ 完整支持 |
139
+ | SQL Server | 🔜 计划中 |
140
+ | Oracle | 🔜 计划中 |
305
141
 
306
142
  ## 开发
307
143
 
308
144
  ```bash
309
- # 安装依赖
145
+ git clone https://github.com/ZhangYaoSong/dbgraph.git
146
+ cd dbgraph
310
147
  npm install
311
-
312
- # 构建
313
148
  npm run build
314
-
315
- # 开发模式(watch)
316
- npm run dev
317
-
318
- # 运行帮助
319
- npm run cli -- --help
149
+ npm run cli -- init -i # 初始化当前目录 + 索引
150
+ npm run cli -- serve # 从源码启动 MCP 服务器
320
151
  ```
321
152
 
322
- ### 添加新数据库引擎
323
-
324
- 在 `src/introspect/` 下创建新文件(如 `mssql.ts`),实现 `BaseIntrospector` 抽象类:
325
-
326
- ```typescript
327
- import { BaseIntrospector } from './base';
328
-
329
- export class MSSQLIntrospector extends BaseIntrospector {
330
- async extractAll(): Promise<IntrospectResult> {
331
- // 1. 连接数据库
332
- // 2. 查询 information_schema
333
- // 3. 调用 this.makeNode() / this.makeEdge()
334
- // 4. 返回 IntrospectResult
335
- }
336
- }
337
- ```
338
-
339
- 然后在 `src/introspect/index.ts` 中注册:
340
-
341
- ```typescript
342
- case 'mssql':
343
- return new MSSQLIntrospector(config);
344
- ```
345
-
346
- ## 参考
347
-
348
- - **[AGENTS.md](AGENTS.md)** — OpenCode AI Agent 的项目指引,包含开发命令速查、架构要点和 CodeGraph 使用说明。
349
- - **CodeGraph** — 本项目已初始化 CodeGraph 索引(`.codegraph/`),Agent 可优先使用 `codegraph_*` 工具进行结构查询,速度远超 grep。
350
-
351
153
  ## 鸣谢
352
154
 
353
- DBGraph 的架构和 MCP 设计受到了 [CodeGraph](https://github.com/colbymchenry/codegraph) 的启发。CodeGraph 是一个优秀的代码知识图谱工具,将代码库结构提取为可查询的知识图谱,本项目借鉴了其思路并将其应用于数据库 schema 领域。
155
+ [CodeGraph](https://github.com/colbymchenry/codegraph) 启发——一个优秀的代码知识图谱工具,本项目将其思路应用于数据库 schema 领域。
354
156
 
355
- ## License
157
+ ## 许可证
356
158
 
357
159
  MIT
package/README.md CHANGED
@@ -1,353 +1,159 @@
1
- # DBGraph
1
+ <div align="center">
2
2
 
3
- [![npm version](https://img.shields.io/npm/v/dbgraph)](https://www.npmjs.com/package/dbgraph)
4
- [![License](https://img.shields.io/npm/l/dbgraph)](LICENSE)
5
- [![Node](https://img.shields.io/node/v/dbgraph)](https://nodejs.org)
3
+ # DBGraph
6
4
 
7
- Database knowledge graph — Introspect database schemas into a local-first knowledge graph, exposed over MCP for LLM-powered SQL generation.
5
+ ### Database Knowledge Graph — Introspect schemas into a searchable graph, expose over MCP for AI agents
8
6
 
9
- ## The Problem
7
+ **Zero-guess SQL generation · Sub-millisecond schema lookups · 100% local**
10
8
 
11
- LLMs make SQL mistakes because they **don't know your schema** — guessing table names, column names, and JOIN conditions. DBGraph extracts your complete database schema (tables, columns, types, foreign keys, constraints, indexes) into a **searchable knowledge graph** stored in `.dbgraph/`. LLMs query it via MCP tools directly — no live database connection needed.
9
+ [![npm version](https://img.shields.io/npm/v/dbgraph)](https://www.npmjs.com/package/dbgraph)
10
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
11
+ [![Node](https://img.shields.io/badge/Node.js-%3E%3D22.5-brightgreen)](https://nodejs.org/)
12
12
 
13
- ```
14
- Without DBGraph:
15
- LLM → guess names → write SQL → run → error → guess again → loop
13
+ [![PostgreSQL](https://img.shields.io/badge/PostgreSQL-supported-blue)](#supported-engines)
14
+ [![MySQL](https://img.shields.io/badge/MySQL-supported-blue)](#supported-engines)
15
+ [![SQLite](https://img.shields.io/badge/SQLite-supported-blue)](#supported-engines)
16
16
 
17
- With DBGraph:
18
- LLM → dbgraph_context("orders") → get exact schema
19
- → write SQL → dbgraph_execute → success
20
- ```
17
+ </div>
21
18
 
22
- ## Quick Install
19
+ ## Get Started
23
20
 
24
21
  ```bash
25
- # Global install
26
- npm install -g dbgraph
22
+ # Zero-install (recommended)
23
+ npx dbgraph
27
24
 
28
- # Or use directly with npx
29
- npx dbgraph --help
25
+ # Or install globally
26
+ npm i -g dbgraph
30
27
  ```
31
28
 
32
- ## Requirements
33
-
34
- - **Node.js >= 22.5.0** (requires built-in `node:sqlite` for FTS5 + WAL)
35
-
36
- ## Quick Start
37
-
38
- All commands default to the current directory. Pass a directory path to target another project.
39
-
40
- ### 1. Initialize a project
41
-
42
- ```bash
43
- # Initialize current directory
44
- dbgraph init
45
-
46
- # Or initialize + index in one step
47
- dbgraph init -i
48
-
49
- # Or target a specific directory
50
- dbgraph init ./demo-project
51
- ```
52
-
53
- This creates:
54
- - `.dbgraph/` — knowledge graph data directory
55
- - `dbgraph-db.json` — database connection config (default template)
56
-
57
- ### 2. Configure database connections
58
-
59
- Edit `dbgraph-db.json` with your database info:
60
-
61
- ```json
62
- {
63
- "databases": [
64
- {
65
- "alias": "prod",
66
- "engine": "postgresql",
67
- "host": "localhost",
68
- "port": 5432,
69
- "database": "ecommerce",
70
- "schemas": ["public"],
71
- "auth": "env:DB_PASSWORD"
72
- },
73
- {
74
- "alias": "local",
75
- "engine": "sqlite",
76
- "path": "./dev.db"
77
- }
78
- ]
79
- }
80
- ```
81
-
82
- ### 3. Extract schema
83
-
84
- ```bash
85
- dbgraph index
86
- ```
87
-
88
- Introspects all configured databases and stores tables, columns, foreign keys, indexes, and views into the knowledge graph.
89
-
90
- ### 4. Query the knowledge graph
91
-
92
- ```bash
93
- # Search tables/columns
94
- dbgraph query orders
95
- dbgraph query users --kind table
96
-
97
- # View full table structure
98
- dbgraph context public.orders
99
-
100
- # Check status
101
- dbgraph status
102
-
103
- # List data sources
104
- dbgraph sources
105
- ```
106
-
107
- ## Configuration
108
-
109
- ### `dbgraph-db.json`
110
-
111
- | Field | Type | Required | Description |
112
- |-------|------|----------|-------------|
113
- | `alias` | string | yes | Database alias, identified as `db://@alias` in the graph |
114
- | `engine` | string | yes | Database engine: `postgresql` / `mysql` / `mariadb` / `sqlite` |
115
- | `host` | string | no | Host address (not needed for SQLite) |
116
- | `port` | number | no | Port (default depends on engine) |
117
- | `database` | string | yes (non-SQLite) | Database name |
118
- | `schemas` | string[] | no | Schemas to introspect (default: all) |
119
- | `path` | string | yes (SQLite) | SQLite file path |
120
- | `auth` | string | no | Authentication, e.g. `env:DB_PASSWORD` or `~/.pgpass` |
121
- | `ssl` | boolean | no | Enable SSL connection |
29
+ ### Initialize a project
122
30
 
123
- ## CLI Reference
124
-
125
- All commands follow: `dbgraph <command> [options] [directory]`
126
-
127
- | Command | Description |
128
- |---------|-------------|
129
- | `init` | Initialize .dbgraph project + config |
130
- | `index` | Run database introspection |
131
- | `serve` | Start MCP server (for AI agents) |
132
- | `query` | Search tables/columns/views |
133
- | `context` | View full table structure |
134
- | `status` | Knowledge graph statistics |
135
- | `sources` | List data sources |
136
- | `test` | Test database connections |
137
- | `config` | View/create configuration |
138
-
139
- ### `init`
140
-
141
- ```bash
142
- # Initialize current directory
143
- dbgraph init
144
-
145
- # Init and index immediately
146
- dbgraph init -i
147
-
148
- # Initialize a specific directory
149
- dbgraph init ./my-project
150
-
151
- # Specify config file path
152
- dbgraph init ./my-project -c ./my-project/custom-config.json
153
- ```
154
-
155
- ### `index`
156
-
157
- ```bash
158
- # Index configured databases (current dir)
159
- dbgraph index
160
-
161
- # Use a specific config file
162
- dbgraph index ./my-project -c ./my-project/custom-config.json
163
- ```
164
-
165
- ### `serve` (MCP mode)
166
-
167
- ```bash
168
- # Start MCP stdio server (current dir)
169
- dbgraph serve
170
-
171
- # Start for a specific project directory
172
- dbgraph serve ./my-project
31
+ ```bash
32
+ cd your-project
33
+ npx dbgraph init -i # init + index in one step
173
34
  ```
174
35
 
175
- AI agents automatically discover `dbgraph_*` tools upon connecting to MCP.
36
+ <sub>`dbgraph init` creates `.dbgraph/` and a default `dbgraph-db.json` config. Adding `-i` (`--index`) also introspects your databases immediately. Edit `dbgraph-db.json` first to configure your connections.</sub>
176
37
 
177
- ### `query`
38
+ ### Start the MCP server
178
39
 
179
40
  ```bash
180
- # Search
181
- dbgraph query orders ./my-project
41
+ npx dbgraph serve
42
+ ```
182
43
 
183
- # Filter by kind
184
- dbgraph query orders --kind table ./my-project
185
- dbgraph query amount --kind column ./my-project
44
+ AI agents connected to MCP automatically discover `dbgraph_*` tools for schema-aware SQL generation.
186
45
 
187
- # JSON output
188
- dbgraph query orders --json ./my-project
189
- ```
46
+ ## Why DBGraph?
190
47
 
191
- ### `context`
48
+ LLMs write wrong SQL because they **don't know your schema** — guessing table names, column names, and JOIN conditions. DBGraph extracts your complete database schema (tables, columns, types, foreign keys, constraints, indexes) into a **searchable knowledge graph** stored in `.dbgraph/`. AI agents query it via MCP tools directly — no live database connection needed.
192
49
 
193
- ```bash
194
- # View table structure
195
- dbgraph context orders ./my-project
196
- dbgraph context public.orders ./my-project
197
50
  ```
51
+ Without DBGraph:
52
+ LLM → guess names → write SQL → run → error → guess again → loop
198
53
 
199
- Example output:
54
+ With DBGraph:
55
+ LLM → dbgraph_context("orders") → get exact schema
56
+ → write SQL → success
200
57
  ```
201
- ## Table: public.orders
202
58
 
203
- Database: prod (postgresql)
59
+ ## CLI Reference
204
60
 
205
- | Column | Type | Nullable | Default | PK | FK |
206
- |-------------|-------------|----------|----------|----|-----------|
207
- | id | bigint | NO | | PK | |
208
- | user_id | integer | NO | | | users.id |
209
- | status | varchar(20) | NO | pending | | |
210
- | total_amount| numeric(10,2)| YES | 0.00 | | |
211
- | created_at | timestamp | NO | now() | | |
61
+ | Command | Description |
62
+ |---------|-------------|
63
+ | `init` | Initialize `.dbgraph` project (`-i` to index immediately) |
64
+ | `index` | Run database introspection |
65
+ | `serve` | Start MCP server (use `--auto-refresh` to watch for schema changes) |
66
+ | `query` | Search tables, columns, views, indexes |
67
+ | `context` | View full table schema (call before writing SQL) |
68
+ | `trace` | Trace foreign key join paths between tables |
69
+ | `explore` | Explore multiple related tables at once |
70
+ | `sources` | List configured database sources |
71
+ | `status` | Knowledge graph statistics |
72
+ | `test` | Test database connections |
73
+ | `config` | View or create configuration |
212
74
 
213
- Indexes:
214
- - idx_orders_status on (status)
215
- - pk_orders PRIMARY KEY using btree (id)
75
+ All commands default to the current directory. Pass a directory path to target another project:
216
76
 
217
- Foreign Keys:
218
- - fk_orders_user users(id) ON DELETE CASCADE
77
+ ```bash
78
+ npx dbgraph status # current directory
79
+ npx dbgraph status ./other-project # another project
219
80
  ```
220
81
 
221
82
  ## MCP Tools
222
83
 
223
- After starting `dbgraph serve`, AI agents can call these tools:
84
+ After starting `dbgraph serve`, AI agents can call:
224
85
 
225
- | Tool | Purpose | When to use |
226
- |------|---------|-------------|
227
- | `dbgraph_search` | Search tables/columns/views/indexes | When unsure about names |
228
- | `dbgraph_context` | **Primary entry** — full table schema + columns + FKs + indexes | Before writing SQL |
229
- | `dbgraph_trace` | Trace FK join paths (orders→users) | Before writing JOINs |
230
- | `dbgraph_explore` | Explore multiple related tables at once | Complex multi-table queries |
231
- | `dbgraph_sources` | List all configured database sources | Learn what databases are available |
232
- | `dbgraph_status` | Knowledge graph statistics | Verify the graph is healthy |
86
+ | Tool | Purpose |
87
+ |------|---------|
88
+ | `dbgraph_search` | Search schema objects by name |
89
+ | `dbgraph_context` | **Full table schema** columns, types, PKs, FKs, indexes |
90
+ | `dbgraph_trace` | Trace FK join paths (orders users) |
91
+ | `dbgraph_explore` | Batch schema for multiple tables |
92
+ | `dbgraph_sources` | List all database sources |
93
+ | `dbgraph_status` | Graph health and statistics |
233
94
 
234
- ### Recommended workflow
95
+ ## Configuration
235
96
 
236
- ```
237
- Standard pre-SQL flow:
238
- 1. dbgraph_search("order") → find relevant tables
239
- 2. dbgraph_context("public.orders") → get full schema
240
- 3. dbgraph_context("public.users") → get related table schema
241
- 4. dbgraph_trace("orders", "users") → verify FK paths
242
- 5. LLM writes precise SQL
97
+ Edit `dbgraph-db.json` in your project root:
98
+
99
+ ```json
100
+ {
101
+ "databases": [
102
+ {
103
+ "alias": "prod",
104
+ "engine": "postgresql",
105
+ "host": "localhost",
106
+ "port": 5432,
107
+ "database": "ecommerce",
108
+ "schemas": ["public"],
109
+ "auth": "env:DB_PASSWORD"
110
+ },
111
+ {
112
+ "alias": "local",
113
+ "engine": "sqlite",
114
+ "path": "./dev.db"
115
+ }
116
+ ]
117
+ }
243
118
  ```
244
119
 
245
- ## Supported Engines
120
+ | Field | Type | Required | Description |
121
+ |-------|------|----------|-------------|
122
+ | `alias` | string | yes | Database alias (`db://@alias` in graph) |
123
+ | `engine` | string | yes | `postgresql` / `mysql` / `mariadb` / `sqlite` |
124
+ | `host` | string | no | Host address |
125
+ | `port` | number | no | Port (default depends on engine) |
126
+ | `database` | string | depends | Required for PostgreSQL/MySQL |
127
+ | `schemas` | string[] | no | Schemas to introspect (default: all) |
128
+ | `path` | string | depends | Required for SQLite |
129
+ | `auth` | string | no | `env:VAR_NAME` or `~/.pgpass` |
130
+ | `ssl` | boolean | no | Enable SSL |
246
131
 
247
- | Engine | Status | Details |
248
- |--------|--------|---------|
249
- | PostgreSQL | ✅ Full | `information_schema` + `pg_catalog` |
250
- | MySQL / MariaDB | ✅ Full | `information_schema` |
251
- | SQLite | ✅ Full | `pragma table_info` / `foreign_key_list` |
252
- | SQL Server | 🔜 Planned | |
253
- | Oracle | 🔜 Planned | |
254
- | MongoDB | 🔜 Planned | |
132
+ ## Supported Engines
255
133
 
256
- ## Project Structure
257
-
258
- ```
259
- dbgraph/
260
- ├── src/
261
- │ ├── index.ts # DBGraph main class
262
- │ ├── types.ts # All types (Node, Edge, TableSchema...)
263
- │ ├── config.ts # dbgraph-db.json config management
264
- │ ├── directory.ts # .dbgraph directory management
265
- │ ├── errors.ts # Error types
266
- │ ├── utils.ts # Utility functions
267
- │ │
268
- │ ├── db/ # SQLite storage layer
269
- │ │ ├── schema.sql # Table schema (nodes/edges FTS5)
270
- │ │ ├── sqlite-adapter.ts # node:sqlite adapter
271
- │ │ ├── migrations.ts # Version migrations
272
- │ │ ├── queries.ts # CRUD + FTS5 search + scoring (LRU cache)
273
- │ │ └── index.ts # Connection management
274
- │ │
275
- │ ├── graph/
276
- │ │ └── traversal.ts # BFS/DFS/pathfinding/impact radius
277
- │ │
278
- │ ├── context/
279
- │ │ ├── index.ts # Table context assembly
280
- │ │ └── formatter.ts # Markdown output
281
- │ │
282
- │ ├── introspect/ # Database introspection
283
- │ │ ├── base.ts # Base class + Node/Edge factory
284
- │ │ ├── index.ts # Factory method
285
- │ │ ├── connection.ts # Connection management
286
- │ │ ├── postgres.ts # PostgreSQL
287
- │ │ ├── mysql.ts # MySQL
288
- │ │ └── sqlite.ts # SQLite
289
- │ │
290
- │ ├── mcp/ # MCP server
291
- │ │ ├── transport.ts # JSON-RPC transport
292
- │ │ ├── session.ts # Session management
293
- │ │ ├── engine.ts # Engine + lifecycle
294
- │ │ ├── tools.ts # 6 dbgraph_* tools
295
- │ │ ├── server-instructions.ts # LLM instructions
296
- │ │ └── index.ts # MCPServer
297
- │ │
298
- │ └── bin/
299
- │ └── dbgraph.ts # CLI
300
- ```
134
+ | Engine | Status |
135
+ |--------|--------|
136
+ | PostgreSQL | ✅ Full support |
137
+ | MySQL / MariaDB | ✅ Full support |
138
+ | SQLite | ✅ Full support |
139
+ | SQL Server | 🔜 Planned |
140
+ | Oracle | 🔜 Planned |
301
141
 
302
142
  ## Development
303
143
 
304
144
  ```bash
305
- # Install dependencies
145
+ git clone https://github.com/ZhangYaoSong/dbgraph.git
146
+ cd dbgraph
306
147
  npm install
307
-
308
- # Build
309
148
  npm run build
310
-
311
- # Development mode (watch)
312
- npm run dev
313
-
314
- # Quick build + run
315
- npm run cli -- status ./my-project
316
- ```
317
-
318
- ### Adding a new database engine
319
-
320
- Create a new file in `src/introspect/` (e.g. `mssql.ts`) implementing `BaseIntrospector`:
321
-
322
- ```typescript
323
- import { BaseIntrospector } from './base';
324
-
325
- export class MSSQLIntrospector extends BaseIntrospector {
326
- async extractAll(): Promise<IntrospectResult> {
327
- // 1. Connect to database
328
- // 2. Query information_schema
329
- // 3. Call this.makeNode() / this.makeEdge()
330
- // 4. Return IntrospectResult
331
- }
332
- }
333
- ```
334
-
335
- Then register it in `src/introspect/index.ts`:
336
-
337
- ```typescript
338
- case 'mssql':
339
- return new MSSQLIntrospector(config);
149
+ npm run cli -- init -i # init current dir + index
150
+ npm run cli -- serve # start MCP server from source
340
151
  ```
341
152
 
342
- ## References
343
-
344
- - **[AGENTS.md](AGENTS.md)** — OpenCode AI Agent project guide with dev commands and architecture overview
345
- - **CodeGraph** — This project uses CodeGraph indexing (`.codegraph/`) for fast structural queries
346
-
347
153
  ## Acknowledgments
348
154
 
349
- DBGraph\'s architecture and MCP design were inspired by [CodeGraph](https://github.com/colbymchenry/codegraph), an excellent code knowledge graph tool that extracts codebase structure into a queryable graph. This project adapts those ideas to the database schema domain.
155
+ Inspired by [CodeGraph](https://github.com/colbymchenry/codegraph) an excellent code knowledge graph tool that this project adapts to the database schema domain.
350
156
 
351
157
  ## License
352
158
 
353
- MIT
159
+ MIT
package/package.json CHANGED
@@ -1,11 +1,11 @@
1
1
  {
2
2
  "name": "dbgraph",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "description": "Database knowledge graph for LLM-powered SQL generation. Introspect database schemas into a local-first knowledge graph, exposed over MCP.",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
7
7
  "bin": {
8
- "dbgraph": "./dist/bin/dbgraph.js"
8
+ "dbgraph": "dist/bin/dbgraph.js"
9
9
  },
10
10
  "files": [
11
11
  "dist",