@aiweik/tableforge
v1.0.0
Published
A powerful MySQL table builder for Node.js with method chaining and complete data type support
Downloads
16
Maintainers
Readme
TableForge - MySQL 表构建器
基于 Node.js + mysql2 实现的纯 JavaScript 动态建表工具,支持完整的 MySQL 数据类型、字段约束与链式调用。
✨ 特性
- 🚀 链式调用 - 流畅的 API 设计,支持方法链式调用
- 🎯 类型安全 - 完整的 MySQL 数据类型支持,参数化配置
- 🔧 灵活配置 - 支持字段约束、索引、表选项等完整配置
- 📝 SQL 调试 - 提供
toSQL()方法查看生成的 SQL 语句 - 🛡️ 防护措施 - 字段名自动转义,防止 SQL 注入
- 📦 零依赖 - 仅依赖 mysql2,轻量级设计
📦 安装
npm install @aiweik/tableforge mysql2🚀 快速开始
const TableBuilder = require('@aiweik/tableforge');
// 创建数据库连接配置
const dbConfig = {
host: 'localhost',
user: 'root',
password: '123456',
database: 'myapp'
};
(async () => {
// 创建用户表
const usersTable = new TableBuilder('users', dbConfig);
await usersTable
.addField('id', 'BIGINT', {
primaryKey: true,
autoIncrement: true,
notNull: true
})
.addField('username', 'VARCHAR(50)', {
notNull: true,
unique: true,
comment: '用户名'
})
.addField('email', 'VARCHAR(255)', {
notNull: true,
unique: true
})
.addField('status', "ENUM('active', 'inactive')", {
default: "'active'",
comment: '用户状态'
})
.addField('created_at', 'TIMESTAMP', {
default: 'CURRENT_TIMESTAMP'
})
.engine('InnoDB')
.charset('utf8mb4')
.create();
console.log('✅ 用户表创建成功!');
})();📋 核心模块
TableBuilder 类
构造函数
new TableBuilder(tableName, connectionConfig)tableName(string): 表名connectionConfig(object): mysql2 连接配置
核心方法
| 方法 | 参数 | 说明 | 返回值 |
|------|------|------|--------|
| addField(name, type, options) | 字段名, 类型, 选项 | 添加字段定义 | TableBuilder |
| addIndex(fields, options) | 字段/字段数组, 选项 | 添加普通索引 | TableBuilder |
| addUniqueIndex(fields, options) | 字段/字段数组, 选项 | 添加唯一索引 | TableBuilder |
| addFullTextIndex(fields, options) | 字段/字段数组, 选项 | 添加全文索引 | TableBuilder |
| engine(name) | 引擎名称 | 设置存储引擎 | TableBuilder |
| charset(name) | 字符集名称 | 设置字符集 | TableBuilder |
| collation(name) | 排序规则名称 | 设置排序规则 | TableBuilder |
| comment(text) | 注释文本 | 设置表注释 | TableBuilder |
| ifNotExists(bool) | 布尔值 | 是否添加 IF NOT EXISTS | TableBuilder |
| create() | 无 | 执行建表操作 | Promise |
| toSQL() | 无 | 获取生成的 SQL | string |
| exists() | 无 | 检查表是否存在 | Promise |
| drop() | 无 | 删除表 | Promise |
字段选项 (options)
{
primaryKey: false, // 是否主键
autoIncrement: false, // 是否自增
notNull: false, // 是否非空
default: undefined, // 默认值
unique: false, // 是否唯一
unsigned: false, // 是否无符号
zerofill: false, // 是否零填充
comment: null // 字段注释
}索引选项 (options)
{
name: 'idx_name', // 索引名称
using: 'BTREE', // 索引类型 (BTREE/HASH)
comment: '索引注释' // 索引注释
}🎨 数据类型支持
数值类型
const TableBuilder = require('@aiweik/tableforge');
// 整数类型
'TINYINT(3)' // -128 ~ 127
'SMALLINT(5)' // -32768 ~ 32767
'MEDIUMINT(8)' // -8388608 ~ 8388607
'INT(10)' // 标准整数
'BIGINT(20)' // 大整数
// 浮点类型
'FLOAT(7,2)' // 单精度浮点
'DOUBLE(15,4)' // 双精度浮点
'DECIMAL(10,2)' // 精确小数(推荐用于金额)
// 位类型
'BIT(8)' // 位字段日期时间类型
'DATE' // YYYY-MM-DD
'TIME(3)' // HH:MM:SS[.ffffff]
'DATETIME(6)' // 日期+时间
'TIMESTAMP(3)' // 时间戳(自动时区转换)
'YEAR' // 四位年份字符串类型
'CHAR(10)' // 固定长度字符串
'VARCHAR(255)' // 可变长字符串
'TINYTEXT' // 短文本 (255 字节)
'TEXT' // 文本 (64KB)
'MEDIUMTEXT' // 中等文本 (16MB)
'LONGTEXT' // 长文本 (4GB)特殊类型
'JSON' // JSON 文档 (MySQL 5.7+)
'ENUM("a","b","c")' // 枚举(单选)
'SET("x","y","z")' // 集合(多选)
'POINT' // 空间点
'GEOMETRY' // 几何图形💡 高级用法示例
复杂表创建
const ordersTable = new TableBuilder('orders', dbConfig);
await ordersTable
// 订单基础信息
.addField('id', 'BIGINT', {
primaryKey: true,
autoIncrement: true,
notNull: true,
unsigned: true
})
.addField('order_no', 'VARCHAR(32)', {
notNull: true,
unique: true,
comment: '订单唯一编号'
})
.addField('user_id', 'BIGINT', {
notNull: true,
unsigned: true,
comment: '用户ID'
})
.addField('total_amount', 'DECIMAL(12,2)', {
notNull: true,
unsigned: true,
comment: '订单总金额'
})
// 订单状态
.addField('status', "ENUM('pending','paid','shipped','delivered','cancelled')", {
notNull: true,
default: "'pending'",
comment: '订单状态'
})
// 地址和标签
.addField('shipping_address', 'JSON', {
comment: '收货地址JSON'
})
.addField('tags', "SET('urgent','gift','fragile','express')", {
comment: '订单标签'
})
// 时间字段
.addField('created_at', 'DATETIME(3)', {
notNull: true,
default: 'CURRENT_TIMESTAMP(3)'
})
// 添加索引
.addIndex('user_id', {
name: 'idx_user_id',
comment: '用户ID索引'
})
.addIndex(['status', 'created_at'], {
name: 'idx_status_date'
})
.addFullTextIndex(['shipping_address'], {
name: 'ft_address'
})
// 表选项
.engine('InnoDB')
.charset('utf8mb4')
.collation('utf8mb4_unicode_ci')
.comment('订单信息表')
.create();调试和预览
const table = new TableBuilder('debug_table', dbConfig);
// 添加字段...
table.addField('id', 'BIGINT', { primaryKey: true });
// 预览生成的 SQL
console.log('生成的SQL:');
console.log(table.toSQL());
// 检查表是否存在
const exists = await table.exists();
console.log('表是否存在:', exists);
// 仅在表不存在时创建
if (!exists) {
await table.create();
}错误处理
try {
const table = new TableBuilder('users', dbConfig);
await table
.addField('id', 'BIGINT', { primaryKey: true })
.create();
console.log('✅ 表创建成功');
} catch (error) {
if (error.message.includes('already exists')) {
console.log('⚠️ 表已存在');
} else {
console.error('❌ 创建失败:', error.message);
}
}⚠️ 重要注意事项
默认值处理
// 字符串默认值需要加引号
default: "'active'"
// 数字直接传值
default: 0
// SQL 函数作为字符串
default: 'CURRENT_TIMESTAMP'主键约束
- 自增字段必须是整数类型
- 自增字段自动成为主键
- 支持多字段联合主键
安全性
- 字段名自动使用反引号转义
- ENUM/SET 值自动转义单引号
- 默认值由用户控制,请勿直接拼接用户输入
生产环境建议
- 适用于开发、测试或轻量级脚本
- 生产环境推荐使用专业迁移工具:
🧪 测试
# 运行测试示例
node examples/basic-example.js
# 运行高级示例
node examples/advanced-example.js📁 项目结构
TableForge/
├── lib/
│ ├── TableBuilder.js # 表构建器核心类
│ └── types.js # MySQL 类型常量(可选)
├── examples/
│ ├── basic-example.js # 基础用法示例
│ └── advanced-example.js # 高级用法示例
├── test/
│ └── table-builder.test.js # 单元测试
├── index.js # 主入口文件
├── package.json # 项目配置
├── README.md # 中文文档
└── README_EN.md # 英文文档🔗 相关链接
📄 许可证
🤝 贡献
欢迎提交 Issue 和 Pull Request!
TableForge - 让 MySQL 表构建变得简单优雅 ✨
