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
Project and Server API Key (
databases.read/write; row operations additionally require the scope intables.*/rows.*that matches the API actually used by the code); table-level permissions should be configured on the server side / in the Console.Use the SDK's
Querybuilder for queries; useID.unique()for IDs.The authoritative reference for column types and index types:
skills/ob-agentbase/references/tables-schema-types.md(rely on the current CE validator; do not copy public cloud documentation).
Usage workflow
Create database:
tablesDB.create({ databaseId, name });list/get/update/deleteto manage the lifecycle.Create table:
createTable({ databaseId, tableId, name, permissions, rowSecurity, enabled, columns, indexes, comment })(permissions,rowSecurity,enabled,columns,indexes,commentare all optional).Inline
columnsgoes through the Attributes validator:typeonly acceptsstring(withsize, optionalformat: email|enum|ip|url,enummust includeelements),integer,double(note: notfloat),boolean,datetime,point,linestring,polygon.relationshipRelationship columns cannot be created inline; usecreateRelationshipColumnafter the table is created.indexes:typetakeskey/unique/fulltext/spatial;attributescan only reference explicit business columns, not system fields such as$idor$createdAt.
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 hasupdate*ColumnandgetColumn/listColumns/deleteColumn). Incremental columns are mostly 202 asynchronous tasks; the status must go fromprocessingtoavailablebefore they can be used for writes.Column annotations (2.6.0 Node extension):
updateColumnComment({ databaseId, tableId, key, comment })(commentoptional) to maintain column descriptions.Row CRUD:
createRow/getRow/listRows/updateRow/deleteRow; batchcreateRows/upsertRows/updateRows/deleteRows; single-column atomicincrementRowColumn/decrementRowColumn;upsertRowto create or update a row by ID.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, andtotal: falsecan omit the total count.Transactions:
createTransaction({ ttl })(ttloptional) →createOperations({ transactionId, operations[] })(action: create/update/upsert/delete/increment/...) →updateTransaction({ commit: true })to commit orrollback: trueto roll back;listTransactions/getTransaction/deleteTransactionfor management.Row aggregation (2.6.0 Node extension):
aggregateRows({ databaseId, tableId, select[], queries, groupBy, transactionId })(queries,groupBy,transactionIdare all optional) returns aggregated rows.Schema versions and rollback (2.6.0 already available):
createSchemaVersion({ databaseId, schema, mode })(modeoptional) (mode: 'migration'(default) /'baseline'— use baseline only when adopting the current running structure as the first effective version);getSchemaVersion/listSchemaVersions({ databaseId, queries, total })(queries,totalare 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
| Plane | Method family | Key returns |
|---|---|---|
| Database | create / get / list / update / delete | Models.Database (storageTotal and other metadata) |
| Table | createTable / getTable / listTables / updateTable / deleteTable | Models.Table (rowSecurity, enabled, $permissions, columns, indexes) |
| Column | create*Column / update*Column / getColumn / listColumns / deleteColumn / updateColumnComment | each ColumnXxx (with status: processing|available|...) |
| Index | createIndex / getIndex / listIndexes / deleteIndex | Models.Index (type: key|unique|fulltext|spatial) |
| Row | createRow / getRow / listRows / updateRow / upsertRow / deleteRow + batch/increment-decrement | Models.Row (business data + $id, $createdAt, $permissions, etc.); lists return rows/total |
| Transaction | createTransaction / createOperations / updateTransaction / ... | Models.Transaction (status and operation log) |
| Aggregation | aggregateRows | Models.RowAggregation |
| Schema version | createSchemaVersion / getSchemaVersion / listSchemaVersions / rollbackSchemaVersion | Models.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
400 Missing fields / validation failure: the most common cause is an unsupported top-level
typefor inline columns (e.g.,varchar,email) — inline must bestring+format; only incremental columns accept path kinds such asvarchar.required: trueanddefaultare mutually exclusive; indexes referencing system fields or columns still inprocessingwill fail.JsonTable column required relaxation (2.7.0, appbase PR 541): tables on the JsonTable backend allow relaxing the
requiredof an existing column fromtruetofalse, provided the name, type, size, signed, and array remain unchanged — this "required-only relaxation" update goes directly to the adapter layer, atomically commits the catalog and metadata within a single transaction, and does not rebuild normal/unique/fulltext indexes (missing or null fields no longer produce index side-table entries; existing non-null index entries remain valid). Mixed relaxations are rejected: relaxing while also changingdefault/format/formatOptions/filters, renaming, changing the type, shrinking the size, or changing signed/array is all rejected with Conflict;requiredtightening fromfalseback totrueis likewise not allowed.Under row-level permissions, list queries return only rows the caller is allowed to
read(see permissions.md);updateRows/deleteRowswithout queries applies to the entire table — always include filter conditions.Operations in a transaction are not visible externally before commit; operations are discarded after
rollback. Deleting a transaction does not roll back committed operations.For large-volume writes, use batch APIs and chunking to stay within request limits. Transactions commit or roll back supported operations together, but do not automatically deduplicate repeated requests;
upsertRowdoes not guarantee business idempotency or eliminate concurrent conflicts either. Implement deduplication and concurrency control in the application. If a commit outcome is unknown, check the transaction status and data before deciding whether to retry.When project database storage / table count limits are exceeded, the corresponding
*_limit_exceedederror is returned (413 / creation failure).
SDK Category Differences
Server SDK (Node / Java / Python planes are isomorphic): the main body of this page; method names are camelCase in Node/JS, snake_case in Python, and synchronous methods + typed models in Java (the row
datageneric defaults toMap, andTypecan be passed to deserialize into a POJO).Client SDK (Web): reads and writes rows directly via the user Session (subject to row/table permissions), with limited table creation capability — table structure and permission baselines are configured on the server side; see client-sdk/web.md.
Console SDK: manages project quota / usage references (
TablesDB.listUsage/getUsageresource details); it does not create business tables; prefer the Server SDK for table structure automation.Entry points for differences: client-sdk/web.md,
console-sdk/nodejs.md,server-sdk/nodejs.md.
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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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' });// Positional parameter form (pass null for nullable parameters): create / update are (databaseId, name, enabled), list is (queries, search, total)
tables.create("app-db", "App", true);
tables.get("app-db"); // Metadata (storageTotal etc.)
tables.list(null, null, null); // queries / search / total
tables.update("app-db", "App2", true);
tables.delete("app-db");
// enabled: false only blocks user-side access; the API Key can still read and writetables_db.create(database_id='app-db', name='App')
tables_db.get(database_id='app-db') # Metadata (storage_total, etc.)
tables_db.list() # Supports queries
tables_db.update(database_id='app-db', name='App2')
tables_db.delete(database_id='app-db')
# enabled: false only blocks user-side access, API Keys can still read/write; method names follow the agentbase.services.tables_db source code_, err := tables.Create("app-db", "App", tables.WithCreateEnabled(true))
_, err = tables.Get("app-db") // Metadata (StorageTotal etc.)
_, err = tables.List() // Supports queries / search (WithListQueries / WithListSearch)
_, err = tables.Update("app-db", tables.WithUpdateName("App2"), tables.WithUpdateEnabled(true))
_, err = tables.Delete("app-db")
// enabled: false only blocks user-side access; the API Key can still read and writecurl -X POST "https://<your-endpoint>/v1/tablesdb" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"databaseId": "app-db", "name": "App", "enabled": true}'
curl -X PUT "https://<your-endpoint>/v1/tablesdb/app-db" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"name": "App2", "enabled": true}'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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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'] },
],
});import io.agentbase.models.DatabaseColumnDefinition;
import io.agentbase.models.DatabaseIndexDefinition;
import io.agentbase.enums.DatabaseSchemaType;
import io.agentbase.enums.DatabaseSchemaIndexType;
import java.util.List;
tables.createTable(
"app-db", "tasks", "Tasks",
null, // permissions
true, // rowSecurity
true, // enabled
List.of(new DatabaseColumnDefinition()
.setKey("title").setType(DatabaseSchemaType.STRING) // Inline column type only accepts string (with size)
.setSize(256L).setRequired(true)),
List.of(new DatabaseIndexDefinition()
.setKey("idx_title").setType(DatabaseSchemaIndexType.UNIQUE)
.setAttributes(List.of("title"))), // attributes must reference explicit business columns; system fields cannot be referenced
null // comment
);tables_db.create_table(
database_id='app-db',
table_id='tasks',
name='Tasks',
row_security=True,
enabled=True,
columns=[
{'key': 'title', 'type': 'string', 'size': 256, 'required': True},
],
indexes=[
{'key': 'idx_title', 'type': 'unique', 'attributes': ['title']},
],
)
# columns / indexes are lists of dicts; inline column type follows the tables-schema-types standard_, err := tables.CreateTable("app-db", "tasks", "Tasks",
tables.WithCreateTableRowSecurity(true),
tables.WithCreateTableEnabled(true),
tables.WithCreateTableColumns([]models.DatabaseColumnDefinition{
{Key: "title", Type: "string", Size: 256, Required: true},
}),
tables.WithCreateTableIndexes([]models.DatabaseIndexDefinition{
{Key: "idx_title", Type: "unique", Attributes: []string{"title"}},
}),
)curl -X POST "https://<your-endpoint>/v1/tablesdb/app-db/tables" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"tableId": "tasks",
"name": "Tasks",
"rowSecurity": true,
"columns": [
{ "key": "title", "type": "string", "size": 256, "required": true },
{ "key": "done", "type": "boolean", "required": false }
],
"indexes": [
{ "key": "idx_title", "type": "unique", "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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
// 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'// 17 family incremental columns are all positional parameters, in the form (databaseId, tableId, key, ...); most return 202 async tasks:
// varchar: createVarcharColumn(db, table, key, size, required, default, array, encrypt)
// integer: createIntegerColumn(db, table, key, required, min, max, default, array)
// relationship: createRelationshipColumn(db, table, relatedTableId, type, twoWay, key, twoWayKey, onDelete)
tables.createVarcharColumn("app-db", "tasks", "nickname", 64L, false, null, null, null);
tables.createIntegerColumn("app-db", "tasks", "views", false, 0L, null, null, null);
tables.createRelationshipColumn("app-db", "tasks", "users",
io.agentbase.enums.RelationshipType.MANYTOONE, false, "owner", null, null);
// createStringColumn is deprecated as of 1.9.0; use createTextColumn / createVarcharColumn instead
var col = tables.getColumn("app-db", "tasks", "nickname"); // writes are allowed only when status == available# Each of the 17 types has a create<Type>Column (mostly 202 asynchronous tasks), for example:
tables_db.create_string_column(database_id='app-db', table_id='tasks',
key='nickname', size=64, required=False)
tables_db.create_relationship_column(database_id='app-db', table_id='tasks', key='owner',
related_table_id='users', type='manyToOne')
col = tables_db.get_column(database_id='app-db', table_id='tasks', key='nickname')
# Writable only after col.status == 'available'; update_*_column / list_columns / delete_column handle corresponding maintenance
# Treat the agentbase.services.tables_db source code as authoritative// 17 types each have a Create<Type>Column (most return 202 async tasks):
_, err = tables.CreateVarcharColumn("app-db", "tasks", "nickname", 64, false)
_, err = tables.CreateIntegerColumn("app-db", "tasks", "views", false,
tables.WithCreateIntegerColumnMin(0))
_, err = tables.CreateRelationshipColumn("app-db", "tasks", "users", "manyToOne",
tables.WithCreateRelationshipColumnKey("owner")) // RelatedTableId / Type positional parameters; twoWay / key / twoWayKey / onDelete via options
col, err := tables.GetColumn("app-db", "tasks", "nickname") // Writes are allowed only after Status == available
_ = col
// UpdateXxxColumn / ListColumns / DeleteColumn provide corresponding maintenance; CreateStringColumn is deprecated (1.9.0), use CreateTextColumn / CreateVarcharColumn instead# Create response 202; poll with GET until status=available
curl -X POST "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/columns/varchar" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"key": "nickname", "size": 64, "required": false}'
curl "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/columns/nickname" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY"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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
await tablesDB.updateColumnComment({
databaseId: 'app-db', tableId: 'tasks', key: 'title', comment: '任务标题',
});tables.updateColumnComment("app-db", "tasks", "title", "任务标题");tables_db.update_column_comment(database_id='app-db', table_id='tasks',
key='title', comment='任务标题')
# Passing an empty comment clears it; agentbase.services.tables_db source code is authoritative_, err = tables.UpdateColumnComment("app-db", "tasks", "title", "任务标题") // Passing an empty comment clears itcurl -X PATCH "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/columns/title/comment" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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>');import { ID, Query } from 'agentbase-web-sdk';
const tablesDB = new TablesDB(client); // User Session; row read/write plane only
await tablesDB.createRow({
databaseId: 'app-db', tableId: 'tasks',
rowId: ID.unique(), data: { title: '写周报' },
});
const one = await tablesDB.getRow({ databaseId: 'app-db', tableId: 'tasks', rowId: '<rowId>' });
await tablesDB.updateRow({
databaseId: 'app-db', tableId: 'tasks', rowId: '<rowId>', data: { done: true },
});
const page = await tablesDB.listRows({
databaseId: 'app-db', tableId: 'tasks', queries: [Query.limit(25)],
});
await tablesDB.deleteRow({ databaseId: 'app-db', tableId: 'tasks', rowId: '<rowId>' });
// Constrained by row/table permissions; cannot create databases or tablesRow<Map<String, Object>> row = tables.createRow(
"app-db", "tasks", ID.unique(),
Map.of("title", "写周报", "done", false),
null, // permissions: if omitted, the table default is used
null // transactionId
);
RowList<Map<String, Object>> open = tables.listRows(
"app-db", "tasks",
List.of(Query.equal("done", false), Query.limit(25)),
null, true, null
);
tables.updateRow("app-db", "tasks", row.getId(), Map.of("done", true), null, null);
tables.deleteRow("app-db", "tasks", row.getId(), null);
// Batch: createRows(db, table, transactionId); updateRows(db, table, data, queries, transactionId);
// deleteRows(db, table, queries, transactionId); without queries, updateRows / deleteRows apply to the entire tabletables_db.create_row(
database_id='app-db', table_id='tasks', row_id=ID.unique(),
data={'title': '写周报'},
)
one = tables_db.get_row(database_id='app-db', table_id='tasks', row_id='<row_id>')
tables_db.update_row(database_id='app-db', table_id='tasks', row_id='<row_id>',
data={'done': True})
tables_db.upsert_row(database_id='app-db', table_id='tasks', row_id='<row_id>',
data={'title': '写周报', 'done': False}) # Create or update the row
rows = tables_db.list_rows(
database_id='app-db', table_id='tasks',
queries=[Query.order_desc('$createdAt'), Query.limit(25)],
total=False,
)
tables_db.increment_row_column(database_id='app-db', table_id='tasks',
row_id='<row_id>', column='views', value=1) # Out-of-range (max/min) throws an error
tables_db.delete_row(database_id='app-db', table_id='tasks', row_id='<row_id>')
# Batch create_rows / upsert_rows / update_rows / delete_rows;
# update_rows / delete_rows apply to the entire table when queries is absent_, err := tables.CreateRow("app-db", "tasks", id.Unique(),
map[string]interface{}{"title": "写周报"}) // Data is a positional parameter
one, err := tables.GetRow("app-db", "tasks", "<rowId>")
payload := map[string]interface{}{}
_ = one.Decode(&payload) // Business fields retrieved as raw JSON via Decode
_, err = tables.UpdateRow("app-db", "tasks", "<rowId>",
tables.WithUpdateRowData(map[string]interface{}{"done": true}))
_, err = tables.UpsertRow("app-db", "tasks", "<rowId>",
tables.WithUpsertRowData(map[string]interface{}{"title": "写周报", "done": false})) // Create or update the row
rows, err := tables.ListRows("app-db", "tasks",
tables.WithListRowsQueries([]string{query.OrderDesc("$createdAt"), query.Limit(25)}))
_, err = tables.IncrementRowColumn("app-db", "tasks", "<rowId>", "views",
tables.WithIncrementRowColumnValue(1)) // Out-of-range (max/min) throws an error
_, err = tables.DeleteRow("app-db", "tasks", "<rowId>")
// CreateRows / UpsertRows / UpdateRows / DeleteRows are isomorphic; UpdateRows / DeleteRows without queries affect the whole tablecurl -X POST "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/rows" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"rowId": "r1", "data": {"title": "写周报"}}'
curl -X PUT "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/rows/r1" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"data": {"title": "写周报", "done": false}}' # upsert
curl -X PATCH "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/rows/r1/views/increment" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"value": 1}'
curl -X PATCH "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/rows" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"data": {"done": true}, "queries": ["equal(\"done\", false)"]}'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.
- Node.js (Server)
- Web (user session)
- Java
- Python
- Go
- REST (curl)
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>'),
]);const rows = await tablesDB.listRows({
databaseId: 'app-db', tableId: 'tasks',
queries: [Query.equal('done', false), Query.orderDesc('$createdAt'), Query.limit(25)],
});RowList<Map<String, Object>> rows = tables.listRows(
"app-db", "tasks",
List.of(
Query.equal("done", false),
Query.orderDesc("$createdAt"),
Query.limit(25)
),
null, true, null
);rows = tables_db.list_rows(
database_id='app-db', table_id='tasks',
queries=[
Query.equal('done', False),
Query.order_desc('$createdAt'),
Query.limit(25),
],
total=False,
)rows, err := tables.ListRows("app-db", "tasks",
tables.WithListRowsQueries([]string{
query.Equal("done", false),
query.OrderDesc("$createdAt"),
query.Limit(25),
}))curl -G "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/rows" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
--data-urlencode 'queries[]=equal("done", false)' \
--data-urlencode 'queries[]=orderDesc("$createdAt")' \
--data-urlencode 'queries[]=limit(25)' \
--data-urlencode 'total=false'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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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 discardimport io.agentbase.ID;
import io.agentbase.enums.TransactionAction;
import io.agentbase.models.TablesDBTransactionOperation;
var tx = tables.createTransaction(null); // ttl accepts a number of seconds
tables.createOperations(tx.getId(), List.of(
new TablesDBTransactionOperation("app-db", "tasks", TransactionAction.CREATE)
.setRowId(ID.unique())
.setData(Map.of("title", "A"))));
tables.updateTransaction(tx.getId(), true, null); // commit commits; pass true to rollback to discard
// The method family also includes listTransactions / getTransaction / deleteTransaction;
// For action values, see TransactionAction (create/update/upsert/delete/increment/decrement, etc.)tx = tables_db.create_transaction(ttl=60)
tables_db.create_operations(
transaction_id=tx['$id'],
operations=[{
'databaseId': 'app-db',
'tableId': 'tasks',
'action': 'create',
'rowId': 'r1',
'data': {'title': 'A'},
}],
)
tables_db.update_transaction(transaction_id=tx['$id'], commit=True) # Or rollback=Truetx, err := tables.CreateTransaction()
_, err = tables.CreateOperations(tx.Id,
tables.WithCreateOperationsOperations([]models.TablesDBTransactionOperation{{
DatabaseId: "app-db",
TableId: "tasks",
Action: "create",
RowId: "r1",
Data: map[string]interface{}{"title": "A"},
}}))
_, err = tables.UpdateTransaction(tx.Id, tables.WithUpdateTransactionCommit(true))curl -X POST "https://<your-endpoint>/v1/tablesdb/transactions" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"ttl": 60}'
curl -X POST "https://<your-endpoint>/v1/tablesdb/transactions/<transactionId>/operations" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"operations": [{"databaseId": "app-db", "tableId": "tasks", "action": "create", "rowId": "r1", "data": {"title": "A"}}]}'
curl -X PATCH "https://<your-endpoint>/v1/tablesdb/transactions/<transactionId>" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
-H "Content-Type: application/json" \
-d '{"commit": true}'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.
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
const stats = await tablesDB.aggregateRows({
databaseId: 'app-db',
tableId: 'tasks',
select: ['count'],
queries: [Query.equal('done', false)],
groupBy: ['done'],
});var agg = tables.aggregateRows(
"app-db", "tasks",
List.of("count"), // select: aggregate function
List.of(Query.equal("done", false)), // Filters
List.of("done"), // groupBy
null // transactionId
);stats = tables_db.aggregate_rows(
database_id='app-db', table_id='tasks',
select=['count'], # Aggregate functions
queries=[Query.equal('done', False)], # Accepts filter conditions only
group_by=['done']) # Non-grouped columns must appear in group_bystats, err := tables.AggregateRows("app-db", "tasks", []string{"count"}, // Select is a positional parameter
tables.WithAggregateRowsQueries([]string{query.Equal("done", false)}),
tables.WithAggregateRowsGroupBy([]string{"done"}))
_ = statscurl -G "https://<your-endpoint>/v1/tablesdb/app-db/tables/tasks/aggregation" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "X-Appwrite-Key: $APPBASE_API_KEY" \
--data-urlencode 'select[]=count(*) AS totalRows' \
--data-urlencode 'select[]=done' \
--data-urlencode 'groupBy[]=done' \
--data-urlencode 'queries[]=equal("done", false)'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).
- Node.js (Server)
- Java
- Python
- Go
- REST (curl)
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>' });tables.listSchemaVersions("app-db", null, null);
var v2 = tables.createSchemaVersion("app-db", schema, io.agentbase.enums.Mode.MIGRATION); // mode: MIGRATION (default) / BASELINE
tables.getSchemaVersion("app-db", v2.getId());
tables.rollbackSchemaVersion("app-db", v2.getId()); // Only switches the pointer; no physical DDL is executedversions = tables_db.list_schema_versions(database_id='app-db', total=True)
# Save the current active version id as the rollback anchor
submitted = tables_db.create_schema_version(
database_id='app-db', schema={'tables': []}) # schema takes the complete schema JSON; mode defaults to migration
v = tables_db.get_schema_version(database_id='app-db', version_id=submitted['$id'])
# Poll until status: active / failed (stepsCompleted / stepsTotal / errorMessage are observable)
# Roll back only after the compatibility review is complete (updates only the pointer, executes no physical DDL, and does not modify data):
# tables_db.rollback_schema_version(database_id='app-db', version_id='<active_version_id>')versions, err := tables.ListSchemaVersions("app-db")
_ = versions // Save the current active version id as the rollback anchor
submitted, err := tables.CreateSchemaVersion("app-db",
map[string]interface{}{"tables": []interface{}{}}) // schema is a positional parameter, pass the complete structure JSON; mode defaults to migration
v, err := tables.GetSchemaVersion("app-db", submitted.Id) // Poll until status: active / failed
_ = v
// Roll back only after the compatibility review is complete (updates only the pointer, executes no physical DDL, and does not modify data):
// tables.RollbackSchemaVersion("app-db", "<activeVersionId>")Operation 1 (run separately)
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -X POST "https://<your-endpoint>/v1/tablesdb/app-db/schema/versions" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>" \
-H "Content-Type: application/json" \
-d '{"schema": {"tables": []}, "mode": "migration"}'
)Operation 2 (run separately)
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- "https://<your-endpoint>/v1/tablesdb/app-db/schema/versions" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>"
)Operation 3 (run separately). Run separately only after confirming the target and consequences.
(
set +x
set -o pipefail
: "${APPBASE_API_KEY:?Set APPBASE_API_KEY}"
builtin printf 'X-Appwrite-Key: %s\n' "${APPBASE_API_KEY:?Set APPBASE_API_KEY}" | curl --disable --header @- -X POST "https://<your-endpoint>/v1/tablesdb/app-db/schema/rollback/1" \
-H "X-Appwrite-Project: <YOUR_PROJECT_ID>"
)Example Guide
Examples by language are centralized in the language tree
examples/; for the complete sequence create database → create table (inline columns/indexes) → transactions → aggregation and the column type mapping, seeskills/ob-agentbase/references/tables-schema-types.mdandskills/ob-agentbase/references/server-sdks/nodejs.md.