@gobing-ai/ts-db

中文文档
0.7.1发布于 2026/10/25Apache-2.0TypeScriptES Module构建来源已验证近 30 天下载 3758

@gobing-ai/ts-db — a drizzle-free database facade: typed DAOs over Bun SQLite / Cloudflare D1, a small predicate query spec, single-source-of-truth tables, and migrations. Drizzle stays an internal detail.

原始使用文档
文档目录17 节
  1. Overview
  2. Optional peers (validation)
  3. Migrating from 0.1.x
  4. Architecture
  5. How It Works
  6. Adapter pattern
  7. EntityDao — CRUD with soft delete
  8. QueueJobDao — job queue persistence
  9. InboxMessageDao — durable inter-agent messages
  10. Migrations
  11. Schema helpers
  12. Usage
  13. Install
  14. Define your schema
  15. Create a DAO
  16. Wire it up
  17. Running with Bun

@gobing-ai/ts-db

A drizzle-free database facade: typed DAOs over Bun SQLite / Cloudflare D1, a small predicate query spec, single-source-of-truth tables, and migration tooling. Drizzle ORM powers it internally but never appears in your application code — so the storage layer is swappable without touching call sites.

v0.2.x is a breaking redesign from 0.1.x. The public DbClient interface and adapter.getDb() are removed; DAOs now take a DbAdapter; where/orderBy use a ts-db predicate spec instead of drizzle expressions. See Migrating from 0.1.x.

Overview

Data-access code imports the main @gobing-ai/ts-db facade; schema definitions import @gobing-ai/ts-db/schema. Consumer code never imports drizzle-orm directly, which keeps the storage engine swappable and the query surface small and auditable. Two tiers, your choice:

  • Structured tier (EntityDao) — typed create/createMany/upsert/findById/findBy/update/delete/list/listByCursor/count, filtered by a small predicate spec ({ col, op, value }).
  • Raw tier (BaseDao) — query/one/tx for table-agnostic access; ETL/analytics/reporting DAOs extend this directly.
  • String-SQL escape (adapter.exec/run/queryFirst/queryAll) — for DDL and dynamic identifiers only.
ComponentPurpose
createDbAdapter / DbAdapterConstruction + lifecycle + string-SQL escape + atomic batch; exposes an internal typed db to the DAO layer only
BunSqliteAdapterBun SQLite implementation with statement caching and WAL pragmas (@gobing-ai/ts-db/bun-sqlite)
D1AdapterCloudflare D1 implementation (@gobing-ai/ts-db/d1; no @cloudflare/workers-types dependency)
BaseDaoRaw tier — query/one/tx, drizzle-free signatures
EntityDaoStructured CRUD — predicate filters, soft delete, RETURNING, batch, upsert, cursor pagination, composite PK
defineTableSingle source of truth — one table → drizzle table + derived zod insert/select schemas (@gobing-ai/ts-db/schema; optional peers)
Predicate / ListSpec / OrderTermThe drizzle-free query vocabulary
QueueJobDaoJob queue persistence — enqueue, claimReady, markCompleted, failExpiredJobs
InboxMessageDaoDurable inter-agent message persistence (@gobing-ai/ts-db/inbox)
applyMigrationsDrizzle migration runner (file-based + embedded fallback)
schema helpersstandardColumns, appendOnlyColumns, soft-delete columns (@gobing-ai/ts-db/schema)
SpanContextRe-exported from @gobing-ai/ts-runtime for telemetry

Optional peers (validation)

defineTable's insertSchema/selectSchema and DAO validation require the optional peers zod and drizzle-zod. Install them only if you use validation; the DAOs and queries work without them.

Migrating from 0.1.x

  • adapter.getDb() → adapter.db (internal typed db; rarely needed directly).
  • new SomeDao(adapter.getDb()) → new SomeDao(adapter) — DAOs now take the adapter, not a db handle.
  • EntityDao PK arg accepts an array: super(adapter, table, [table.id], 'name') (enables composite PKs).
  • 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 use RETURNING, so returned rows include DB-defaulted columns.

Architecture

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"

How It Works

Adapter pattern

createDbAdapter() selects the correct implementation based on driver config:

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 });

All adapters implement the same DbAdapter interface:

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');
// 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'] },
]);

EntityDao — CRUD with soft delete

Define a table through the schema subpath, extend EntityDao, get full CRUD for free:

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: '[email protected]' });
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

Soft delete is automatic for tables with an inUsed column (from standardColumnsWithSoftDelete). Call findById(id, true) to include soft-deleted records.

QueueJobDao — job queue persistence

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: '[email protected]' }, { 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 }

Delivery semantics: the lease path is at-least-once, never exactly-once. A claimed job whose lease expires (crash, lost renewal, stalled event loop) becomes claimable again and will execute a second time; the attempt token only fences the ack (a stale markCompleted/markFailed from the lost owner is ignored), it does not fence execution. Handlers must therefore be idempotent or carry their own dedup key — assume any claimed job can run more than once under failure.

InboxMessageDao — durable inter-agent messages

InboxMessageDao persists directed messages for team-mode or multi-agent workflows. It lives on the @gobing-ai/ts-db/inbox subpath so consumers can depend on the inbox surface without pulling schema helpers.

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');

Structural event sink

InboxMessageDao accepts an optional InboxMessageEventSink via the second constructor argument. The DAO depends only on the structural port (InboxMessageEventSink is a plain interface); it does not import @gobing-ai/ts-infra or EventBus. This follows the ProcessEventSink pattern from ADR-013.

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}`);
});

Events emitted (after the corresponding database mutation succeeds):

EventTriggerKey payload fields
message.enqueuedenqueue succeedsid, fromId, toId, inReplyTo?
message.injecteddrainPending returns rowsid, toId, inReplyTo?, injectAttempts
message.deliveredmarkDelivered succeedsid, toId, deliveredAt
message.failedmarkFailed succeedsid, toId, error

Omitting the sink preserves the existing contract — no no-op object is allocated and no event infrastructure is required.

Event delivery is best-effort and never changes the result of an already-committed mutation: the DAO does not await observers and contains synchronous throws or rejected thenables. Lifecycle observers can persist event payloads, so message bodies are deliberately excluded. The required message.failed.error field may be persisted; callers must pass a pre-redacted error string.

The inbox_messages table is additive and included in embedded migrations. It stores from_id, to_id, body, status, optional reply linkage, delivery timestamp, injection attempts, and the last injection error. The indexed access path is (to_id, status) for efficient pending drains.

Migrations

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 helpers

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

Usage

Install

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

Define your schema

// 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;

Create a DAO

// 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' });
    }
}

Wire it up

// 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');

Running with Bun

# Generate migrations
bun drizzle-kit generate

# Apply at startup
bun run src/index.ts

版本与发布记录

@gobing-ai/ts-db 共发布 139 个版本,首次发布于 2026/05/30;过去 12 个月发布了 139 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.1latest2026/10/2522 天前
0.7.02026/10/2522 天前
0.6.42026/10/2423 天前
0.6.32026/10/2424 天前
0.6.22026/10/2324 天前
0.6.12026/10/2324 天前

关于 @gobing-ai/ts-db 的常见问题

@gobing-ai/ts-db 是什么?

@gobing-ai/ts-db — a drizzle-free database facade: typed DAOs over Bun SQLite / Cloudflare D1, a small predicate query spec, single-source-of-truth tables, and migrations. Drizzle stays an internal detail.

如何安装 @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 和提交记录判断。