# Database change events
Source: https://sovaria.in/docs/realtime-database-changes

Get told when rows are inserted, updated or deleted: turning change capture on per table, the event format, delivery and ordering, writes from direct Postgres connections, who may listen, and why an event may be missing.

With change capture on, every write to a chosen table publishes an event on the channel `db.table.<table>`. Use it to refresh a list when data changes, without polling.

## Turn it on

1. **Realtime › Database change data capture** — Switch it on and pick the tables. Nothing is published for tables you didn't pick.
2. **Allow listeners** — Callers who may read the table through a rule that names it (`ALLOW IF ctx.resource.name == "orders" …`) may also listen to `db.table.orders`; each event is still filtered by their row security. To allow listening more narrowly or more widely, add a rule that lets the right callers `SUBSCRIBE` to `db.table.<table>` ([Policy language (SPL)](https://sovaria.in/docs/policy-language)); a DENY on the channel always wins.
3. **Listen** — Subscribe like any channel.
```js
sovaria.realtime.channel('db.table.orders', {
  onMessage: async (event) => {
    // { event_type: 'row.inserted' | 'row.updated' | 'row.deleted', table, schema, timestamp, event_id, row_count, new, old }
    if (event.event_type !== 'row.deleted' && event.new?.id) upsertOrder(event.new)   // a row this user may read
    else setOrders(await loadMyOrders())                                             // a delete, or no row: re-read
  },
})
```

> **Tip:** With supabase-style channels: `channel(name).on('postgres_changes', { event, schema, table }, cb)` listens on the same events ([Broadcast, presence and table changes](https://sovaria.in/docs/realtime-broadcast-and-presence)).

## What an event contains

| Field | Value |
|---|---|
| `event_type` | `row.inserted`, `row.updated` or `row.deleted` |
| `table`, `schema` | The table that changed (`public`) |
| `row_count` | How many rows the statement changed |
| `timestamp` | When it was committed |
| `event_id` | Unique per event — use it to ignore a duplicate |
| `new` | Inserts and updates: the row, exactly as this listener could read it with its own query. `{}` when the row can't be sent (see below) |
| `old` | Deletes: the row's primary key, only for tables without row-level security; otherwise `{}` |
| `errors` | Set when the row was too large to send (over 64 KB): `new` then holds only its key columns |
| `truncated` | `true` on a last event for a statement that changed more than 100 rows: `row_count` is how many more changed |

Each listener gets the changed rows **it** may read. Sovaria reads them for each listener under that listener's own access policies and row-level security, the same way its own query would. A row the listener can't see is never sent to it, and it isn't told about that change at all. A statement that changes many rows sends one event per row.

Deleted rows can't be checked against your policies any more, because they're gone. A delete from a table with row-level security therefore says only how many rows went (`old` is `{}`): re-read the list. A table without row-level security also sends the deleted row's primary key.

To get fewer events, add a filter when you connect, in the form `column=op.value` (`eq`, `neq`, `lt`, `lte`, `gt`, `gte` or `in`). For example, `status=eq.open` or `room_id=in.(1,2)`. It's applied on the server before anything is sent; deletes are never filtered. If a row can't be read for a moment, the event still arrives, with `new: {}`.

## Delivery and ordering

- Events are written to a durable outbox before the write returns and delivered from there with retries, so a restart delays them rather than losing them.
- Events for one table arrive in commit order.
- A retried delivery carries the same `event_id`; duplicates are dropped by realtime, and your code can ignore any it has already handled.
- The same events can also call your HTTPS endpoint — database webhooks ([Database webhooks](https://sovaria.in/docs/database-webhooks)).

## Writes from outside the API (change capture)

For the tables you picked, rows written through Sovaria's API (the SDKs, REST and GraphQL) are announced. Rows written over a **direct Postgres connection** (`psql`, an ORM, a migration tool, a function with its own driver) are announced too once the database records its own changes: a trigger on each captured table notes every changed row in a private outbox in your project's database, and Sovaria turns that into the same events and [Database webhooks](https://sovaria.in/docs/database-webhooks).

- It switches on by itself when you turn on database change events for the project (within about 30 seconds). You can also set it yourself with the project team's session or the service key.
- `tables: null` (the default) captures every table, including ones created later over any connection; a list captures only those tables.
- Events are grouped per transaction, table and operation, carry the changed rows' primary keys (at most 100 per event) and how many rows changed, and have a stable `event_id`, so a redelivery is dropped.
- App users and anon keys can neither read the outbox nor write to it. Rows nothing has delivered are pruned after 24 hours.
- Checking the outbox never wakes a sleeping database, and its connections don't count as use.

TypeScript:
```ts
const capture = await sovaria.data.cdc.getCapture()       // { enabled, tables, … backlog }
await sovaria.data.cdc.setCapture(true)                     // every table
await sovaria.data.cdc.setCapture(true, ['orders', 'items'])
await sovaria.data.cdc.setCapture(false)
```

Python:
```python
capture = await sovaria.api.data.get_cdc_capture()
await sovaria.api.data.set_cdc_capture(True)                # every table
await sovaria.api.data.set_cdc_capture(True, tables=["orders", "items"])
```

HTTP:
```bash
curl -X PUT "$URL/api/v1/data/rel/cdc/capture" \
  -H "apikey: $SERVICE_KEY" -H "Content-Type: application/json" \
  -d '{"enabled": true, "tables": null}'
```

## An event didn't arrive

| Check | Why |
|---|---|
| Is change capture on for that table? | Only picked tables publish. |
| Was it written over a direct Postgres connection? | Those writes publish only while the database records its own changes ([change capture](https://sovaria.in/docs/realtime-database-changes#capture)). `getCapture()` says whether it does. |
| Did the statement change rows? | An `update` that matched no rows (for example because of row-level security) publishes nothing. |
| Is the client allowed to subscribe? | A refused subscription closes with `4401`/`4408`. |
| Was the client offline? | Catch up with replay ([Channels and connections](https://sovaria.in/docs/realtime-channels)). |
