# @gobing-ai/ts-db 中文文档

规范地址：https://npmcn.com/package/%40gobing-ai/ts-db/

版本：0\.7\.1
npm 元数据更新时间：2026-10-25T00:56:03.614Z
中文译文更新时间：2026-11-16T17:51:39.849Z
软件包许可：Apache-2\.0

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40gobing-ai/ts-db
原文对照：https://npmcn.com/package/%40gobing-ai/ts-db/?lang=original
项目主页：https://github.com/gobing-ai/ts-libs#readme
源码仓库：https://github.com/gobing-ai/ts-libs

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：269 kB，90 个文件
- 模块格式：ES Module
- TypeScript 类型：包内自带
- 运行依赖：2 个
- peer 依赖：zod \>=3\.23\.0，drizzle-orm \>=0\.38\.0，drizzle-zod \>=0\.5\.0
- 首次发布：2026-05-29T16:56:24.827Z
- 最新版本发布：2026-10-25T00:56:03.220Z
- 近 30 天下载量：3758（2026-10-17 至 2026-11-15，npm 官方下载统计）
- 已发布版本数：139（近 12 个月 139 个）

## 中文简介

@gobing-ai/ts-db — 一个无细雨的数据库外观:键入了DAOs over Bun SQLite / Cloudflare D1,一个小型的上游查询光谱,单源真实表,以及迁移. 德瑞兹留作内部细节.

## 安装

```sh
npm install @gobing-ai/ts-db
```

也可以使用：`pnpm add @gobing-ai/ts-db`、`yarn add @gobing-ai/ts-db`、`bun add @gobing-ai/ts-db`

## README

# @gobing-ai/ts-db (英语)

A 类 **无细雨数据库外观**: 在 Bun SQLite / Cloudflare D1 上键入 DAOs, 是一个小的上游查询光谱, 单源真实表, 以及迁移工具 。 Drizzle ORM在内部赋予它,但从未出现在您的应用程序代码中——因此存储层可以互换而无需触碰呼叫站点.

> **v0.2.x是从0.1.x.** 公众 `DbClient` 接口和 `adapter.getDb()` 删除; DAOs 现在使用 `DbAdapter`· ; `where`编号 :`orderBy` 使用 ts-db 上游光谱来代替细雨表达式。 见 [从0.1.x迁移](https://npmcn.com/package/%40gobing-ai/ts-db/#readme-migrating-from-01x)。 。 。 .

## 概览

数据访问码导入主 `@gobing-ai/ts-db` 外观; 计划定义导入 `@gobing-ai/ts-db/schema`消费代码从未进口 `drizzle-orm` 直接保留 存储引擎可互换和查询表面小而可审计。 两层,你的选择:

-   **结构层次** (单位:千美元)`EntityDao`)——已打入 `create`编号 :`createMany`编号 :`upsert`编号 :`findById`编号 :`findBy`编号 :`update`编号 :`delete`编号 :`list`编号 :`listByCursor`编号 :`count`,由小的上游光谱过滤(`{ col, op, value }`) (中文(简体) ).
-   **初级** (单位:千美元)`BaseDao`(b) —— `query`编号 :`one`编号 :`tx` ;ETL/分析/报告DAOs直接扩展.
-   **字符串- SQL 逃脱** (单位:千美元)`adapter.exec`编号 :`run`编号 :`queryFirst`编号 :`queryAll`)——仅用于DDL和动态标识.

| 构成部分 | 目的 |
| --- | --- |
| `createDbAdapter` 编号 : `DbAdapter` | 构造 + 生命周期 + 字符串- SQL 逃出 + 原子批; 仅将内部打出 db 显示于 DAO 层 |
| `BunSqliteAdapter` | 装有语句缓存和WAL pragmas的 Bun SQLite 执行(`@gobing-ai/ts-db/bun-sqlite`(中文(简体) ) |
| `D1Adapter` | 云花板D1的执行(`@gobing-ai/ts-db/d1`; 无 `@cloudflare/workers-types` 扶养) |
| `BaseDao` | 原始级别 - `query`编号 :`one`编号 :`tx`,无细雨签名 |
| `EntityDao` | 结构化 CRUD — 上游滤波器, 软删除, 返回, 批量, 上移, 光标平移, 复合 PK |
| `defineTable` | 单一的真相来源——一个表格——细小的表格+衍生出 Zod 插入/选择计划(`@gobing-ai/ts-db/schema`; 可选同伴) |
| `Predicate` 编号 : `ListSpec` 编号 : `OrderTerm` | 无细雨查询词汇 |
| `QueueJobDao` | 任务队列持续性 —— `enqueue`, (中文(简体) ), `claimReady`, (中文(简体) ), `markCompleted`, (中文(简体) ), `failExpiredJobs` |
| `InboxMessageDao` | 持久的代理信息持久性(`@gobing-ai/ts-db/inbox`(中文(简体) ) |
| `applyMigrations` | Drizzle 迁移跑道( 文件 + 嵌入式倒计时) |
| `schema` 帮助者 | `standardColumns`, (中文(简体) ), `appendOnlyColumns`,软删除列(`@gobing-ai/ts-db/schema`(中文(简体) ) |
| `SpanContext` | 从 `@gobing-ai/ts-runtime` 用于遥测 |

### 可选同行(认证)

`defineTable`是因为 `insertSchema`编号 :`selectSchema` 和 DAO 验证要求 **选项** 同行 `zod` 财务报告和审定财务报表 `drizzle-zod`。只有当您使用验证时才安装它们; DAOs 和查询工作没有它们.

### 从0.1.x迁移

-   `adapter.getDb()` → `adapter.db` (内部输入db;很少直接需要).
-   `new SomeDao(adapter.getDb())` → `new SomeDao(adapter)` ——DAOs现在取出适配器,而不是DB手柄.
-   `EntityDao` PK 参数接受数组 : `super(adapter, table, [table.id], 'name')` (可计量复合PK).
-   `BaseDao.withTransaction` → `tx`。 。 。 .
-   `list({ where: eq(col, v) })` → `list({ where: { col, op: 'eq', value: v } })`。 。 。 .
-   `count(eq(col, v))` → `count({ col, op: 'eq', value: v })`。 。 。 .
-   `create`编号 :`update` 使用情况 `RETURNING`,因此返回的行包括已默认的 DB 列.

## 建筑

```mermaid
classDiagram
    class DbAdapter {
        <<interface>>
        +db InternalDb (internal)
        +exec(sql) void
        +run(sql, ...params) void
        +queryFirst(sql, ...params) T?
        +queryAll(sql, ...params) T[]
        +batch(operations) void
        +close() void
    }

    class BunSqliteAdapter {
        -Database sqlite
        -drizzleDb
        -stmtCache
        +getDrizzleDb()
    }

    class D1Adapter {
        -binding
        -drizzleDb
        +getBinding()
    }

    class BaseDao {
        <<abstract>>
        #db
        +now() number
        +tx(fn) T
        +query(table, spec) T[]
        +one(table, where) T?
    }

    class EntityDao {
        +create(data) TSelect
        +createMany(rows) TSelect[]
        +upsert(data, conflict) TSelect
        +findById(id) TSelect?
        +update(id, data) TSelect?
        +delete(id, soft?) TSelect?
        +findBy(column, value) TSelect?
        +list(spec) TSelect[]
        +listByCursor(spec) Page
        +count(where?) number
    }

    class QueueJobDao {
        +enqueue(type, payload, opts?) string
        +enqueueBatch(jobs) string[]
        +claimReady(batchSize) QueueJobRecord[]
        +markProcessing(ids) void
        +markCompleted(id) void
        +markFailed(id, attempts, error) void
        +markForRetry(id, attempts, error, nextRetryAt) void
        +resetStuckJobs(timeout) number
        +failExpiredJobs() number
        +getStats() QueueStats
    }

    class InboxMessageDao {
        +enqueue(fromId, toId, body, inReplyTo?) string
        +drainPending(toId) InboxMessage[]
        +markDelivered(msgId) void
        +markFailed(msgId, error) void
        +inbox(toId, limit?, offset?) InboxMessage[]
        +countPending(toId) number
    }

    class ColumnHelpers {
        +standardColumns
        +standardColumnsWithSoftDelete
        +appendOnlyColumns
    }

    class QueueJobsTable {
        +queueJobs
    }

    class InboxMessagesTable {
        +inboxMessages
    }

    class MigrationRunner {
        +applyMigrations(adapter, opts?) void
    }

    class EmbeddedMigrations {
        +embeddedMigrations EmbeddedMigration[]
    }

    DbAdapter <|.. BunSqliteAdapter : implements
    DbAdapter <|.. D1Adapter : implements
    BaseDao <|-- EntityDao : extends
    EntityDao <|-- QueueJobDao : extends
    EntityDao <|-- InboxMessageDao : extends
    QueueJobDao --> QueueJobsTable : "uses"
    InboxMessageDao --> InboxMessagesTable : "uses"
    MigrationRunner --> EmbeddedMigrations : "uses"
    MigrationRunner --> BunSqliteAdapter : "requires"
```

## 如何运作

### 适应器模式

`createDbAdapter()` 根据驱动程序配置选择正确的执行 :

```ts
import { createDbAdapter } from '@gobing-ai/ts-db';

// Bun SQLite (in-memory)
const adapter = await createDbAdapter({ driver: 'bun-sqlite', url: ':memory:' });

// Bun SQLite (file-based with pragmas)
const adapter = await createDbAdapter({
    driver: 'bun-sqlite',
    url: './data/app.db',
    pragmas: { journalMode: 'PRAGMA journal_mode = WAL' },
});

// Cloudflare D1
const adapter = await createDbAdapter({ driver: 'd1', binding: env.DB });
```

所有适配器执行相同的 `DbAdapter` 接口 :

```ts
await adapter.exec('CREATE TABLE users (id TEXT PRIMARY KEY, name TEXT)');
await adapter.run('INSERT INTO users VALUES (?, ?)', 'u1', 'Alice');
const user = await adapter.queryFirst<{ name: string }>('SELECT name FROM users WHERE id = ?', 'u1');
const all = await adapter.queryAll<{ name: string }>('SELECT name FROM users');
```

```ts
// Atomic multi-statement batch — all succeed or all roll back (ADR-020)
await adapter.batch([
    { sql: 'INSERT INTO users VALUES (?, ?)', params: ['u2', 'Bob'] },
    { sql: 'UPDATE counters SET count = count + 1 WHERE name = ?', params: ['users'] },
]);
```

### 实体Dao — 有软删除的 CRUD

通过子路径定义表格, 延伸 `EntityDao`,免费获得完整的 CRUD:

```ts
import { type DbAdapter, EntityDao } from '@gobing-ai/ts-db';
import { defineTable, standardColumns, text } from '@gobing-ai/ts-db/schema';

const users = defineTable('users', {
    id: text('id').primaryKey(),
    name: text('name').notNull(),
    email: text('email').notNull(),
    ...standardColumns,
}).table;

class UsersDao extends EntityDao<typeof users, typeof users.id> {
    constructor(adapter: DbAdapter) {
        super(adapter, users, [users.id], 'users');
    }

    async findByEmail(email: string) {
        return this.findBy(users.email, email);
    }
}

// Usage
const dao = new UsersDao(adapter);
const user = await dao.create({ id: 'u1', name: 'Alice', email: 'a@test.com' });
const found = await dao.findById('u1');
const updated = await dao.update('u1', { name: 'Alice Updated' });
const page = await dao.list({ limit: 20, offset: 0 });
const total = await dao.count();
await dao.delete('u1'); // soft delete if table has `inUsed` column
```

**软删除** 自动为带有 `inUsed` 列(从) `standardColumnsWithSoftDelete`) (中文(简体) ). 打电话 `findById(id, true)` 包括软删除记录.

### 队列JobDao——任务队列持续

```ts
import { QueueJobDao } from '@gobing-ai/ts-db';

const queue = new QueueJobDao(adapter);

// Enqueue — maxRetries is a total attempt budget, not retries after the first:
// 5 means up to 5 attempts, and `maxRetries: 1` runs the job once with no retry.
// timeoutMs is the per-job execution policy: a positive ms deadline, or explicit
// `null` = unlimited (omitted = inherit the consumer default).
const jobId = await queue.enqueue('send-email', { to: 'user@test.com' }, { maxRetries: 5, timeoutMs: 60_000 });

// Consumer: claim ready jobs atomically. claimReady leases each job (mints an
// attempt token); renew the lease while the handler runs, then ack with the
// token — fenced acks are ignored if ownership was lost mid-run.
const jobs = await queue.claimReady(10, { leaseMs: 30_000 });
await queue.renewLease(jobs[0].id, jobs[0].attemptToken, 30_000);

for (const job of jobs) {
    try {
        await processJob(job);
        await queue.markCompleted(job.id, job.attemptToken);
    } catch (error) {
        if (job.attempts >= job.maxRetries) {
            await queue.markFailed(job.id, job.attempts + 1, String(error), job.attemptToken);
        } else {
            const retryAt = Date.now() + Math.pow(2, job.attempts) * 1000;
            await queue.markForRetry(job.id, job.attempts + 1, String(error), retryAt, job.attemptToken);
        }
    }
}

// Maintenance
await queue.resetStuckJobs(30_000); // reset stuck after 30s
await queue.failExpiredJobs(); // fail expired TTL jobs

const stats = await queue.getStats();
// → { pending: 5, processing: 2, completed: 100, failed: 3 }
```

**发送语义 :** 租赁路径是 **至少一次,从来没有完全一次**A级 租约到期(崩溃、续约失败、事件循环停滞) 可再次要求,并将再次执行;尝试符号只设置栅栏 _亚克_ (已过时) `markCompleted`编号 :`markFailed` 从失去的主人被忽略,它 不设栅栏执行。 因此,处理者必须具有本能或携带自己的 dadup key——假设任何声称的工作在失败的情况下可以不止一次运行.

### InboxMessageDao — 持久的代理信件

`InboxMessageDao` 持续为团队模式或多代理工作流程提供直接信息。 它靠着 `@gobing-ai/ts-db/inbox` 子路径使消费者可以依赖收件箱表面而不拉出计划 帮手.

```ts
import { InboxMessageDao } from '@gobing-ai/ts-db/inbox';

const inbox = new InboxMessageDao(adapter);

// Operator sends a task to an agent.
const msgId = await inbox.enqueue(null, 'coder', 'Please inspect packages/db');

// Agent process startup/live-injection path atomically drains queued work.
const pending = await inbox.drainPending('coder');
for (const msg of pending) {
    try {
        await injectIntoAgentStdin(`[task from=${msg.fromId ?? 'operator'} id=${msg.id}] ${msg.body}`);
        await inbox.markDelivered(msg.id);
    } catch (error) {
        await inbox.markFailed(msg.id, String(error));
    }
}

const history = await inbox.inbox('coder', 20);
const queued = await inbox.countPending('coder');
```

#### 结构事件汇

`InboxMessageDao` 接受可选选项 `InboxMessageEventSink` 通过第二个构造器 参数。 DAO只依赖于结构端口(`InboxMessageEventSink` 是一个平地 界面; 它确实 **没有** 导入 `@gobing-ai/ts-infra` 或者说 `EventBus`。这跟随 `ProcessEventSink` 图案来源于ADR-013.

```ts
import { type BusLifecycleEvents, EventBus } from '@gobing-ai/ts-infra';
import { InboxMessageDao, type InboxMessageEvents } from '@gobing-ai/ts-db/inbox';

// Pass an EventBus directly as the structural sink — no adapter class needed.
const lifecycleBus = new EventBus<BusLifecycleEvents>();
const events = new EventBus<InboxMessageEvents>({ lifecycleBus });
const inbox = new InboxMessageDao(adapter, { events });
events.on('message.enqueued', (detail) => {
    console.log(`message ${detail.id} from ${detail.fromId ?? 'operator'} to ${detail.toId}`);
});
```

**排放的事件** (在相应的数据库突变成功后):

| 活动 | 触发 | 关键有效载荷域 |
| --- | --- | --- |
| `message.enqueued` | `enqueue` 继承 | `id`, (中文(简体) ), `fromId`, (中文(简体) ), `toId`, (中文(简体) ), `inReplyTo?` |
| `message.injected` | `drainPending` 返回行 | `id`, (中文(简体) ), `toId`, (中文(简体) ), `inReplyTo?`, (中文(简体) ), `injectAttempts` |
| `message.delivered` | `markDelivered` 继承 | `id`, (中文(简体) ), `toId`, (中文(简体) ), `deliveredAt` |
| `message.failed` | `markFailed` 继承 | `id`, (中文(简体) ), `toId`, (中文(简体) ), `error` |

关闭水槽保留现有合同——没有分配对象,没有 需要建立事件基础设施.

事件交付是最佳的,永远不会改变已经承诺的突变的结果: dAO 不等待观察者, 包含同步抛出或拒绝的可当量 。 生命周期 观察者可以坚持事件有效载荷,因此信息机构被故意排除在外. 所需数额 `message.failed.error` 字段可能会被坚持;调用者必须通过预先编辑的错误字符串.

这个 `inbox_messages` 表格是添加剂,并包含在嵌入式迁移中。 它储存 `from_id`, (中文(简体) ), `to_id`, (中文(简体) ), `body`, (中文(简体) ), `status`、可选的回复链接、交货时间戳、注射尝试和 上次注射错误。 索引访问路径为 `(to_id, status)` 用于高效的待排水管.

### 移徙

```ts
import { applyMigrations } from '@gobing-ai/ts-db';
import { BunSqliteAdapter } from '@gobing-ai/ts-db/bun-sqlite';

const adapter = new BunSqliteAdapter({ databaseUrl: './data/app.db' });

// Applies pending migrations from drizzle/ folder (file-based)
// Falls back to embedded SQL if no folder exists (compiled binaries, CF Workers)
await applyMigrations(adapter);

// Safe to call on every startup — already-applied migrations are skipped
```

### Schema 帮助者

```ts
import {
    defineTable,
    inboxMessages,
    queueJobs,
    standardColumns,
    standardColumnsWithSoftDelete,
    text,
} from '@gobing-ai/ts-db/schema';

// Standard columns (createdAt, updatedAt)
const docs = defineTable('docs', {
    id: text('id').primaryKey(),
    title: text('title').notNull(),
    ...standardColumns,
}).table;

// With soft delete (adds inUsed column)
const projects = defineTable('projects', {
    id: text('id').primaryKey(),
    name: text('name').notNull(),
    ...standardColumnsWithSoftDelete,
}).table;

// queue_jobs table is pre-built for use with QueueJobDao

// inbox_messages table is pre-built for use with InboxMessageDao
```

## 使用量

### 安装

```bash
bun add @gobing-ai/ts-db drizzle-orm
bun add -D drizzle-kit
```

### 定义您的方案

```ts
// src/schema.ts
import { defineTable, standardColumns, text } from '@gobing-ai/ts-db/schema';

export const todos = defineTable('todos', {
    id: text('id').primaryKey(),
    title: text('title').notNull(),
    done: text('done').notNull().default('0'),
    ...standardColumns,
}).table;
```

### 创建 DAO

```ts
// src/todos-dao.ts
import type { DbAdapter } from '@gobing-ai/ts-db';
import { EntityDao } from '@gobing-ai/ts-db';
import { todos } from './schema';

export class TodosDao extends EntityDao<typeof todos, typeof todos.id> {
    constructor(adapter: DbAdapter) {
        super(adapter, todos, [todos.id], 'todos');
    }

    async findPending() {
        return this.findAllBy(todos.done, '0');
    }

    async markDone(id: string) {
        return this.update(id, { done: '1' });
    }
}
```

### 把它接起来

```ts
// src/index.ts
import { createDbAdapter, applyMigrations } from '@gobing-ai/ts-db';
import { TodosDao } from './todos-dao';

const adapter = await createDbAdapter({ driver: 'bun-sqlite', url: ':memory:' });
await applyMigrations(adapter);

const todos = new TodosDao(adapter);

await todos.create({ id: '1', title: 'Learn ts-db' });
await todos.create({ id: '2', title: 'Build something' });

const pending = await todos.findPending();
// → [{ id: '1', ... }, { id: '2', ... }]

await todos.markDone('1');
```

### 与 Bun 运行

```bash
# Generate migrations
bun drizzle-kit generate

# Apply at startup
bun run src/index.ts
```

## 常见问题

### @gobing-ai/ts-db 是什么？

@gobing-ai/ts-db — 一个无细雨的数据库外观:键入了DAOs over Bun SQLite / Cloudflare D1,一个小型的上游查询光谱,单源真实表,以及迁移\. 德瑞兹留作内部细节\.

### 如何安装 @gobing-ai/ts-db？

在项目目录运行 npm install @gobing-ai/ts-db，或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖：drizzle-orm（\>=0\.38\.0）。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖，Yarn 需要手动安装。

### @gobing-ai/ts-db 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @gobing-ai/ts-db 支持 ESM 还是 CommonJS？

以 ES Module 形式发布，推荐使用 import 引入。在 CommonJS 项目中，Node\.js 20\.19\+ / 22\.12\+ 可以直接 require\(\) 不含顶层 await 的 ES Module，更早的版本需要改用动态 import\(\)。

### @gobing-ai/ts-db 可以商用吗？

@gobing-ai/ts-db 使用 Apache-2\.0 许可。宽松许可：允许商业使用、修改和再分发，并附带明确的专利授权；分发时需保留许可与 NOTICE 文件，修改过的文件要注明改动。以上为概括，不构成法律意见，请以许可原文为准。

### @gobing-ai/ts-db 的下载量有多少？

根据 npm 官方下载统计，@gobing-ai/ts-db 在 2026/10/17 – 2026/11/15 这 30 天内被下载 3,758 次，日均约 125 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @gobing-ai/ts-db 还在维护吗？

最新版本 0\.7\.1 发布于 2026/10/25（22 天前）；至今共发布 139 个版本，其中过去 12 个月发布了 139 个；首次发布于 2026/05/30。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

