agentbase-docs

数据库

这是什么 / 何时用

TablesDB 是 Agentbase 的结构化数据库面:数据库 → 表 → 列 / 索引 → 行,支持事务、批量、聚合与行级权限(权限模型见 permissions.md)。新项目一律优先 TablesDB;DocumentsDB(collection / document 语义)是旧文档面,仅维护旧数据或明确需要 Documents API 时使用。

前置

使用骨架

关键参数与返回

层方法族关键返回
数据库create/get/list/update/deleteModels.Database(storageTotal 等元数据)
表createTable/getTable/listTables/updateTable/deleteTableModels.Table(rowSecurity、enabled、$permissions、columns、indexes)
列create*Column/update*Column/getColumn/listColumns/deleteColumn/updateColumnComment各 ColumnXxx(带 `status: processingavailable...`)
索引createIndex/getIndex/listIndexes/deleteIndexModels.Index(`type: keyuniquefulltextspatial`)
行createRow/getRow/listRows/updateRow/upsertRow/deleteRow + 批量/增减Models.Row(业务 data + $id、$createdAt、$permissions 等);列表返回 rows/total
事务createTransaction/createOperations/updateTransaction/...Models.Transaction(状态与操作日志)
聚合aggregateRowsModels.RowAggregation
Schema 版本createSchemaVersion/getSchemaVersion/listSchemaVersions/rollbackSchemaVersionModels.SchemaVersion(版本号、状态、schemaHash)

createIndex 的排序参数用 SDK 枚举(如 OrderBy.ASC/DESC),索引用 TablesDBIndexType 等枚举;以各 SDK 导出为准。

错误与边界

SDK 类别差异

各语言调用示例

以下按使用骨架逐项给出各语言调用示例;每个卡片可切换语言(全页同步)。

建库

库是表的上层容器;创建后可 get / list / update / delete 管理生命周期,enabled: false 只挡用户侧访问,API Key 仍可读写。

import { TablesDB } from 'agentbase-node-sdk';
const tablesDB = new TablesDB(client);

await tablesDB.create({ databaseId: 'app-db', name: 'App', enabled: true });
await tablesDB.get({ databaseId: 'app-db' });
await tablesDB.list({ queries: [], total: true });
await tablesDB.update({ databaseId: 'app-db', name: 'App2' });
await tablesDB.delete({ databaseId: 'app-db' });

建表(内联列与索引)

createTable 一次性传入 columns / indexes(同步建表)。内联 columns 走 Attributes 校验器:type 只接受 string(配 size,可选 format: email|enum|ip|url,enum 须带 elements)、integer、double、boolean、datetime、point、linestring、polygon;relationship 关系列不能内联。indexes[].type 取 key / unique / fulltext / spatial,attributes 不能引用系统字段。

await tablesDB.createTable({
  databaseId: 'app-db',
  tableId: 'tasks',
  name: 'Tasks',
  rowSecurity: true,
  columns: [
    { key: 'title', type: 'string', size: 256, required: true },
    { key: 'status', type: 'string', size: 64, required: true,
      format: 'enum', elements: ['draft', 'published', 'archived'] },
    { key: 'score', type: 'double', required: false },
    { key: 'done', type: 'boolean', required: false },
    { key: 'created_at', type: 'datetime', required: false },
  ],
  indexes: [
    { key: 'idx_title', type: 'unique', attributes: ['title'] },
    { key: 'idx_title_fulltext', type: 'fulltext', attributes: ['title'] },
  ],
});

增量列

表已存在后按类型加列,多为 202 异步任务:status 从 processing 到 available 后才可用于写入。每类均有 update*Column,getColumn / listColumns / deleteColumn 管理。

// 17 种类型各有 create<Type>Column,例如:
await tablesDB.createStringColumn({
  databaseId: 'app-db', tableId: 'tasks',
  key: 'nickname', size: 64, required: false,
});
await tablesDB.createIntegerColumn({
  databaseId: 'app-db', tableId: 'tasks',
  key: 'views', required: false, min: 0,
});
await tablesDB.createRelationshipColumn({
  databaseId: 'app-db', tableId: 'tasks',
  key: 'owner', relatedTableId: 'users', type: 'manyToOne',
});

const col = await tablesDB.getColumn({ databaseId: 'app-db', tableId: 'tasks', key: 'nickname' });
// col.status === 'available' 后才可写入

列注释

维护列的展示名(2.6.0 扩展);comment 传空即清除,仅改展示名,通常零 DDL。

await tablesDB.updateColumnComment({
  databaseId: 'app-db', tableId: 'tasks', key: 'title', comment: '任务标题',
});

行读写

单条 CRUD、批量(createRows / upsertRows / updateRows / deleteRows)、幂等 upsertRow 与单列原子 incrementRowColumn / decrementRowColumn。批量更新/删除无 queries 时作用于全表。

await tablesDB.createRow('app-db', 'tasks', ID.unique(), { title: '写周报' });
await tablesDB.getRow('app-db', 'tasks', '<rowId>');
await tablesDB.updateRow('app-db', 'tasks', '<rowId>', { done: true });
await tablesDB.upsertRow('app-db', 'tasks', '<rowId>', { title: '写周报', done: false });
await tablesDB.createRows('app-db', 'tasks', [
  { data: { title: 'A' } },
  { data: { title: 'B' } },
]);
await tablesDB.incrementRowColumn('app-db', 'tasks', '<rowId>', 'views', 1);   // 越界(max/min)抛错
await tablesDB.deleteRow('app-db', 'tasks', '<rowId>');

查询与分页

Query 构造器组合过滤、排序、分页与游标;列表默认返回 total,total: false 可省计数。REST 侧查询是可重复的 queries[] 参数。

import { Query } from 'agentbase-node-sdk';

const rows = await tablesDB.listRows('app-db', 'tasks', [
  Query.equal('done', false),
  Query.greaterThan('score', 60),
  Query.orderDesc('$createdAt'),
  Query.limit(25),
  Query.cursorAfter('<lastId>'),
]);

事务

事务是项目级对象:创建 → 暂存操作(可分多次追加)→ 提交或回滚。commit 前操作对外不可见;行读写端点也可传 transactionId 挂到事务。

const tx = await tablesDB.createTransaction({ ttl: 60 });
await tablesDB.createOperations({
  transactionId: tx.$id,
  operations: [
    { databaseId: 'app-db', tableId: 'tasks', action: 'create', rowId: ID.unique(), data: { title: 'A' } },
    { databaseId: 'app-db', tableId: 'tasks', action: 'update', rowId: '<rowId>', data: { done: true } },
  ],
});
await tablesDB.updateTransaction({ transactionId: tx.$id, commit: true });
// 或 rollback: true 丢弃

行聚合

服务端聚合(count / sum / avg / min / max,可分组),不拉全表;普通列必须出现在 groupBy,queries 仅接受过滤条件。

const stats = await tablesDB.aggregateRows({
  databaseId: 'app-db',
  tableId: 'tasks',
  select: ['count'],
  queries: [Query.equal('done', false)],
  groupBy: ['done'],
});

Schema 版本与回滚

提交完整结构 JSON(不是 diff patch)生成版本并自动迁移,轮询版本终态;mode 缺省 migration,baseline 仅在把当前物理结构采纳为首活跃版本时用。回滚只切换生效指针(重算列可见性),不执行物理 DDL、不改数据。同一数据库同时只允许一个 in-flight 版本(重复提交 409)。

const before = await tablesDB.listSchemaVersions({ databaseId: 'app-db', queries: [], total: true });
// 保存当前 active 版本 id 作为回滚锚点

const submitted = await tablesDB.createSchemaVersion({
  databaseId: 'app-db',
  schema: { tables: [/* 已 review 的完整结构 JSON */] },
});
const v = await tablesDB.getSchemaVersion({ databaseId: 'app-db', versionId: submitted.$id });
// 轮询至 status: active / failed(stepsCompleted / stepsTotal / errorMessage 可观测)

// 仅当完成兼容性评审后回滚:
// await tablesDB.rollbackSchemaVersion({ databaseId: 'app-db', versionId: '<activeVersionId>' });

示例指引

事实源