Tutorial: Building with CleaveDB
ON ... RUN — triggers
Database triggers allow you to execute reactive CleaveQL operations automatically when documents are written or modified. Using the ON ... RUN statement, you can create automated audit entries, generate cross-bucket notifications, or mirror data synchronously.
Trigger definition syntax
A trigger binds an event (such as POUR) on a target bucket to an executable query string:
ON POUR INTO <bucket> RUN '<CleaveQL query>'The query inside the single quotes is evaluated dynamically whenever a matching document is written.
Dynamic field interpolation
Inside the trigger query string, CleaveDB automatically replaces dollar-prefixed variables with values from the incoming document:
$gid: Resolves to the unique document ID or global key (e.g.purchases:p101).$field_name: Resolves to any top-level JSON key present in the inserted payload (e.g.$item,$price,$customer_id).
Audit trail generation
A classic use case is writing a synchronized audit ledger entry every time a purchase is recorded:
ON POUR INTO purchases RUN 'POUR INTO audit "$gid" {"action": "item_purchased", "item": "$item"}'When an application writes a new purchase:
POUR INTO purchases "p99" {"item": "Quantum Keyboard", "price": 149.99}The database engine automatically executes the interpolated query, creating audit:p99 with {"action": "item_purchased", "item": "Quantum Keyboard"}.
Automated notification dispatch
Triggers can also seed workflow queues, such as order fulfillment or downstream indexing jobs:
ON POUR INTO orders RUN 'POUR INTO notifications "$gid" {"status": "pending_fulfillment", "total": "$total"}'This guarantees that the secondary record is created in the same database engine lifecycle as the primary write.
