Docs
Contents

Databases

Overview and use cases

TablesDB is Agentbase's structured database plane: database → table → column / index → row, supporting transactions, batching, aggregation, and row-level permissions (for the permission model, see permissions.md). New projects should always prefer TablesDB; DocumentsDB (collection / document semantics) is the legacy document plane, used only for maintaining legacy data or when the Documents API is explicitly required.

Prerequisites

Usage workflow

  1. Create database: tablesDB.create({ databaseId, name }); list / get / update / delete to manage the lifecycle.

  2. Create table: createTable({ databaseId, tableId, name, permissions, rowSecurity, enabled, columns, indexes, comment }) (permissions, rowSecurity, enabled, columns, indexes, comment are all optional).

    • Inline columns goes through the Attributes validator: type only accepts string (with size, optional format: email|enum|ip|url, enum must include elements), integer, double (note: not float), boolean, datetime, point, linestring, polygon.

    • relationshipRelationship columns cannot be created inline; use createRelationshipColumn after the table is created.

    • indexes: type takes key / unique / fulltext / spatial; attributes can only reference explicit business columns, not system fields such as $id or $createdAt.

  3. Incremental columns: after a table exists, use createStringColumn / createVarcharColumn / createTextColumn / createLongtextColumn / createMediumtextColumn / createEmailColumn / createEnumColumn / createUrlColumn / createIpColumn / createIntegerColumn / createFloatColumn / createBooleanColumn / createDatetimeColumn / createPointColumn / createLineColumn / createPolygonColumn / createRelationshipColumn (each has update*Column and getColumn / listColumns / deleteColumn). Incremental columns are mostly 202 asynchronous tasks; the status must go from processing to available before they can be used for writes.

  4. Column annotations (2.6.0 Node extension): updateColumnComment({ databaseId, tableId, key, comment }) (comment optional) to maintain column descriptions.

  5. Row CRUD: createRow / getRow / listRows / updateRow / deleteRow; batch createRows / upsertRows / updateRows / deleteRows; single-column atomic incrementRowColumn / decrementRowColumn; upsertRow to create or update a row by ID.

  6. Queries: Query.equal/notEqual/greaterThan/lessThan/between/contains/startsWith/search/in/orderAsc/orderDesc/limit/offset/cursorAfter/cursorBefore/or/and/not, etc.; lists are paginated by default, and total: false can omit the total count.

  7. Transactions: createTransaction({ ttl }) (ttl optional) → createOperations({ transactionId, operations[] }) (action: create/update/upsert/delete/increment/...) → updateTransaction({ commit: true }) to commit or rollback: true to roll back; listTransactions / getTransaction / deleteTransaction for management.

  8. Row aggregation (2.6.0 Node extension): aggregateRows({ databaseId, tableId, select[], queries, groupBy, transactionId }) (queries, groupBy, transactionId are all optional) returns aggregated rows.

  9. Schema versions and rollback (2.6.0 already available): createSchemaVersion({ databaseId, schema, mode }) (mode optional) (mode: 'migration' (default) / 'baseline' — use baseline only when adopting the current running structure as the first effective version); getSchemaVersion / listSchemaVersions({ databaseId, queries, total }) (queries, total are both optional) (in descending order by version number); rollbackSchemaVersion({ databaseId, versionId }) switches the effective pointer back to a historical version — it only updates the pointer, does not execute physical DDL, and does not change data.

Key parameters and returns

PlaneMethod familyKey returns
Databasecreate / get / list / update / deleteModels.Database (storageTotal and other metadata)
TablecreateTable / getTable / listTables / updateTable / deleteTableModels.Table (rowSecurity, enabled, $permissions, columns, indexes)
Columncreate*Column / update*Column / getColumn / listColumns / deleteColumn / updateColumnCommenteach ColumnXxx (with status: processing|available|...)
IndexcreateIndex / getIndex / listIndexes / deleteIndexModels.Index (type: key|unique|fulltext|spatial)
RowcreateRow / getRow / listRows / updateRow / upsertRow / deleteRow + batch/increment-decrementModels.Row (business data + $id, $createdAt, $permissions, etc.); lists return rows/total
TransactioncreateTransaction / createOperations / updateTransaction / ...Models.Transaction (status and operation log)
AggregationaggregateRowsModels.RowAggregation
Schema versioncreateSchemaVersion / getSchemaVersion / listSchemaVersions / rollbackSchemaVersionModels.SchemaVersion (version number, status, schemaHash)

The sort parameters of createIndex use SDK enums (e.g., OrderBy.ASC/DESC), and indexes use enums such as TablesDBIndexType; refer to each SDK's exports.

Errors and boundaries

SDK Category Differences

Examples by language

The following provides examples by language, item by item along the usage workflow; each card can switch languages (synced across the page).

Create database

A database is the upper-level container for tables; after creation, you can use get / list / update / delete to manage the lifecycle, and enabled: false only blocks user-side access while API Keys can still read and write.

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

Create table (inline columns and indexes)

createTable passes in columns / indexes in one call (synchronous table creation). Inline columns goes through the Attributes validator: type only accepts string (with size, optional format: email|enum|ip|url, enum must include elements), integer, double, boolean, datetime, point, linestring, polygon; relationship relationship columns cannot be inline. indexes[].type takes key / unique / fulltext / spatial, and attributes cannot reference system fields.

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

Incremental columns

After a table exists, columns are added by type, mostly as 202 asynchronous tasks: status must go from processing to available before the column can be used for writes. Each type has update*Column, with getColumn / listColumns / deleteColumn for management.

// 17 types each have a create<Type>Column, for example:
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' });
// Writes are only allowed after col.status === 'available'

Column annotations

Maintains a column's display name (2.6.0 extension); passing an empty value to comment clears it. It only changes the display name and typically involves zero DDL.

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

Row reads and writes

Single-item CRUD, batch (createRows / upsertRows / updateRows / deleteRows), upsertRow, and single-column atomic incrementRowColumn / decrementRowColumn. Batch updates/deletes without queries apply to the entire table.

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);   // Out-of-range (max/min) throws an error
await tablesDB.deleteRow('app-db', 'tasks', '<rowId>');

Queries and pagination

The Query builder composes filtering, sorting, pagination, and cursors; lists return total by default, and total: false can omit the total count. On the REST side, queries are repeatable queries[] parameters.

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

Transactions

A transaction is a project-level object: create → stage operations (can be appended across multiple calls) → commit or roll back. Operations are not visible externally before commit; row read/write endpoints can also pass transactionId to attach to a transaction.

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 });
// or rollback: true to discard

Row aggregation

Server-side aggregation (count / sum / avg / min / max, groupable), without pulling full tables; ordinary columns must appear in groupBy, and queries only accepts filter conditions.

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

Schema versioning and rollback

Submit the complete structure JSON (not a diff patch) to generate a version and migrate automatically, then poll for the version's final state; mode defaults to migration, and baseline is only used when adopting the current physical structure as the first active version. Rollback only switches the effective pointer (recomputing column visibility); it does not run physical DDL or change data. Only one in-flight version is allowed per database at a time (duplicate submissions return 409).

const before = await tablesDB.listSchemaVersions({ databaseId: 'app-db', queries: [], total: true });
// Save the current active version id as the rollback anchor

const submitted = await tablesDB.createSchemaVersion({
  databaseId: 'app-db',
  schema: { tables: [/* Complete reviewed structure JSON */] },
});
const v = await tablesDB.getSchemaVersion({ databaseId: 'app-db', versionId: submitted.$id });
// Poll until status: active / failed (stepsCompleted / stepsTotal / errorMessage are observable)

// Roll back only after the compatibility review is complete:
// await tablesDB.rollbackSchemaVersion({ databaseId: 'app-db', versionId: '<activeVersionId>' });

Example Guide