tengits-dbm
v1.0.8
Published
Database Manager CLI - MySQL connection management and migration tool
Maintainers
Readme
dbm - Database Manager CLI
一个功能强大的 MySQL 数据库管理命令行工具,支持直连和 SSH 隧道连接。
特性
- 🔌 多种连接方式:支持直连和 SSH 隧道连接
- 🔐 安全加密:使用 AES-256-GCM + PBKDF2 加密存储密码
- 📊 数据库操作:列出数据库、表、字段信息,执行 SQL
- 📦 数据库迁移:支持跨服务器数据库迁移,自动处理冲突
- 🔍 数据比对:支持源/目标数据库结构和数据差异分析
- 🔄 连接池缓存:缓存已建立的连接,减少 SSH 隧道频繁创建
- 📝 结构化日志:多级别日志系统,支持文件输出
- 🎯 脚本友好:纯命令行参数,适合自动化场景
安装
# 从 npm 安装(推荐)
npm install -g tengits-dbm
# 或使用 yarn
yarn global add tengits-dbm从源码安装
# 克隆仓库
git clone <repository-url>
cd db-manager-cli
# 安装依赖
npm install
# 构建
npm run build
# 全局链接(开发时使用)
npm link快速开始
1. 设置主密码
dbm 使用主密码加密存储数据库连接密码。在使用前需要设置环境变量:
export DBM_MASTER_PASSWORD="your-secure-master-password"建议在 ~/.bashrc 或 ~/.zshrc 中添加:
# 在 shell 配置文件中添加
export DBM_MASTER_PASSWORD="your-secure-master-password"2. 添加数据库连接
直连方式:
dbm add mydb \
--host 192.168.1.100 \
--port 3306 \
--user root \
--password mypasswordSSH 隧道方式:
dbm add mydb-tunnel \
--host 192.168.1.100 \
--port 3306 \
--user root \
--password mypassword \
--ssh-host ssh.example.com \
--ssh-user sshuser \
--ssh-password sshpassword3. 基本操作
# 列出所有连接
dbm list
# 测试连接
dbm test mydb
# 列出数据库
dbm databases mydb
# 列出表
dbm tables mydb --database mydatabase
# 显示字段信息
dbm fields mydb --database mydatabase --table mytable
# 执行 SQL(直接输入)
dbm exec mydb --database mydatabase --sql "SELECT * FROM users LIMIT 10"
# 执行 SQL(从文件读取)
dbm exec mydb --database mydatabase --file ./scripts/init.sql
# 删除连接
dbm remove mydb4. 数据库迁移
# 基本迁移
dbm migrate \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database
# 强制覆盖(跳过确认)
dbm migrate \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--force
# 迁移前备份
dbm migrate \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--backup5. 数据比对
数据比对功能用于比较源数据库和目标数据库之间的差异。
# 仅比对表结构
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--mode schema_only
# 采样比对(默认模式,采样 10% 数据)
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--mode data_sample \
--sample-rate 0.1
# 完整比对(注意:大数据量时耗时较长)
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--mode full
# 指定比对的表
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--tables users,orders,products
# 排除某些表
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--exclude logs,temp,audit
# 输出报告到文件
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--output comparison-report.md
# JSON 格式输出
dbm compare \
--source sourcedb \
--source-db source_database \
--target targetdb \
--target-db target_database \
--json比对模式说明:
| 模式 | 说明 | 适用场景 |
|------|------|----------|
| schema_only | 仅比对表结构 | 快速检查表结构差异 |
| data_sample | 采样比对数据(默认) | 大数据量时的快速检查 |
| full | 完整数据比对 | 需要精确比对所有数据 |
比对报告示例:
# 数据比对报告
**生成时间:** 2024-01-01T12:00:00.000Z
**源数据库:** source_db
**目标数据库:** target_db
## 统计信息
- 源数据库表数量: 10
- 目标数据库表数量: 10
- 比对表数量: 10
- 比对行数量: 5000
- 差异数量: 3
## 结构差异
### users
- **状态:** 结构不同
| 列名 | 差异类型 | 源值 | 目标值 |
|------|----------|------|--------|
| email | type_diff | varchar(255) | varchar(100) |
## 数据差异(采样)
### orders
- 源存在目标不存在: 5
- 值不同: 12高级配置
连接池配置
连接池管理器自动缓存已建立的数据库连接,减少 SSH 隧道频繁创建。
默认配置:
- 空闲超时: 5 分钟
- 清理间隔: 1 分钟
- 最大连接数: 10
配置方式:
import { ConnectionPoolManager } from './core/connection-pool-manager.js';
const poolManager = new ConnectionPoolManager(decryptPassword, {
idleTimeout: 10 * 60 * 1000, // 10 分钟
cleanupInterval: 2 * 60 * 1000, // 2 分钟
maxConnections: 20, // 最大 20 个连接
});日志配置
dbm 支持结构化日志系统,可以输出到控制台和文件。
日志级别:
debug: 调试信息info: 常规信息(默认)warn: 警告信息error: 错误信息
使用方式:
import { Logger, createLogger, configureLogger } from './core/logger.js';
// 创建日志器
const logger = createLogger({
level: 'debug', // 日志级别
console: true, // 输出到控制台
logDir: './logs', // 日志目录
filePrefix: 'dbm', // 文件前缀
timestamp: true, // 包含时间戳
colorize: true, // 控制台彩色输出
format: 'text', // 'text' 或 'json'
}, { service: 'my-service' }); // 上下文
// 使用日志
logger.debug('调试信息', { userId: 123 });
logger.info('操作成功', { action: 'connect' });
logger.warn('警告:连接接近超时');
logger.error('发生错误', new Error('连接失败'));
// 创建子日志器
const childLogger = logger.child({ module: 'sub-module' });
// 配置默认日志器
const defaultLogger = configureLogger({ level: 'debug' });日志文件示例(text 格式):
[2024-01-01T12:00:00.000Z] INFO 操作成功 action="connect" userId=123
[2024-01-01T12:00:01.000Z] ERROR 发生错误
Error: 连接失败
at Object.<anonymous> ...日志文件示例(JSON 格式):
{"timestamp":"2024-01-01T12:00:00.000Z","level":"info","message":"操作成功","context":{"action":"connect","userId":123}}
{"timestamp":"2024-01-01T12:00:01.000Z","level":"error","message":"发生错误","error":{"name":"Error","message":"连接失败","stack":"..."}}错误处理
dbm 提供了完善的错误处理机制:
错误类型:
| 错误类型 | 说明 | 退出码 |
|----------|------|--------|
| ConfigurationError | 配置错误 | 1 |
| ConnectionError | 连接错误 | 2 |
| EncryptionError | 加密错误 | 3 |
| DecryptionError | 解密错误 | 4 |
| SshTunnelError | SSH 隧道错误 | 5 |
| QueryError | 查询错误 | 6 |
| MigrationError | 迁移错误 | 7 |
| ValidationError | 验证错误 | 8 |
| NotFoundError | 资源未找到 | 9 |
| UnknownError | 未知错误 | 99 |
错误恢复机制:
- 连接重试:SSH 隧道连接失败时自动重试(默认 3 次)
- 事务回滚:迁移失败时自动回滚已创建的表
- 连接池验证:使用缓存的连接前自动验证有效性
- 敏感数据清理:密码使用后自动清零内存
命令参考
| 命令 | 说明 |
|------|------|
| add | 添加数据库连接 |
| list | 列出所有连接 |
| test | 测试连接 |
| remove | 删除连接 |
| databases | 列出数据库 |
| tables | 列出表 |
| fields | 显示字段信息 |
| exec | 执行 SQL 语句 |
| migrate | 迁移数据库 |
| compare | 比对数据库 |
数据存储
连接信息存储在本地 SQLite 数据库中:
- 位置:
~/.dbm/connections.db - 权限:
0600(仅所有者可读写) - 加密:所有密码使用 AES-256-GCM 加密
安全注意事项
- 主密码安全:请使用强密码作为主密码,并妥善保管
- 环境变量:避免在命令行中直接设置主密码(可能被历史记录)
- 文件权限:
~/.dbm/目录权限已自动设置为0700 - SSH 隧道:SSH 密码同样加密存储
- 内存清理:敏感数据使用后自动清零内存
开发
# 安装依赖
npm install
# 开发模式(监听文件变化)
npm run dev
# 构建
npm run build
# 运行测试
npm test
# 代码检查
npm run lint
# 运行单个测试文件
npm test -- tests/core/logger.test.ts项目结构
src/
├── commands/ # CLI 命令
│ ├── add.command.ts
│ ├── compare.command.ts
│ ├── databases.command.ts
│ ├── exec.command.ts
│ ├── fields.command.ts
│ ├── list.command.ts
│ ├── migrate.command.ts
│ ├── remove.command.ts
│ ├── tables.command.ts
│ └── test.command.ts
├── core/ # 核心模块
│ ├── connection-pool-manager.ts
│ ├── crypto.ts
│ ├── logger.ts
│ ├── mysql-driver.ts
│ ├── sql-utils.ts
│ └── ssh-tunnel.ts
├── errors/ # 错误处理
├── services/ # 业务服务
│ ├── connection.service.ts
│ ├── data-comparison.service.ts
│ ├── database.service.ts
│ └── migration.service.ts
├── store/ # 数据存储
└── types/ # 类型定义技术栈
- 运行时:Node.js 18+
- 语言:TypeScript
- CLI 框架:Commander.js
- 数据库驱动:mysql2
- SSH 隧道:ssh2
- 本地存储:better-sqlite3
- 加密:Node.js crypto (AES-256-GCM + PBKDF2)
- 终端美化:chalk, cli-table3, ora
- 测试框架:Vitest
License
MIT
