SQL Database
A PostgreSQL-backed relational store that lives in its own per-circle schema — the place for structured, tabular, ACID data that other elements query through parameterized SQL, idempotent migrations, and simple row CRUD.
Working with it
Selecting a SQL Database reveals its settings in the properties panel; it has no dedicated full-screen workbench.
How it appears
The same element type rendered as a definition, a circle instance, and a live workspace card.
When to use / not
When to use
- Your data is structured and relational — typed columns, primary keys, joins, and transactional integrity that a tabular store gives you for free.
- A function or app needs durable shared state: attach the SQL element and read the injected RESOURCE_SQL_{NAME} connection string from inside your code.
- You want schema changes shipped with the element as declarative, idempotent migrations (CREATE TABLE IF NOT EXISTS …) applied once on provisioning.
- You need to mint and manage per-consumer bearer tokens from a credential-set table (issue / rotate / revoke) without standing up a separate auth store.
When not to use
- You need semantic similarity search over embeddings — use the vector element, not hand-rolled SQL.
- Your data is a graph of nodes and edges, time-indexed series, or free-form documents — reach for graph, timeseries, or document respectively.
- You want real-time push on every change — the subscribe op is a stub today; for live updates wire an explicit event flow instead of relying on it.
Topology
Created from the library and placed inside an app or circle. It is a top-level building block you compose with other elements.
Properties
migrationsarray- Optional declarative DDL migrations bundled with this element. Each entry runs once on element provisioning via the existing `migrate` op (idempotent — re-runs against an already-applied schema are no-ops when migrations use `IF NOT EXISTS`). Migrations execute in array order. Provisioning tooling (scripts/cprx-provision.sh, or any other seed bootstrapper) walks this array after element creation and POSTs each entry to `/api/{circle}/{slug}/ops/migrate` with `{sql: up, description: "<version> <name>"}`. Use `down` for documentation / rollback runbooks; the platform does not auto-roll-back on enable failures (operator-driven). Storage backend already supports the migration shape natively via `runtime-types::forces::storage::StorageForce::migrate` (Vec<Migration>{version, name, up, down}). This field declares the same shape at the spec level so a single YAML seed brings up its tables on enable without a separate provisioning step.
Operations
- activityGET
- attachmentsGET
- batch_statsGET
- composePOST
- contextGET
- createPOST
- deletePOST
- disablePOST
- enablePOST
- export_bundleGET
- getPOST
- import_bundlePOST
- insertPOST
- intentionGET
- issue_credentialPOST
- migratePOST
- promotePOST
- queryPOST
- readmeGET
- readme_updatePOST
- remove-modifierPOST
- restorePOST
- revoke_credentialPOST
- rotate_credentialPOST
- schemaGET
- sourceGET
- source_branchesGET
- source_fixturesPOST
- source_promotePOST
- source_repairPOST
- source_statusGET
- source_validatePOST
- statsGET
- subscribePOST
- tablesGET
- treeGET
- updatePOST
- update_metaPATCH
- vacuumPOST
- versionGET
Composition
Errors / when it fails
- migrations[*].version must be a numeric string (e.g. '0001', '0002')
- Fails unless:
migrations == null || migrations.all(m, m.version != null && m.version.matches('^[0-9]+$')) - migrations[*].name must be lowercase snake_case, max 64 chars (e.g. 'create_users')
- Fails unless:
migrations == null || migrations.all(m, m.name != null && m.name.matches('^[a-z][a-z0-9_]*$') && size(m.name) <= 64) - migrations[*].up is required and must be non-empty DDL
- Fails unless:
migrations == null || migrations.all(m, m.up != null && size(m.up) > 0) - migrations[*].version values must be unique — duplicate version found
- Fails unless:
migrations == null || migrations.size() == migrations.map(m, m.version).toSet().size()
Validation rules
- More than 50 declarative migrations — consider consolidating older migrations for maintainability
SQL Database (sql)
Category: data | Form: | Symbol: Sq
Store structured relational data
PostgreSQL-backed relational storage. Configure connection details in spec.connection (host, port, database, credential_ref) or use the default circle database. Use the “query” operation to run SQL with optional bind parameters, and “migrate” to apply schema changes. When attached to a function, the connection string is injected as an environment variable named RESOURCE_SQL_{NAME} (e.g., element “users-db” becomes RESOURCE_SQL_USERS_DB). Common mistake: forgetting to attach this element to your function before invoking — without attachment, no connection is injected.
Guide
Store structured relational data
What It Does
SQL Database is a PostgreSQL-backed relational storage element. Each SQL element gets a dedicated PostgreSQL schema (circle_{uuid}), so tables, queries, and migrations are isolated per circle. Connection details are configured in spec.connection (host, port, database, credential_ref), or the element falls back to the default circle database.
It exposes a full DML/DDL surface as operations: run arbitrary parameterized SQL with query, apply schema changes with migrate, and use convenience wrappers (insert, update, delete, get) for single-table row work without hand-writing SQL. Discovery ops (schema, tables) report table structure before you build queries; vacuum sends a storage-optimization hint. SQL elements may also act as a credential set — when the spec declares credential_set_table, the issue_credential / revoke_credential / rotate_credential ops manage per-consumer bearer tokens.
Other elements attach to a SQL element rather than embedding it. When attached to a function, the connection string is injected as an environment variable named RESOURCE_SQL_{NAME} (e.g. element users-db becomes RESOURCE_SQL_USERS_DB). Without that attachment, no connection is injected.
Element Definition
| Property | Value |
|---|---|
| Type | sql |
| Category | data |
| Form | atom |
| Symbol | Sq |
| Icon | storage / #3B82F6 |
| Storage backend | postgres |
| Wirable | false |
Properties
| Field | Type | Default | Description |
|---|---|---|---|
migrations | array | [] | Optional declarative DDL migrations bundled with the element. Each entry runs once on provisioning via the migrate op (idempotent with IF NOT EXISTS). Executes in array order. |
migrations[].version | string | — | Numeric version string ordering migrations (e.g. '0001'). Must match ^[0-9]+$; lex-sortable. |
migrations[].name | string | — | Snake-case migration name (^[a-z][a-z0-9_]*$, max 64 chars). Surfaced in observability + the migration-log table. |
migrations[].up | string | — | DDL applied on provisioning. Must be idempotent — use IF NOT EXISTS. |
migrations[].down | string | — | Inverse DDL for rollback runbooks. Documentation-only — the platform does not auto-roll back. |
States
| State | Description |
|---|---|
provisioned | Initial state. |
active | Element is live. |
error | Element is in an error state. |
Capabilities
| Capability | Description |
|---|---|
relational-storage | PostgreSQL-backed relational storage with per-circle schema isolation |
schema-migration | Declarative DDL migrations via the migrate op; idempotent with IF NOT EXISTS |
parameterized-query | Parameterized SQL queries with $1/$2 bind parameters (sqlx) |
upsert | INSERT ... ON CONFLICT with auto-detected primary-key conflict target |
change-subscription | subscribe op placeholder — returns a stub acknowledgement; real-time change notifications are not yet wired |
credential-set | Optional credential-set table for bearer auth token issuance (B.4) |
Attaches / Uses
| Relationship | Elements |
|---|---|
attaches (modifiers) | rate-limit, auth-policy |
uses | — |
Error Codes
| Code | Class | Retryable | Description |
|---|---|---|---|
SQL_INVALID_TABLE_NAME | validation | No | Table name fails [a-zA-Z_][a-zA-Z0-9_]* pattern (reserved word or injection attempt) |
SQL_NO_PRIMARY_KEY | validation | No | on_conflict='update' requested but table has no primary key; specify on_conflict_columns explicitly |
SQL_INVALID_CONFLICT_COLUMN | validation | No | on_conflict_columns contains a name that is not a valid Postgres unquoted identifier |
SQL_INVALID_SET_COLUMN | validation | No | on_conflict_set_columns contains a name that is not a valid column in the target table |
SQL_NOT_A_CREDENTIAL_SET | validation | No | Credential op called on an SQL element that has no credential_set_table in spec |
SQL_TABLE_NOT_FOUND | validation | No | Table does not exist — run the migrate op first (PG 42P01) |
SQL_COLUMN_NOT_FOUND | validation | No | Column referenced in query does not exist in the table (PG 42703) |
SQL_SYNTAX_ERROR | validation | No | SQL syntax error — often an unquoted reserved word used as identifier (PG 42601) |
SQL_DUPLICATE_KEY | validation | No | Unique constraint violation on insert without ON CONFLICT handling (PG 23505) |
SQL_NOT_NULL_VIOLATION | validation | No | NOT NULL constraint violated — provide a value for all required columns (PG 23502) |
Operations
query
POST query · auth: write
Execute a SQL query with optional bind parameters. SELECT returns rows as JSON arrays; INSERT/UPDATE/DELETE return affected row count. Use $1, $2 placeholders with the params array. Queries run inside the circle’s schema. Timeouts default to 30s. Input: sql (required), params, timeout_ms (default 30000). Output: rows, row_count, columns.
migrate
POST migrate · auth: admin
Apply a schema migration (DDL): CREATE TABLE, ALTER TABLE, etc. Migrations are recorded in a migration log and are idempotent when using IF NOT EXISTS. Input accepts the statement in any one of migration (canonical), sql, or query; plus dry_run (default false) and description. Output: migrated, migration_id, rows_affected.
insert
POST insert · auth: write
Insert one or more rows into a table. Pass table and rows (array of JSON objects; keys = column names). For upsert, set on_conflict_action to update (canonical; on_conflict is the deprecated alias) — on_conflict_columns is optional and auto-detects the table’s primary key when omitted. on_conflict_set_columns restricts which columns the UPDATE SET clause refreshes. Output: inserted, ids.
schema
GET schema · auth: read
Get detailed schema metadata for all user-created tables: column names, data types, nullability, primary keys, defaults, and index definitions. System tables are excluded. Output: tables, indexes, schema_name.
tables
GET tables · auth: read
List tables in the element’s dedicated schema, with column info, row counts, and index details. Output: tables (array of {name, columns, row_count}).
vacuum
POST vacuum · auth: admin
Send a storage-optimization hint to PostgreSQL. Useful after large bulk operations to reclaim space and update statistics. Output: vacuumed.
subscribe
POST subscribe · auth: read
Set up a NATS subscription for real-time notification when data changes. (Placeholder — see change-subscription capability.) Output: subscribed, channel.
delete
POST delete · auth: write
Delete rows from a table by id (single-row) or where clause (multi-row). Input: table (required), id, pk (default id), where (string or column-value object), params. Output: deleted, rows.
update
POST update · auth: write
Update a single row by its id. Pass changed column values in fields. Returns the updated row via RETURNING *. Input: table, id, fields (all required), pk (default id). Output: updated, record.
get
POST get · auth: read
Retrieve a single row by its id column. Input: table, id (both required), pk (default id). Output: record, table.
issue_credential
POST issue-credential · auth: admin
Generate a fresh 32-byte random token, hash it (SHA-256), insert a row into the credential set, and return the plaintext exactly once (not persisted). Only callable when the spec declares credential_set_table; otherwise returns SQL_NOT_A_CREDENTIAL_SET. Input: consumer_name (required), rpm_limit (default 600). Output: credential_id, consumer_name, token, rpm_limit.
revoke_credential
POST revoke-credential · auth: admin
Soft-delete a credential (active=FALSE, revoked_at=NOW()). Provide either credential_id (preferred, single-row) or consumer_name (revokes ALL rows for that name). Idempotent. Output: revoked (count).
rotate_credential
POST rotate-credential · auth: admin
Atomically revoke an old credential and issue a fresh one in one transaction, returning the new plaintext token (shown once). If multiple active rows exist for the consumer, the latest (by created_at DESC) is rotated. Input: consumer_name (required). Output: revoked_credential_id, new_credential_id, consumer_name, token, rpm_limit.
Quick Start
Creating via API
POST /api/{circle}/{project}/
Content-Type: application/json
{
"element_type": "sql",
"slug": "users-db",
"name": "Users Database",
"spec": {
"migrations": [
{
"version": "0001",
"name": "create_users",
"up": "CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT)"
}
]
}
}
Applying a migration
POST /api/{circle}/{project}/users-db/ops/migrate
Content-Type: application/json
{
"migration": "CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, name TEXT NOT NULL, email TEXT)",
"description": "0001 create_users"
}
Querying with bind parameters
POST /api/{circle}/{project}/users-db/ops/query
Content-Type: application/json
{
"sql": "SELECT id, name FROM users WHERE email = $1",
"params": ["alice@example.com"]
}
Inserting (with upsert by primary key)
POST /api/{circle}/{project}/users-db/ops/insert
Content-Type: application/json
{
"table": "users",
"rows": [{ "id": "u1", "name": "Alice", "email": "alice@example.com" }],
"on_conflict_action": "update"
}
Common Mistakes
Querying a table before creating it.
SELECT/INSERT against a table that doesn’t exist returns SQL_TABLE_NOT_FOUND (PG 42P01). Run the migrate op (or declare spec.migrations) to create the schema first.
Non-idempotent migrations.
Migration up statements must be idempotent — use IF NOT EXISTS on CREATE TABLE / CREATE INDEX. Re-runs against an already-applied schema must be no-ops.
Invalid migration metadata.
migrations[].version must be a numeric string (^[0-9]+$, e.g. '0001'), migrations[].name must be lowercase snake_case (max 64 chars), migrations[].up must be non-empty, and versions must be unique within the element — otherwise validation fails.
Reserved words or bad identifiers as table names.
Table names must match [a-zA-Z_][a-zA-Z0-9_]* or the op returns SQL_INVALID_TABLE_NAME. SQL syntax errors from unquoted reserved words surface as SQL_SYNTAX_ERROR (PG 42601).
Upserting a table with no primary key.
on_conflict_action='update' auto-detects the table’s primary key. If the table has none, it returns SQL_NO_PRIMARY_KEY — specify on_conflict_columns explicitly to target a unique constraint.
Calling credential ops on a plain SQL element.
issue_credential / revoke_credential / rotate_credential only work when the spec declares credential_set_table; otherwise they return SQL_NOT_A_CREDENTIAL_SET.
Relationships
- Attaches to: rate-limit, auth-policy
Capabilities
- relational-storage: PostgreSQL-backed relational storage with per-circle schema isolation
- schema-migration: Declarative DDL migrations via the migrate op; idempotent with IF NOT EXISTS
- parameterized-query: Parameterized SQL queries with 1/2 bind parameters (sqlx)
- upsert: INSERT … ON CONFLICT with auto-detected primary key conflict target
- change-subscription: Subscribe op placeholder — returns a stub acknowledgement; real-time change notifications via PostgreSQL LISTEN/NOTIFY through the WebSocket event bus are not yet wired. Ops: subscribe.
- credential-set: Optional credential-set table for bearer auth token issuance (B.4)
Properties
| Property | Type | Default | Description |
|---|---|---|---|
migrations | array | [] | Optional declarative DDL migrations bundled with this element. Each entry runs once on element provisioning via the existing migrate op (idempotent — re-runs against an already-applied schema are no-ops when migrations use IF NOT EXISTS).Migrations execute in array order. Provisioning tooling (scripts/cprx-provision.sh, or any other seed bootstrapper) walks this array after element creation and POSTs each entry to /api/{circle}/{slug}/ops/migrate with {sql: up, description: "<version> <name>"}.Use down for documentation / rollback runbooks; the platform does not auto-roll-back on enable failures (operator-driven).Storage backend already supports the migration shape natively via runtime-types::forces::storage::StorageForce::migrate (Vec |
Operations
activity
Get /ops/activity | Auth: Read
Get activity events for this element
Scope depends on element capabilities: individual elements query by element_id, project-form elements with activity-scope-members include member activities, circle-level elements with activity-scope-all query the entire circle. Gracefully returns empty list if activities table is missing (old circles).
attachments
Get /ops/attachments | Auth: Read
List all modifiers and resources attached to this element
Returns both modifiers (policy enforcement) and resources (data injection) with is_modifier flag to distinguish. Items in the generated MODIFIER_TYPES list are modifiers; everything else is a resource. Includes cascade_policy and version pin info.
batch_stats
Get /ops/batch_stats | Auth: Read
Get per-element statistics for all children of this element
Returns per-child stats plus an aggregate. Most meaningful on compound or manifest form elements (repositories, circles, projects); atoms have no children so the result is an empty children array with a zeroed aggregate. Uses efficient GROUP BY SQL. Weighted averages for eval scores.
compose
Post /ops/compose | Auth: Execute
Batch add and remove modifiers on this element in a single call
Declarative composition: add modifiers by ref path (slug or path@version) and remove by attachment ID, all in one atomic call on the target element. Each ‘add’ entry resolves the source element, validates topology, attaches with optional priority and cascade policy. Each ‘remove’ entry deletes the attachment row. Returns a summary of what was added and removed. Example: compose({ add: [{ref: “my-prompt”}, {ref: “rate-limit/api@v2”, priority: 50}], remove: [{attachment_id: “uuid”}] })
context
Get /ops/context | Auth: Read
Get connected elements (graph traversal)
Graph traversal showing all connected elements with their relationship type (contains, contained_by, references, referenced_by, attaches, etc.). Use ?depth=N to control traversal depth (default 1) and ?types=actor,data to filter by element types.
create
Post /ops/create | Auth: Write
Create child element
POST to the parent path — element_type goes in the request body, NOT the URL. Both element_type and slug are required and must be non-empty. Name is derived from slug if omitted. Writes to both Git and PostgreSQL. All elements are stored flat under the circle — no intermediate library wrapper rows.
delete
Post /ops/delete | Auth: Write
Delete rows from a table by id or where clause
Deletes rows from the specified table. Provide an id for single-row deletion, or a where clause for multi-row deletion. Returns deleted rows. Use the pk parameter to specify a custom primary key column (defaults to id).
disable
Post /ops/disable | Auth: Admin
Disable element (hides and prevents use)
Idempotent — safe to call on already-disabled elements. Optionally pass a reason string. Disabled elements cannot be invoked or executed. Inverse of enable.
enable
Post /ops/enable | Auth: Admin
Enable element (makes usable and visible)
Idempotent — safe to call on already-enabled elements. Transitions element to ready/enabled state. Cannot enable deleted elements. Inverse of disable.
export_bundle
Get /ops/export/bundle | Auth: Read
Export element as downloadable git bundle
On non-root-namespace elements, returns a binary git bundle. On root-namespace (circle) elements, dispatch hands off to the circle’s own export_bundle op, which returns a multi-element JSON envelope with one base64 bundle per child element — this is intentional, not an error.
get
Post /ops/get | Auth: Read
Get a single row from a table by id
Retrieves a single row from the specified table by its id column. Returns the full row as a JSON object. Use the pk parameter to specify a custom primary key column (defaults to id). Use query for more complex lookups.
import_bundle
Post /ops/import/bundle | Auth: Write
Import git bundle into element
Accepts a base64-encoded git bundle in the JSON bundle_base64 field. Use overwrite=true to replace existing elements with same slug (default skips duplicates). Imported elements get new UUIDs. Returns counts of imported/skipped elements and any errors.
insert
Post /ops/insert | Auth: Write
Insert one or more rows into a table
Convenience wrapper around INSERT. Pass table name and rows as JSON objects. Column names are inferred from object keys. Returns the number of inserted rows and any generated IDs (if the table has a RETURNING clause configured). For upsert semantics: set on_conflict=‘update’. on_conflict_columns is OPTIONAL (IMPROVE-182): when omitted, the runtime auto-detects the table’s primary key and uses it as the conflict target — covers the 90% “upsert by PK” case with zero ceremony. Specify on_conflict_columns explicitly when conflict resolution should target a non-PK unique constraint, or when the table has no PK (returns SQL_NO_PRIMARY_KEY otherwise). PK lookups are cached per (circle, table); migrate ops invalidate the cache. on_conflict=‘ignore’ tolerates missing on_conflict_columns; specifying them constrains the conflict to a specific target instead of any unique constraint.
intention
Get /ops/intention | Auth: Read
Get element intention with full inheritance chain
Returns three levels: direct (this element’s intention), inherited (from category and root), and resolved (final merged intention). Useful for understanding an element’s purpose in context of its hierarchy.
issue_credential
Post /ops/issue-credential | Auth: Admin
Issue a new credential into a credential-set table (B.4)
Generates a fresh 32-byte random token, hashes it (SHA-256), inserts a row into the credential set, and returns the plaintext exactly once. The plaintext is NOT persisted — store it where the consumer needs it (workspace pod env, dev box ~/.triform/credentials, etc.). Only callable on data/sql elements whose spec declares credential_set_table; other sql elements return SQL_NOT_A_CREDENTIAL_SET.
migrate
Post /ops/migrate | Auth: Admin
Apply a schema migration (DDL)
Applies a DDL migration (CREATE TABLE, ALTER TABLE, etc.) to the element’s schema. Migrations are recorded in a migration log and are idempotent when using IF NOT EXISTS. Use this for schema changes; use query for DML. Send the DDL in the
migrationfield (canonical).sqlandqueryare accepted as aliases for the same payload, so any one of the three works — prefermigrationto avoid ambiguity.
promote
Post /ops/promote | Auth: Admin
Promote element configuration to a target environment
Only for manifest-form elements (projects). Environments advance: dev → demo → live. dev→demo requires member+ role, demo→live requires admin. Freezes member versions at promotion time (creates snapshot). Persists environment config to spec.environments.
query
Post /ops/query | Auth: Write
Execute a SQL query with optional bind parameters
Runs a SQL statement against this element’s database. SELECT returns rows as JSON arrays. INSERT/UPDATE/DELETE return affected row count. Use $1, $2 placeholders with the params array for parameterized queries. Queries run inside the circle’s schema (circle_{uuid}). Timeouts default to 30s.
readme
Get /ops/readme | Auth: Read
Get element README.md content
Reads README.md from the element’s git repository. Returns empty content (not an error) if no README exists. Always returns markdown format.
readme_update
Post /ops/readme_update | Auth: Write
Update element README.md content
Creates or overwrites README.md in the element’s git repo. Commits to the draft branch. Content must be provided as a markdown string.
remove-modifier
Post /ops/remove-modifier | Auth: Execute
Remove an attached modifier from this element by attachment ID
Removes a modifier/resource attachment by its row ID. The ID comes from the attachments or context API. This is the reverse of attach — called on the target element, not the source.
restore
Post /ops/restore | Auth: Admin
Restore element to a specific version
Automatically snapshots the current state before restoring (creates a ‘Before restore to vN’ version entry). Writes restored spec to git as .triform/spec.yaml. Git failures warn but don’t fail the operation — DB state is authoritative. Cannot restore deleted elements.
revoke_credential
Post /ops/revoke-credential | Auth: Admin
Revoke a credential in a credential-set table (B.4)
Soft-deletes a credential by flipping active=FALSE and stamping revoked_at=NOW(). Future inbound requests presenting the revoked token’s hash will 401. Provide either credential_id (preferred, safe) or consumer_name (revokes ALL rows for that name — useful for “kill all credentials issued to pod X” but be deliberate). Returns the count of rows revoked. Idempotent — revoking an already-revoked row returns {revoked: 0} with no error.
rotate_credential
Post /ops/rotate-credential | Auth: Admin
Atomically revoke an old credential and issue a fresh one (B.4)
Runs revoke + issue inside one transaction. The old row is soft-deleted (active=FALSE, revoked_at=NOW()); a new row is inserted with the same consumer_name and rpm_limit. Returns the new plaintext token (shown once). Used for credential rotation without a downtime window — operator hands the new token to the consumer, then the consumer drops the old one. If multiple active rows exist for the consumer, the LATEST (by created_at DESC) is rotated; older active rows stay live until separately revoked.
schema
Get /ops/schema | Auth: Read
Get detailed schema metadata (columns, types, indexes)
Returns detailed metadata about all user-created tables in this SQL element’s schema: column names, data types, nullability, primary keys, defaults, and index definitions. Use this to discover table structure before building queries. System tables are excluded.
source
Get /ops/source | Auth: Read
Get any file’s content from the element’s git repository
Reads an arbitrary file from the element’s CAS-backed git tree by its relative path. Same store as
readme, just generalized. Path safety: rejects..traversal, leading/, and null bytes. Use this to viewmain.pyfor action elements, asset files for SPAs, etc. Returns empty content (not an error) if the file doesn’t exist.
source_branches
Get /ops/source/branches | Auth: Read
List Source branches for this element
Returns the standard draft/demo/live Source branches, their current commits, and promotion relationships. Use GET /api/{element_path}/ops/source/branches.
source_fixtures
Post /ops/source/fixtures | Auth: Write
Dry-run or apply approved Source seed fixtures
Scans
.triform/fixtures/manifests from the addressed data element Source repo. Defaults to dry_run=true and never imports live runtime data. Apply requires dry_run=false plus confirm=true and dispatches approved records through existing generated element ops.
source_promote
Post /ops/source/promote | Auth: Write
Promote Source branch forward
Promotes draft to demo or demo to live through the generated element op path. Direct Git pushes to demo/live are blocked by Source policy.
source_repair
Post /ops/source/repair | Auth: Write
Inspect or repair the element Source index
Runs Source repair through the element operation path. Defaults to dry_run=true; set dry_run=false only after reviewing a dry-run report.
source_status
Get /ops/source/status | Auth: Read
Get Source control status for this element
Returns the branch-aware clone URL, checkout commands, current draft commit, child source-link count, portable export summary, Source health, warnings, and auth hints for the addressed element. Use the element-first path: GET /api/{element_path}/ops/source/status.
source_validate
Post /ops/source/validate | Auth: Read
Validate Source branch contents
Validates a Source branch before accepting local Git workflow changes or promotion. Defaults to branch=draft and rejects runtime data, generated output, secret material, and unreadable CAS refs.
stats
Get /ops/stats | Auth: Read
Get aggregate statistics for this element
Health status is computed: error if errors_per_day > 5 or success_rate < 0.8, warning if errors_per_day > 0 or success_rate < 0.95. Firing alerts escalate health to error/warning. Default period is ‘day’. Returns runs_per_day, success_rate, avg_duration_ms, and more.
subscribe
Post /ops/subscribe | Auth: Read
Subscribe to change notifications
Sets up a NATS subscription for real-time notification when data changes in this SQL element’s tables.
tables
Get /ops/tables | Auth: Read
List tables in this element’s schema
Returns all tables in the element’s dedicated schema with column info, row counts, and index details. Useful for discovery before running queries.
tree
Get /ops/tree | Auth: Read
Get the element’s position in the graph — ancestors, children, references, and subtree statistics
Uses per-circle ElementGraph cache for O(1) lookups. Returns ancestors (containment chain), children (direct), members (references), referenced_by (reverse refs), attachments, and subtree stats. Default depth is 3, max is 10. Pass ?include_metadata=true for name/state on each node.
update
Post /ops/update | Auth: Write
Update a row in a table by id
Updates a single row in the specified table by its id. Pass the column values to change as a JSON object. Returns the updated row via RETURNING *. Use the pk parameter to specify a custom primary key column (defaults to id). Use query for complex updates.
update_meta
Patch /ops/update_meta | Auth: Write
Update element metadata (lightweight merge — does NOT bump version or snapshot spec)
Shallow JSONB merge into element.meta. Top-level keys in the provided value replace existing meta values; other keys are preserved. Used for UI metadata like canvas positions, panel state, viewer preferences. Wire-shape op_name is
update_meta(distinct fromupdate) so SSE subscribers + the cache auto-invalidator can distinguish lightweight metadata changes from spec edits without inspecting the payload. The MutatingElementStore wrapper stamps this op_name on the lifecycle event emitted byupdate_element_metastorage calls.
vacuum
Post /ops/vacuum | Auth: Admin
Run storage optimization
Sends a storage optimization hint to PostgreSQL. Useful after large bulk operations to reclaim space and update statistics.
version
Get /ops/version | Auth: Read
Get current version or full history
Returns current version by default. Pass ?history=true for full version history (up to ?limit=N, default 50). Versions are backed by the element_versions table. Every spec update creates a new version entry.
Error Codes
| Code | Class | Retryable | Description |
|---|---|---|---|
SQL_INVALID_TABLE_NAME | validation | no | Table name fails [a-zA-Z_][a-zA-Z0-9_]* pattern (reserved word or injection attempt) |
SQL_NO_PRIMARY_KEY | validation | no | on_conflict=‘update’ requested but table has no primary key; specify on_conflict_columns explicitly |
SQL_INVALID_CONFLICT_COLUMN | validation | no | on_conflict_columns contains a name that is not a valid Postgres unquoted identifier |
SQL_INVALID_SET_COLUMN | validation | no | on_conflict_set_columns contains a name that is not a valid column in the target table |
SQL_NOT_A_CREDENTIAL_SET | validation | no | issue_credential / revoke_credential / rotate_credential called on an SQL element that has no credential_set_table in spec |
SQL_TABLE_NOT_FOUND | validation | no | Table does not exist — run the migrate op first to create the schema (PG 42P01) |
SQL_COLUMN_NOT_FOUND | validation | no | Column referenced in query does not exist in the table (PG 42703) |
SQL_SYNTAX_ERROR | validation | no | SQL syntax error — often an unquoted reserved word used as identifier (PG 42601) |
SQL_DUPLICATE_KEY | validation | no | Unique constraint violation on insert without ON CONFLICT handling (PG 23505) |
SQL_NOT_NULL_VIOLATION | validation | no | NOT NULL constraint violated — provide a value for all required columns (PG 23502) |
Observability
Defined for this element
Metrics
- sql_query_count
- sql_query_latency_ms
- sql_insert_count
- sql_update_count
- sql_delete_count
- sql_migrate_count
- sql_row_count
Events
- sql.query.executed
- sql.query.failed
- sql.insert.executed
- sql.update.executed
- sql.delete.executed
- sql.migrate.executed
Pricing / cost
Platform default
Operation costs
- create: free
- update: free
- delete: free
- get: free
- list: free
- invoke: 10000 micro-AU
- tool_use: free