Collections and datasets
Document Collections (collection.yaml)
Put collection.yaml in a folder to make it a document Collection. fields is a YAML mapping keyed by field name, not a list. select and multi-select options are plain strings:
version: 1
name: Kyoto Activities
fields:
Day:
type: number
Status:
type: select
options:
- Idea
- Booked
- Done
Cost:
type: number
Supported field types: text, number, checkbox, date, select, multi-select, person, relation, url, button.
Create records with dohc_create_record (pass collectionPath, name, optional fields). Update fields with dohc_set_record_fields (recordPath, fields). Query records with dohc_query_collection.
Transactional Collections (dataset.json)
Every transactional Collection is defined by dataset.json, a SQLite schema (schema.sql), and operations source (operations.js or backend.ts).
Choosing between create, prepare + approve, and app stage
- Generated CRUD Collection: Call
dohc_datasetwith{ request: { action: "create", workspaceId, definition } }, wheredefinitionis adataset.jsondescriptor object (formatVersion: 1or2,name,schemaPath,operationsPath,tables,operations, plusdatasetIdforformatVersion: 1). dohc generatesdataset.json,schema.sql, andoperations.jsand approves revision 1 in one step. Generated operations reject unknown keys withinvalid_inputand use these exact input shapes (keyed by field UUIDs fromdescribe):read:{}(all fields optional:limit1–100 default 50,after: { id, value } | null,search,filters: [{ fieldId, value }]up to 20 AND-combined,sort: { fieldId, direction: "asc" | "desc" },range: { fieldId, start, end },group: { fieldId, value }; for distinct groups passgroupBy: fieldIdwith an explicitlimitof 1–8, optionalgroupAfter: { value }only withgroupBy, and noafterorsort).create:{ values: { "<fieldId>": value } }.edit:{ id, expectedVersion, values: { "<fieldId>": value } }(expectedVersionisrow.versionfromread).delete:{ id, expectedVersion }(novalues).
- Custom business rules (
backend.tsoroperations.js): Writedataset.json,schema.sql, andbackend.tswithdohc_write_file, then callpreparefollowed byapprove. - Table view needs a read: dohc's desktop table view opens a table only through a
kind: "read"operation on that table that takes the generatedreadinput above and returns{ rows: [{ id, version, values: { "<fieldId>": value } }], nextCursor: { id, value } | null }, or{ groupBy, groups, nextGroupCursor: { value } | null }when the input hasgroupBy. A table with only"action"operations can't be browsed, even by its owner. Add one such read per table the owner should browse (access: "owner"is fine), or use generated CRUD.prepare,prepareMigration, andcreatereturnwarningsnaming each table without a read. - App + Collection created or changed together: Use
dohc_publish_appstage->approveStagedto review and apply the Collection changes and activate the local app in one approval. Staging activates only the local app and does not update live share-link publications; share-link apps still requireprepare+approve.
Exact dataset.json rules
Every violation fails validation (for full slug-based formatVersion: 2 details, see docs/reference/app-kit.md):
formatVersionmay be1(explicit UUIDs fordatasetId,tableId,fieldId, andoperationId) or2(datasetIdis still required in authoreddataset.jsonfiles, whiletableId,fieldId, andoperationIdmay be omitted and are derived deterministically via UUIDv5 fromdatasetId,sqlName,sqlColumn, and operationname; onlydohc_datasetcreategenerates a missingdatasetId).- In
formatVersion: 1,datasetId, everytableId, everyfieldId, and everyoperationIdmust be valid UUIDs and globally unique across the entire definition. schemaPathends in.sqlandoperationsPathends in.jsor.ts. InformatVersion: 1anddohc_datasetcreate, both are workspace-relative; in authoredformatVersion: 2descriptors they resolve relative todataset.json(defaulting to"schema.sql"and"operations.js").- Each table has
name,sqlName,primaryKey, andfields(plustableIdin v1).primaryKeymust match a column field'ssqlColumnwhosetypeis"text"or"number", withrequired: true,unique: true, and nodefault. - Optional
"generated": "record-id"is valid only on the primary key field whentype: "text",required: true,unique: true, and nodefault. - Column field types:
text,number,checkbox,date,select,multi-select,url,attachment,relation(plusbuttonfields which have only{ fieldId?, name, type: "button" }). selectandmulti-selectrequire non-empty uniqueoptions: string[]. Other field types must omitoptions.- Each operation has
name,label,tableId(ortablein v2),kind("read" | "create" | "edit" | "delete" | "action"),access("link" | "helper" | "owner"),readOnly, andfieldIds(orfieldsin v2). readOnlymust betruewhenkind === "read", andfalsewhenkindis"create","edit", or"delete"."action"may be either.kind === "delete"must havefieldIds: [].kind === "create"must NOT list agenerated: "record-id"field infieldIds.kind === "edit"must NOT list the table'sprimaryKeyfield infieldIds.- Every field referenced by an operation must belong to a column field (not a button) on the operation's table.
Custom operations (backend.ts / operations.js)
Operations run synchronously inside an isolated QuickJS sandbox with no import, require, network, or filesystem access. Assign functions to globalThis.operations:
globalThis.operations = {
bookSeat(ctx, input) {
const seats = Number(input?.seats ?? 1);
if (!Number.isInteger(seats) || seats < 1) {
ctx.refuse("invalid_seats", "Choose at least 1 seat.");
}
const taken = Number(ctx.db.query("SELECT COALESCE(SUM(seats), 0) AS n FROM bookings")[0]?.n ?? 0);
if (taken + seats > 8) {
ctx.refuse("workshop_full", "All 8 seats are taken.");
}
ctx.db.execute(
"INSERT INTO bookings(id, name, seats) VALUES(?, ?, ?)",
[ctx.requestId, String(input?.name ?? ""), seats],
);
return { id: ctx.requestId, seats };
},
};
ctx.db.query(sql, params)returns rows;ctx.db.execute(sql, params)returns{ changes }. Parameters are strings, finite numbers, ornull, up to 256 KiB as JSON per statement. Another type is refused asinvalid_input.- Pass a list as JSON text and read it with
json_each(?). SQL the operation can't use is refused assql_not_allowed, naming the table or function. ctx.refuse(code, message)rolls back the transaction and returns a structured refusal (codematches/^[a-z][a-z0-9_]{0,63}$/).ctx.caller.kindis"owner","named","link", or"automation". A"link"caller hasgrantId, the link's ID. The owner copies it from Share → Link options → Copy link ID;dohc_publish_appcreateLinkreturns it too.ctx.localDate(timeZone)returns today'sYYYY-MM-DDatctx.nowMsin a zone name such asAsia/Singapore. The caller picks the zone, so use it for calendar checks, never access.- Operations read and write only their own Collection's tables. No
ATTACH,PRAGMA, schema changes,load_extension,readfile,writefile,edit, orfts3_tokenizer.ctx.db.queryonly reads. - Name rows by the table's primary key, not
rowid(allowed only when the key is anINTEGER PRIMARY KEYthat aliasesrowid). Useexecute's{ changes }, notchanges(),total_changes(), orlast_insert_rowid(). - Default limits per call: 64 KiB input, 256 KiB result, 1,000 rows and 256 KiB per query, 128 statements, 128 parameters per statement, 24 MiB memory, and 1 s for the operation's code. Size and count refusals name the limit, its unit, and the actual usage; time and memory refusals name the limit.
dohc_dataset action cheat sheet
Pass { request: { action, ... } } to dohc_dataset. Through MCP, leave out workspaceId and dohc fills in the workspace the server serves. expectedDatasetId (the datasetId from describe) refuses a request when the path now names another Collection.
| Action | Required fields | Notes |
|---|---|---|
list | workspaceId | Returns approved Collections with datasetPath, revision, revisionSha256. |
describe | workspaceId, datasetPath | Returns tables, fields, operations, revision, revisionSha256. |
permissions | workspaceId, datasetPath | Returns place ({ kind: "here" } on this computer or { kind: "server", host } on the workspace's server), workspace defaults, rules, collaborator grants, app bindings, boundApps with scope ("local", "link", "workspace", or "owner") and drift status ("compatible", "needs-refresh", "incompatible") and reasons, and boundAppsIncomplete: true if discovery failed or results are paginated (do not treat omitted boundApps as a complete check when boundAppsIncomplete is set). |
create | workspaceId, definition | Writes generated files and approves revision 1. |
prepare | workspaceId, descriptorPath | Captures edited dataset.json, schemaPath, operationsPath. Returns preparationId and revision.revisionSha256. |
approve | workspaceId, preparationId, revisionSha256 | Approves a preparation. Do not pass datasetPath or sourceDigest. |
invoke | workspaceId, datasetPath, operationId, revision, revisionSha256, input, idempotencyKey | Runs an approved operation and returns revision, replayed, and place ({ kind: "here" } or { kind: "server", host }). Check the operation's readOnly flag in describe to distinguish reads from writes: when place.kind === "server", writes (readOnly: false) run directly on place.host and fail offline rather than queuing, so a successful write proves revision committed on that server. When copy (offline, savedAtMs, host) is present, the read ran on a local replica or saved copy; online member reads and direct relay reads omit copy. Use a fresh idempotencyKey per intended write; reuse the same key and input to retry an uncertain write. |
prepareSchemaChange | workspaceId, datasetPath, revision, revisionSha256, change | change.kind: addField, renameField, changeField, renameTable, renameCollection, addButton. Required addField needs default. Returns boundApps and, if checks were incomplete or paginated, boundAppsIncomplete: true. |
prepareMigration | workspaceId, datasetPath, migrationPath | Prepares edited source + SQL migration file for custom Collections. Pass migrationPath: null when only operations or metadata changed without schema SQL edits. Returns boundApps and, if checks were incomplete or paginated, boundAppsIncomplete: true. |
prepareRelationChoices | workspaceId, datasetPath, revision, revisionSha256, tableId, fieldId, labelFieldId | Adds a public read operation returning only key + labelFieldId for a relation field. Returns boundApps and, if checks were incomplete or paginated, boundAppsIncomplete: true. |
approveMigration | workspaceId, preparationId, revisionSha256, approvalDigest | Applies a prepared schema change, migration, or relation choices. Do not pass datasetPath. |
createForm | workspaceId, datasetPath, revision, revisionSha256, tableId, createOperationId, appRoot, fieldIds | Optional title, relationChoices: [{ fieldId, operationId, labelFieldId }]. Generated app.publish.json omits revision and revisionSha256 so re-preparing picks up later approved revisions automatically. |
types | workspaceId, datasetPath | Writes a .d.ts file under .dohc/types/ with TypeScript types for the approved tables and operations, and returns its workspace-relative path. An app imports that file with import type, using a path relative to the importing source file. |
sql | workspaceId, datasetPath, sql | Owner only. Runs one read-only SQL query under the SQLite authorizer, or EXPLAIN QUERY PLAN with explain: true. |
trace | workspaceId, datasetPath | Lists recent in-memory operation timings and SQL metrics. |
history, historyRevision | workspaceId, datasetPath; revisionSha256 for historyRevision | history queries the Collection's authority directly and returns headRevision, place, record edits, and schema and rule revisions. Pass limit: 1 when place.kind === "server" to confirm the server's latest revision. historyRevision reads one revision's saved source. |
prepareHistoryRestore | workspaceId, datasetPath, revision, revisionSha256, targetRevisionSha256, changedRevisionSha256 | Prepares a reviewed forward change back to a past revision against current records, keeping current access. Apply it with approveMigration. Restoring source files alone never activates rules. |
approval, confirmApproval | workspaceId, datasetPath; revisionSha256 for confirmApproval | approval says who approved the rules the Collection runs. When needsOwnerConfirmation is true, the Admin who approved them no longer is one: confirmApproval with that revisionSha256 records the Owner as their approver without changing the rules. |
export | workspaceId, datasetPath, savePath | Streams a private recovery archive, with private records, files, history, and retry credentials. savePath is absolute, outside the workspace, and ends in .dohc-recovery. |
prepareRecovery | workspaceId, sourcePath | Reads an archive at sourcePath (relative to the MCP server folder, or absolute) and returns recovery. |
claimRecovery | workspaceId, transferId, manifestSha256, sourceCursor, oldHostStopped | Copy recovery.sourceCursor.workspaceId, recovery.transferId, recovery.manifestSha256, and recovery.sourceCursor from prepareRecovery. Stop the old host first, then pass oldHostStopped: true. |
discardRecovery | workspaceId, transferId | Cancels a prepared recovery before it installs. Copy recovery.transferId from prepareRecovery. |