BBackOne Docsserver · utils · cli
Bun-nativeGitHub ↗
@geektech/backone-utils

数据库

多库 CRUD:Database / DatabaseManager / Table,where DSL 与事务。

db 模块基于 Bun 内置的 Bun.SQL(零运行时依赖),统一支持 SQLite / PostgreSQL / MySQL / MariaDB 四种方言。核心是三个类:Database(单连接)、DatabaseManager(多库管理)与 Table(单表 CRUD)。

建立连接

ts
import { Database } from '@geektech/backone-utils';

// SQLite 内存库(缺省 url 时)
const db = new Database();

// SQLite 文件
const db2 = new Database({ url: './data/app.db' });

// PostgreSQL / MySQL / MariaDB
const pg = new Database({ url: 'postgres://user:pass@localhost:5432/mydb' });
const my = new Database({ url: 'mysql://user:pass@localhost:3306/mydb' });
说明

方言缺省时按 url 推断,无法推断时按 sqlite 处理;也支持 url: ':memory:'、sqlite://:memory: 等形式。

多库管理 DatabaseManager

ts
const db = new DatabaseManager();
db.register('main', { url: process.env.PRIMARY_DB_URL });
db.register('analytics', { url: process.env.ANALYTICS_DB_URL, dialect: 'mysql' });

const users = db.get('main').table<User>('users');
db.has("main");       // true
db.names();           // ["main", "analytics"]
await db.remove("main"); // 关闭并移除
await db.close();     // 关闭全部

重复注册同名库抛 DB_ALREADY_REGISTERED,读取未注册库抛 DB_NOT_FOUND。

原生查询

query 支持标签模板(安全参数绑定)与纯字符串;raw 用 ? 占位符(Bun 统一参数化):

ts
// 标签模板:自动参数绑定
const rows = await db.query<Task[]>`SELECT * FROM tasks WHERE id = ${id}`;

// 原生 SQL(? 占位符)
const rows2 = await db.raw<Row[]>('SELECT * FROM tasks WHERE done = ?', [0]);

Table CRUD

ts
const tasks = db.table<Task>('tasks');

// 查询
await tasks.findById(1);
await tasks.findOne({ where: { title: { like: '%报表%' } } });
await tasks.findMany({ where: { done: 0 }, orderBy: { created_at: "desc" }, limit: 20 });
await tasks.count({ done: 1 });
await tasks.exists({ id: 5 });

// 写入
await tasks.insert({ title: "写周报", done: 0 });
await tasks.update({ done: 1 }, { id: 5 });
await tasks.delete({ id: 5 });

where 条件 DSL

裸值表示等值(null 表示 IS NULL);操作符对象支持比较 / 模糊 / 集合 / 空值 / 范围;AND / OR 数组组合子条件:

ts
const where = {
  age: { gte: 18 },
  status: { in: ['active', 'pending'] },
  name: { like: '%a%' },
  deletedAt: { isNull: true },
  OR: [{ city: 'x' }, { city: 'y' }],
};
操作符说明
eq / ne等于 / 不等于
gt / gte / lt / lte比较
like / notLike模糊匹配
in / notIn集合
isNull空值判断
between范围 [min, max]

排序与投影

ts
// 字符串 = 升序;对象支持多列
orderBy: { created_at: "desc", id: "asc" }

// 投影列
select: ["id", "title"] as const,

事务

回调中的查询在同一连接内原子执行,任一失败自动回滚;回调收到绑定到当前事务连接的 Database:

ts
const [a, b] = await db.transaction(async (tx) => {
  const table = tx.table<Item>('items');
  const a = await table.insert({ v: 1 });
  const b = await table.insert({ v: 2 });
  return [a, b];
});

方言差异

说明

PostgreSQL / SQLite 直接使用 RETURNING * 返回变更后的行;MySQL / MariaDB 通过 LAST_INSERT_ID / 前置 COUNT 回查,写入类操作返回的 rows 为空数组,count 表示匹配行数。 可调用 db.dialectSupportsReturning() 判断当前方言。

连接选项

选项说明
name库的业务名称(默认 "default")
url连接串;未传时按 sqlite 内存库处理
dialectsqlite / postgres / mysql / mariadb
readonly只读标记(业务语义)
max / idleTimeout / connectionTimeout / tls连接池参数(仅服务端方言生效)
bigintint8 等大整数按 BigInt 返回(默认按字符串)
onconnect / onclose连接建立 / 关闭回调