elements
Start Docs Blog Demos UI Pricing
Elements Manual
  • Getting Started
  • CLI
  • Build
  • Browser
  • Packages
  • TypeScript
  • Elements HTML
  • Assets
  • RPC
  • Router
  • Session
  • Database
  • Migrations
  • LiveTable
  • Channel
  • Jobs
  • Email
  • Payments
  • JSON
  • Async
  • Style
  • UI
  • JSOC
  • Config
  • Tests
  • Logs
  • Deploy
  • Editors
  • Recipes
    • Todo App
    • Todo App: Markup and Styles
    • Authentication
    • Form Validation
    • Signup with Email Confirmation
    • Signup Wizard
    • Admin Roles
    • File Upload
    • Serving Assets From the Database
    • Live Comments
    • Likes / Votes Toggle
    • Shared Lists
    • Team-Partitioned Table
    • Chat Rooms
    • Typing Indicator
    • Grouped Feed Without Flicker
    • Unread Counts
    • Room Presence
    • Collaborative Canvas
    • Infinite Scroll Feed
    • Bidirectional Partition
    • Search and Filter
    • Admin Table
    • Markdown Blog
    • Public and Admin Views
    • Cron Cache
    • Live Dashboard
    • Live Updates From Any Write
    • Marketing Page
    • Status Indicators
    • Markdown Editor
    • Time Ago
  • Licenses
  • Issues
  • Changelog
Manual / Recipes/ Live Updates From Any Write

Live Updates From Any Write

elements man recipes/live-from-sql

On This Page

  • The channel
  • The trigger
  • Partitioned tables
  • Verify with a write from outside the app
  • Related

A LiveTable view broadcasts every write that goes through it. Add a Postgres trigger and every other write broadcasts too: an @rpc calling sqlAsync, a cron job, a webhook handler, a migration backfill, or elements db -sql. The trigger calls pg_notify with the written row, Postgres delivers the notification to every app server, and each app server sends the row to its open pages that have a view of the table. A view broadcasts the writes that go through it. The trigger makes Postgres broadcast every other write to the table.

Insert, update and delete through a live view already broadcast, which is what elements man recipes/todo-app and most of the recipes here do. The trigger is useful on any table a page watches: a job, a backfill or a psql session writing to the table updates the page, so you can test the UI by changing the database directly.

The channel

Every write to a LiveTable notifies the table's one channel, and the channel's name is the table's name. Each app server listens on it once and sends each row to the views whose partition it matches. The trigger notifies that same channel:

LiveTable
import { LiveTable } from "@elements/app"; export interface Ping { id: string; createdAt: Date; body: string; } export let pings = new LiveTable<Ping>();

The compiler names the table from the variable, camelCase to snake_case, so pings is pings and chatMessages is chat_messages. That string is the channel the trigger hashes.

The trigger

Terminal
elements create migration 'notify pings'
app/migrations/<timestamp>-notify-pings.migration.sql
-- notify pings create or replace function pingsNotify() returns trigger language plpgsql as $$ declare r record; payload text; begin r := coalesce(new, old); payload := json_build_object( 'op', lower(tg_op), 'data', json_build_object( 'id', r.id, 'createdAt', json_build_object('$type', 'Date', '$value', (extract(epoch from r.createdAt) * 1000)::bigint), 'body', r.body ) )::text; -- NOTIFY takes under 8000 bytes. A larger row goes as its id, and the -- server reads the row back. if octet_length(payload) >= 8000 then payload := json_build_object('op', lower(tg_op), 'id', r.id)::text; end if; perform pg_notify(channel_name('pings'), payload); return r; end; $$; create trigger pingsNotifyTrigger after insert or update or delete on pings for each row execute function pingsNotify();

The trigger function above does five things that every trigger on a LiveTable's table has to do:

  • channel_name() hashes a logical name to 16 characters. Postgres caps an identifier at 63 and truncates silently past it, so the framework hashes every channel name and your trigger has to hash the same way. Elements creates the function in the database as part of its baseline schema; you do not create it.
  • op is insert, update or delete. lower(tg_op) gives exactly that.
  • data is the row in the field names your app uses, not the column names. Elements converts camelCase identifiers in a migration, function bodies included, so r.createdAt reads the created_at column, while the quoted key 'createdAt' stays as written for the browser.
  • A Date is sent as { "$type": "Date", "$value": <milliseconds> }. A plain timestamp string is still a string in the browser, so a template that sorts or formats the field gets a string where it expects a Date. Every other column is sent as its own JSON value.
  • The size. Postgres rejects a NOTIFY payload of 8000 bytes or more, and the write that fired the trigger fails with it. A row that large goes as { "op": ..., "id": ... } with no data, and each app server reads the row back through the view's select before the browsers get it. A delete needs only the id.

after matters: the row has to be committed before the notification goes out, or a listener can query for a row that is not there yet. coalesce(new, old) covers delete, where new is null.

Partitioned tables

The same trigger serves every view of the table, whole or partitioned. The app server listens on the table's one channel and sends a page on chatMessages.view({ roomId }) only the rows whose roomId matches:

Partitioned table
perform pg_notify(channel_name('chat_messages'), payload);

A browser watching room A never receives room B. An update that moves a row to another room is sent to the old room's pages as a delete and to the new room's pages as an insert, because each app server keeps a record of which rows each of its pages holds. The trigger sends the row as it is after the update, and the app server turns it into the delete and the insert.

Verify with a write from outside the app

Open the page, then write from outside the app:

Terminal
elements db -sql "insert into pings (body) values ('from outside the app')"

The row appears in the open page, written from outside the app.

elements db -sql converts camelCase names like sql() does, so roomId works there. The interactive shell that elements db opens is plain psql: there, write the names the database has, room_id, not roomId.

Related

  • livetable/mutations: writing through a view, which broadcasts with no trigger.
  • livetable/options: the channel and table options.
  • channel: the Channel class and channel_name(). A LiveTable broadcasts on a channel named for its table.
Prev Live DashboardNext Marketing Page
Product
Manual Pricing Compare
Company
History Contact
Legal
Privacy Policy Acceptable Use Terms License Agreement
© Elements Dev Corporation 2026