PostgreSQL Trigger
Trigger workflows on database changes using LISTEN/NOTIFY
PostgreSQL Trigger
The PostgreSQL trigger allows you to initiate workflows based on database changes using PostgreSQL's LISTEN/NOTIFY mechanism. It can automatically set up database triggers to watch for INSERT, UPDATE, and DELETE operations on specific tables.
Installation
pnpm add @stepflowjs/trigger-postgresUsage
import { PostgresChangeTrigger } from "@stepflowjs/trigger-postgres";
const trigger = new PostgresChangeTrigger({
connectionString: process.env.DATABASE_URL,
channel: "order_changes",
table: "orders",
operations: ["INSERT", "UPDATE"],
});
await trigger.start(async (event) => {
console.log("Database change detected:", event.data);
await stepflow.trigger("process-order", event.data);
});How it Works
When you specify a table in the configuration, the trigger will:
- Create a PostgreSQL function that sends a
NOTIFYevent with the row data as JSON. - Create a database trigger on the specified table that calls this function after the configured operations.
- Start a dedicated connection to
LISTENon the specified channel.
If you don't specify a table, the trigger will simply LISTEN on the channel for any manual NOTIFY events sent from your database or other applications.
Configuration
| Option | Type | Description |
|---|---|---|
connectionString | string | PostgreSQL connection string |
channel | string | LISTEN/NOTIFY channel name |
table | string | Optional table to watch for changes |
operations | string[] | Optional operations to watch (INSERT, UPDATE, DELETE) |
Event Data
The event data contains the operation type and the row data:
{
operation: "INSERT" | "UPDATE" | "DELETE";
table: string;
old?: Record<string, any>; // Previous row data (for UPDATE and DELETE)
new?: Record<string, any>; // New row data (for INSERT and UPDATE)
}