@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迁移。 。 。 .
概览
数据访问码导入主 @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手柄.EntityDaoPK 参数接受数组 :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 列.
建筑
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() 根据驱动程序配置选择正确的执行 :
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 接口 :
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'] },
]);
实体Dao — 有软删除的 CRUD
通过子路径定义表格, 延伸 EntityDao,免费获得完整的 CRUD:
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
软删除 自动为带有 inUsed 列(从) standardColumnsWithSoftDelete) (中文(简体) ). 打电话 findById(id, true) 包括软删除记录.
队列JobDao——任务队列持续
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 }
发送语义 : 租赁路径是 至少一次,从来没有完全一次A级
租约到期(崩溃、续约失败、事件循环停滞)
可再次要求,并将再次执行;尝试符号只设置栅栏
亚克 (已过时) markCompleted编号 :markFailed 从失去的主人被忽略,它
不设栅栏执行。 因此,处理者必须具有本能或携带自己的
dadup key——假设任何声称的工作在失败的情况下可以不止一次运行.
InboxMessageDao — 持久的代理信件
InboxMessageDao 持续为团队模式或多代理工作流程提供直接信息。 它靠着
@gobing-ai/ts-db/inbox 子路径使消费者可以依赖收件箱表面而不拉出计划
帮手.
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.
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) 用于高效的待排水管.
移徙
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 帮助者
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
使用量
安装
bun add @gobing-ai/ts-db drizzle-orm
bun add -D drizzle-kit
定义您的方案
// 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
// 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' });
}
}
把它接起来
// 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 运行
# Generate migrations
bun drizzle-kit generate
# Apply at startup
bun run src/index.ts