# Database event functions

Source: https://cubibase.com/docs/functions/database-events

Also available: [Markdown version](https://cubibase.com/docs/functions/database-events.md) · [llms.txt](https://cubibase.com/llms.txt) · [full site content](https://cubibase.com/llms-full.txt)

Run a CubiBase Function after an INSERT, UPDATE or DELETE commits on a table you choose. Events are captured atomically with your data change and delivered asynchronously — a function failure can never roll back your transaction.

## Configure a trigger

In the function editor open Triggers → Add trigger → Database events. Pick the table (public schema in the current release) and the operations; optionally include the previous record for UPDATE/DELETE. The platform installs a generated PostgreSQL trigger that writes to a transactional outbox (`functions.events_outbox`) in your project database — you never write trigger SQL yourself.

**Trigger configuration**

```json
{
  "kind": "database",
  "config": {
    "schema": "public",
    "table": "orders",
    "events": ["INSERT", "UPDATE", "DELETE"],
    "includeOldRecord": true
  }
}
```

- One function can subscribe to several tables; one table can feed several functions.
- Schema and table identifiers are validated; the generated trigger SQL is injection-safe.
- Removing the subscription drops the installed PostgreSQL trigger.
- Events are captured only for committed transactions — a rolled-back write produces no event.

## The event payload

**request.event · database.insert**

```text
// request.event on a database trigger (schemaVersion 1)
{
  "schemaVersion": 1,
  "eventId": "8c1f…",
  "type": "database.insert",
  "projectId": "4c8d…",
  "schema": "public",
  "table": "orders",
  "operation": "INSERT",
  "newRecord": { "id": "…", "total": 4200, "user_id": "…" },
  "oldRecord": null,
  "actorUserId": "user_ada",
  "timestamp": "2026-11-20T10:05:00.000Z",
  "correlationId": "…"
}
```

`oldRecord` is null unless you enabled “include previous record”. `actorUserId` carries the end-user id when the write came through the Data API with a user JWT.

## Delivery semantics

- At-least-once: a delivery can repeat after a retry. Deduplicate on eventId — the template shows the pattern.
- Retries use exponential backoff; exhausted deliveries land in a queryable dead-letter state (Executions & Logs → Delivery queue).
- Function writes go through the same scoped database access as any invocation; recursion depth is capped.
- Outbox rows are cleaned up on a retention schedule; inactive projects are not polled without bound.

**Idempotent change handler**

```ts
export default async function handler(request: any, ctx: any) {
  const event = request.event;
  // At-least-once delivery: skip work you already did for this eventId.
  const seen = await ctx.db.from('processed_events').select({ event_id: event.eventId });
  if (seen.rows?.length > 0) return { duplicate: true };

  const record = event.operation === 'DELETE' ? event.oldRecord : event.newRecord;
  await ctx.db.from('audit_log').insert([{
    table_name: event.table,
    operation: event.operation,
    event_id: event.eventId,
    record_id: String(record?.id ?? ''),
    occurred_at: event.timestamp,
  }]);
  await ctx.db.from('processed_events').insert([{ event_id: event.eventId }]);
  return { ok: true };
}
```

> **note**: This is not a synchronous constraint mechanism. If a rule must block the write itself, use a PostgreSQL constraint or a native database trigger (Database → Database Triggers). CubiBase Functions react after commit.

## Additional resources

- [Native database triggers](https://cubibase.com/docs/database/triggers) Synchronous SQL triggers, a different tool.
- [Templates](https://cubibase.com/docs/functions/templates) Database Change Handler and Send Email.
