matrix-db-client
v1.9.0
Published
模块化异步数据库 CRUD 客户端, 自动适配 SQLite/MySQL/D1/MongoDB/PostgreSQL, 支持表/字段 Schema 导入导出, 兼容 Nuxt4 (Node.js & Cloudflare Pages)
Maintainers
Readme
matrix-db-client
模块化异步数据库 CRUD 客户端 · 自动适配 SQLite / MySQL / Cloudflare D1 / MongoDB / PostgreSQL · JOIN / UNION / 批量流式 / 迁移 / 类型生成 / 事务 / 日志 / CLI · 兼容 Nuxt 4 (Node.js & Cloudflare Pages)
matrix-db-client 是一套极致精炼的 TypeScript 数据库客户端, 通过统一的 IDatabaseAdapter 接口封装 5 种主流数据库的异步 CRUD 操作, 并支持JOIN/UNION、批量流式、迁移、类型生成、事务、查询日志、Schema 校验、CLI 工具与JSON Schema 导入导出。
✨ 特性
- 🎯 一行创建客户端 —
createClient(config)自动识别数据库类型并加载对应适配器 - 🧩 模块化分包 — 按需安装
@matrix-db-client/sqlite等, tree-shaking 友好 - 🔄 统一 API — 5 种数据库共享同一套
表 / 字段 / 记录 / 索引 / 原生查询 / 事务 / JOIN / UNION / 批量异步接口 - 🔗 JOIN 支持 —
INNER/LEFT/RIGHT/FULL JOIN+ 表别名, 字段自动加表名前缀避免歧义 - 🔀 UNION 查询 —
UNION / UNION ALL合并多表 SELECT, 自动去重 - 📦 批量流式 —
bulkInsert分批插入 10k+ 行,findStream异步迭代器流式查询 - 🔄 Migration —
snapshot/diff/plan/up/downSchema 版本管理, 自动生成迁移计划 - 🏷️ 类型生成 —
schemaToInterface/schemaToZodSchema从 Schema 生成 TS 类型 + Zod schema - 🔒 事务支持 —
transaction(fn)自动 commit/rollback, 支持显式 commit/rollback (sqlite/mysql/pg) - 📜 查询日志 —
logging: true或自定义LogFn,getLogs()/setLogger()动态控制 - 🛡️ Schema 校验 —
validateSchema/assertValid校验 columns/formItems/typeOverrides, 22 项规则 - 🖥️ CLI 工具 —
mdb inspect/export/sql/validate命令行 + 编程式 API - 📋 Schema 导入导出 — 支持完整
columns / formItems / searchItems / typeOverrides结构 - ⚡ Nuxt 4 全栈兼容 — Node.js 使用
better-sqlite3 / mysql2 / pg / mongodb, Cloudflare Pages/Workers 使用 D1 binding - 🧪 Vitest 全覆盖 — 142 个测试用例 (含 SQLite 真实 JOIN/UNION/批量/迁移/事务/日志集成测试)
- 📐 极致精炼 — 能 1 行实现绝不写 2 行, 全量 TypeScript 严格类型
📦 包结构
| 包名 | 说明 | 运行时 |
|------|------|--------|
| @matrix-db-client/core | 核心类型 / Schema / 适配器接口 / 工厂 / 校验 / JOIN / UNION / 批量 | 通用 |
| @matrix-db-client/sqlite | SQLite 适配器 (better-sqlite3) · 事务+日志 | Node.js |
| @matrix-db-client/mysql | MySQL 适配器 (mysql2 连接池) · 事务+日志 | Node.js |
| @matrix-db-client/d1 | Cloudflare D1 适配器 (Pages/Workers binding) · 日志 | Edge |
| @matrix-db-client/mongodb | MongoDB 适配器 (v6 driver, 兼容 server 4.4+) | Node.js |
| @matrix-db-client/pg | PostgreSQL 适配器 (node-postgres) · 事务+日志 | Node.js |
| @matrix-db-client/cli | CLI 工具 (inspect/export/sql/validate) | Node.js |
| @matrix-db-client/migrator | 迁移工具 (snapshot/diff/plan/up/down) | Node.js |
| @matrix-db-client/typegen | 类型生成 (TS interface + Zod schema) | Node.js |
🚀 安装
按需安装核心包 + 你使用的方言包:
# SQLite (Nuxt Node.js / Nitro ssr)
npm install @matrix-db-client/core @matrix-db-client/sqlite
# 还需安装底层驱动
npm install better-sqlite3
# MySQL
npm install @matrix-db-client/core @matrix-db-client/mysql mysql2
# PostgreSQL
npm install @matrix-db-client/core @matrix-db-client/pg pg
# MongoDB (兼容 server 4.4+)
npm install @matrix-db-client/core @matrix-db-client/mongodb mongodb
# Cloudflare D1 (Nuxt Cloudflare Pages preset)
npm install @matrix-db-client/core @matrix-db-client/d1或一次性安装全部:
npm install @matrix-db-client/core @matrix-db-client/sqlite @matrix-db-client/mysql @matrix-db-client/d1 @matrix-db-client/mongodb @matrix-db-client/pg🧑💻 快速开始
1. 自动适配 (推荐)
传入连接配置, createClient 会自动识别数据库类型并返回适配器实例:
import { createClient } from '@matrix-db-client/core'
// 1. SQLite — 从 filename 推断
const db = await createClient({ type: 'sqlite', filename: './data.db' })
// 2. MySQL — 从 type 或 port 3306 推断
const db = await createClient({ type: 'mysql', host: '127.0.0.1', user: 'root', password: 'xxx', database: 'app' })
// 3. PostgreSQL — 从 uri (postgres://) 或 port 5432 推断
const db = await createClient({ uri: 'postgresql://user:pass@host:5432/db', type: 'pg', database: 'db' } as never)
// 4. MongoDB — 从 uri (mongodb://) 推断
const db = await createClient({ type: 'mongodb', uri: 'mongodb://localhost:27017', database: 'app' })
// 5. Cloudflare D1 — 从 binding 推断 (在 Pages/Workers 中)
export default {
async fetch(req, env) {
const db = await createClient({ type: 'd1', binding: env.DB })
// ...
}
}2. 显式指定适配器
import { createAdapter } from '@matrix-db-client/core'
const db = await createAdapter('sqlite', { type: 'sqlite', filename: ':memory:' })3. 直接实例化 (跳过工厂, 零开销)
import SqliteAdapter from '@matrix-db-client/sqlite'
const db = await new SqliteAdapter({ type: 'sqlite', filename: './data.db' }).connect()📖 API 速查
所有适配器实现同一 IDatabaseAdapter 接口:
表操作
await db.listTables() // → string[]
await db.hasTable('users') // → boolean
await db.createTable('users', [ // 建表
{ name: 'id', type: 'int', primary: true, autoIncrement: true },
{ name: 'name', type: 'string', length: 100, nullable: false },
{ name: 'email', type: 'string', length: 200, unique: true }
])
await db.dropTable('users')
await db.renameTable('users', 'accounts')
await db.truncate('users')字段操作
await db.describeTable('users') // → FieldInfo[]
await db.listFields('users') // → string[]
await db.addField('users', { name: 'age', type: 'int', default: 0 })
await db.updateField('users', 'age', { name: 'age', type: 'int', length: 3 })
await db.removeField('users', 'age')索引操作
await db.listIndexes('users') // → IndexDef[]
await db.createIndex('users', { name: 'idx_email', fields: ['email'], unique: true })
await db.dropIndex('users', 'idx_email')记录 CRUD
// 新增
const id = await db.insert('users', { name: 'Alice', age: 30 })
const ids = await db.insertMany('users', [{ name: 'A' }, { name: 'B' }])
// 查询
const user = await db.findById<User>('users', 1)
const user = await db.findById<User>('users', 'uuid-xxx', 'uuid')
const list = await db.find<User>('users', {
fields: ['id', 'name'],
where: [
{ field: 'age', op: '>', value: 18 },
{ field: 'status', op: '=', value: 'active' }
],
orderBy: [{ field: 'id', direction: 'desc' }],
limit: 10, offset: 0
})
const one = await db.findOne<User>('users', { where: { field: 'email', op: '=', value: '[email protected]' } })
const total = await db.count('users', { field: 'age', op: '>', value: 18 })
// 更新
const changed = await db.update('users', { field: 'id', op: '=', value: 1 }, { name: 'Bob' })
await db.updateById('users', 1, { name: 'Bob' })
// 删除
const deleted = await db.remove('users', { field: 'id', op: '=', value: 1 })
await db.removeById('users', 1)分页
const page = await db.paginate<User>('users', {
page: 2, pageSize: 20,
where: { field: 'age', op: '>', value: 18 },
orderBy: [{ field: 'id', direction: 'asc' }]
})
// → { list: User[], total: number, page: 2, pageSize: 20 }事务 (sqlite / mysql / pg)
// 自动 commit/rollback: 抛错自动回滚
await db.transaction(async (tx) => {
const id = await tx.insert('orders', { user_id: 1, total: 100 })
await tx.update('accounts', { field: 'id', op: '=', value: 1 }, { balance: -100 })
await tx.insert('inventory', { order_id: id, shipped: false }
// 全部成功才 commit; 任一抛错自动 rollback
})
// 显式 commit / rollback
await db.transaction(async (tx) => {
await tx.insert('accounts', { name: 'X', balance: 0 })
if (someCondition) await tx.rollback() // 撤销
await tx.commit() // 提交
})查询日志
// 方式 1: config.logging = true, 日志累积在内存 (console.log 同步打印)
const db = await createClient({ type: 'sqlite', filename: './data.db', logging: true })
await db.find('users')
console.log(db.getLogs()) // → LogEntry[] { sql, params, ms, rows, timestamp }
// 方式 2: 自定义 LogFn 回调
const db = await createClient({
type: 'sqlite', filename: './data.db',
logging: (entry) => metrics.record(entry.sql, entry.ms)
})
// 动态控制
db.setLogger(null) // 关闭
db.setLogger(fn) // 切换回调
db.clearLogs() // 清空Schema 校验
import { validateSchema, assertValid } from '@matrix-db-client/core'
const result = validateSchema(schema)
// → { valid: boolean, errors: string[], warnings: string[] }
// errors: id 必填 / prop 重复 / type 非法 等
// warnings: select 缺 options / file 缺 accept 等建议
assertValid(schema) // 校验失败抛 MatrixDBError校验规则覆盖:
- 基础字段:
id/path/title/apiPath/rank - 列:
prop/label必填,render/align合法枚举, prop 唯一性 - 表单:
prop/label/type必填,type合法枚举 (22 种),select提示 options,file/files提示 accept+maxSize - 搜索: 同表单
typeOverrides引用必须存在于formItems
原生查询
const { rows } = await db.raw('SELECT * FROM users WHERE age > ?', [18])
const { changes } = await db.raw('UPDATE users SET status = ?', ['active'])JOIN 查询 (v1.2.0+)
// INNER JOIN: 订单 + 商品名
const list = await db.find<{ qty: number; product_name: string }>('orders', {
fields: ['qty', 'products.name AS product_name'],
joins: [{ type: 'INNER', table: 'products', on: '"orders"."product_id" = "products"."id"' }]
})
// LEFT JOIN + 表别名 + WHERE + ORDER BY
const list = await db.find('orders', {
joins: [{ type: 'LEFT', table: 'users', as: 'u', on: '"orders"."user_id" = "u"."id"' }],
where: { field: 'u.status', op: '=', value: 'active' },
orderBy: [{ field: 'orders.id', direction: 'desc' }]
})
// 多表 JOIN
const list = await db.find('orders', {
joins: [
{ type: 'INNER', table: 'users', as: 'u', on: '...' },
{ type: 'LEFT', table: 'products', as: 'p', on: '...' }
]
})UNION 查询 (v1.2.0+)
// UNION (去重)
const names = await db.union<{ name: string }>([
{ table: 'users', query: { fields: ['name'] } },
{ table: 'admins', query: { fields: ['name'] } }
])
// UNION ALL (保留重复)
const all = await db.union([{ table: 'users' }, { table: 'admins' }], true)批量流式操作 (v1.2.0+)
// bulkInsert: 分批插入 10k+ 行 (默认 batchSize=500)
const rows = Array.from({ length: 10000 }, (_, i) => ({ name: `user${i}`, age: i }))
const inserted = await db.bulkInsert('users', rows, 500) // → 10000
// findStream: 异步迭代器流式查询 (内存友好)
for await (const batch of db.findStream<User>('users', { batchSize: 1000, orderBy: [{ field: 'id', direction: 'asc' }] })) {
console.log(batch.length) // 每批 1000 条
}🔄 Migration 迁移工具 (v1.2.0+)
import { snapshot, diff, plan, up, down, makeSnapshot, formatPlan } from '@matrix-db-client/migrator'
// 1. 从数据库导出当前快照
const current = await snapshot(db, 1)
// 2. 定义目标快照 (或从 Schema 文件加载)
const target = makeSnapshot(2, [
{ name: 'users', fields: [{ name: 'id', type: 'int', primary: true }, { name: 'email', type: 'string' }] },
{ name: 'posts', fields: [{ name: 'id', type: 'int', primary: true }] }
])
// 3. 生成迁移计划
const p = plan(current, target)
console.log(formatPlan(p))
// 迁移计划: v1 → v2 (3 个动作)
// 01. CREATE TABLE users (2 fields)
// 02. CREATE TABLE posts (1 fields)
// 4. 执行迁移
const result = await up(db, p)
console.log(`执行 ${result.executed} 个动作, ${result.errors.length} 个错误`)
// 5. 回滚
const rollbackPlan = down(target, current)
await up(db, rollbackPlan)🏷️ 类型生成 (v1.2.0+)
import { schemaToInterface, schemaToZodSchema, fieldsToInterface, fieldInfosToInterface } from '@matrix-db-client/typegen'
// 1. 从 TableSchema 生成 TS interface
const tsCode = schemaToInterface(schema)
// export interface 商品管理 {
// name: string
// price: number
// is_hot?: boolean
// ...
// }
// 2. 从 TableSchema 生成 Zod schema
const zodCode = schemaToZodSchema(schema)
// import { z } from 'zod'
// export const 商品管理Schema = z.object({
// name: z.string(),
// price: z.number(),
// is_hot: z.boolean().optional(),
// ...
// })
// export type 商品管理 = z.infer<typeof 商品管理Schema>
// 3. 从 FieldDef[] 生成
const code = fieldsToInterface('User', [
{ name: 'id', type: 'int', primary: true },
{ name: 'name', type: 'string', nullable: false },
{ name: 'age', type: 'int', nullable: true }
])
// export interface User {
// id: number
// name: string
// age?: number
// }
// 4. 从数据库 describeTable 结果生成
const fields = await db.describeTable('users')
const code = fieldInfosToInterface('users', fields)🖥️ CLI 工具
# 安装
npm install -g @matrix-db-client/cli
# 检查数据库表结构
mdb inspect --type sqlite --filename ./data.db
# 从数据库导出 Schema JSON
mdb export --type sqlite --filename ./data.db --siteId my-site > schema.json
# 执行 SQL 查询
mdb sql --type sqlite --filename ./data.db "SELECT * FROM users LIMIT 10"
# 校验 Schema 文件
mdb validate --file ./schema.json编程式调用:
import { inspect, exportFromDb, runSql, validateSchemaFile, formatInspect } from '@matrix-db-client/cli'
const result = await inspect({ type: 'sqlite', filename: './data.db' })
console.log(formatInspect(result)) // 美化表格输出
const schemaJson = await exportFromDb({ type: 'sqlite', filename: './data.db' }, { siteId: 'export' })
const rows = await runSql({ type: 'sqlite', filename: './data.db' }, 'SELECT count(*) FROM users')📋 Schema 导入导出
import { importSchema, exportSchema, schemaToFields, findSchema, mergeSchemas } from '@matrix-db-client/core'
// 1. 导入 (字符串 / 对象 / 数组均可)
const store = importSchema(jsonString)
// 或 const store = importSchema({ code: 0, data: [...] })
// 或 const store = importSchema([schema1, schema2])
// 2. 导出
const json = exportSchema(store.data) // → JSON 字符串
const json = exportSchema(store.data, false) // → 紧凑模式
// 3. Schema → FieldDef[] (直接用于 createTable)
const fields = schemaToFields(store.data[0])
await db.createTable('products', fields)
// 4. 查找 / 合并
const s = findSchema(store.data, { path: '/products' })
const merged = mergeSchemas(store1, store2)WHERE 条件 (支持全部操作符)
// 单条件
{ field: 'age', op: '>', value: 18 }
// in / not in
{ field: 'id', op: 'in', values: [1, 2, 3] }
// between
{ field: 'age', op: 'between', values: [18, 30] }
// is null / is not null
{ field: 'email', op: 'is null' }
// like
{ field: 'name', op: 'like', value: '%alice%' }
// 数组 = AND
[{ field: 'a', op: '=', value: 1 }, { field: 'b', op: '>', value: 2 }]
// OR 组
{ logic: 'OR', conditions: [{ field: 'x', op: '=', value: 1 }, { field: 'y', op: '=', value: 2 }] }原生查询
const { rows } = await db.raw('SELECT * FROM users WHERE age > ?', [18])
const { changes } = await db.raw('UPDATE users SET status = ?', ['active'])📋 Schema 导入导出
支持题目约定的完整 schema 结构 (columns / formItems / searchItems / fieldMappings / typeOverrides):
import { importSchema, exportSchema, schemaToFields, findSchema, mergeSchemas } from '@matrix-db-client/core'
// 1. 导入 (字符串 / 对象 / 数组均可)
const store = importSchema(jsonString)
// 或 const store = importSchema({ code: 0, data: [...] })
// 或 const store = importSchema([schema1, schema2])
// 2. 导出
const json = exportSchema(store.data) // → JSON 字符串
const json = exportSchema(store.data, false) // → 紧凑模式
// 3. Schema → FieldDef[] (直接用于 createTable)
const fields = schemaToFields(store.data[0])
await db.createTable('products', fields)
// 4. 查找 / 合并
const s = findSchema(store.data, { path: '/products' })
const merged = mergeSchemas(store1, store2)Schema 结构示例
{
"code": 0,
"data": [{
"id": "sch_dc2bb942c8qwih",
"siteId": "site_19f2cb544fv7mf",
"path": "/products",
"title": "商品管理",
"apiPath": "/products",
"icon": "ri:shopping-bag-3-line",
"columns": [
{ "prop": "name", "label": "名称", "minWidth": 160 },
{ "prop": "price", "label": "价格", "width": 120, "align": "right", "render": "number" },
{ "prop": "status", "label": "状态", "render": "tag",
"options": [{ "label": "启用", "value": "active", "type": "success" }] }
],
"formItems": [
{ "prop": "name", "label": "名称", "type": "input", "required": true },
{ "prop": "price", "label": "价格", "type": "float", "step": 0.01 },
{ "prop": "is_hot", "label": "热门", "type": "switch", "defaultValue": false }
],
"searchItems": [{ "prop": "name", "label": "名称", "type": "input" }],
"fieldMappings": {},
"typeOverrides": { "price": "number", "is_hot": "boolean" },
"rank": 1, "createdAt": 1784348031257, "updatedAt": 1784492065925
}]
}🟢 Nuxt 4 集成示例
Nitro server route (Node.js preset)
// server/api/products.post.ts
import { createClient } from '@matrix-db-client/core'
let db: Awaited<ReturnType<typeof createClient>>
export default defineEventHandler(async (event) => {
if (!db) db = await createClient({ type: 'sqlite', filename: './data.db' })
const body = await readBody(event)
const id = await db.insert('products', body)
return { code: 0, data: { id } }
})Cloudflare Pages preset (D1)
// server/utils/db.ts
import { createClient } from '@matrix-db-client/core'
export const useDb = () => {
const binding = useRuntimeConfig().cloudflare?.env?.DB
return createClient({ type: 'd1', binding })
}
// server/api/products.get.ts
export default defineEventHandler(async (event) => {
const db = await useDb()
return { code: 0, data: await db.find('products') }
})nuxt.config.ts:
export default defineNuxtConfig({
nitro: { preset: 'cloudflare-pages' }
})🧪 测试
# 运行全部测试
npm test
# watch 模式
npm run test:watch
# 覆盖率
npm run test:coverage测试覆盖:
core— schema 导入导出 (9)、SQL builder (26, 含 JOIN/UNION)、factory 检测 (5)、utils (6)、validator 校验 (16)sqlite— 真实 SQLite 集成 (14): 建表 / 字段 / 索引 / CRUD / 分页 / 复杂条件 / Schema 集成sqlite— 事务 + 日志集成 (9): transaction commit/rollback/转账场景, getLogs/setLogger/错误日志sqlite— 高级集成 (10): JOIN/UNION/bulkInsert/findStreamd1— Mock binding 集成 (4)mysql/pg/mongodb— 构造与配置校验 (各 3-4)cli— inspect/exportFromDb/runSql/validateSchemaFile (7)migrator— snapshot/diff/plan/up/down/selectMigrations/serialize (20)typegen— fieldsToInterface/schemaToInterface/fieldsToZodSchema/批量生成 (13)
🏗️ 构建
npm run build # 构建全部 9 个包 (ESM + CJS + d.ts)
npm run lint # tsc 类型检查
npm run clean # 清理 dist / node_modules每个包输出:
dist/index.js— ESMdist/index.cjs— CommonJSdist/index.d.ts— 类型声明
📐 类型系统
完整类型从 @matrix-db-client/core 导出:
import type {
DatabaseType, DataType, DatabaseConfig,
SqliteConfig, MysqlConfig, PgConfig, D1Config, MongoConfig,
FieldDef, FieldInfo, IndexDef, QueryOptions, WhereClause,
Condition, ConditionGroup, JoinClause, OrderDirection, Operator,
ID, RawResult, PageResult, IDatabaseAdapter,
TableSchema, ColumnSchema, FormItemSchema, SearchItemSchema, SchemaExport,
MatrixDBError
} from '@matrix-db-client/core'📄 License
MIT © kentpan [email protected]
