Postgres CDC
监听 PostgreSQL 表变更。presence / postgres_changes 监听必须在 subscribe() 之前绑定。
前置条件
本页代码能跑通的前提是业务库已配置好 数据库侧准备(publication、connector 角色授权、RLS 策略)。这些没做的话,订阅会成功但收不到任何事件,容易误判成 SDK 问题。
const channel = realtime.channel("db-changes");
channel.on("postgres_changes", { event: "*", schema: "public" }, (payload) => {
console.log("public schema 变更", payload);
});
channel.on(
"postgres_changes",
{ event: "INSERT", schema: "public", table: "messages" },
(payload) => {
console.log("新增", payload.new);
}
);
channel.on(
"postgres_changes",
{
event: "UPDATE",
schema: "public",
table: "users",
filter: "username=eq.Realtime",
},
(payload) => {
console.log("更新", payload.new, payload.old);
}
);
channel.subscribe((status, err) => {
if (status === "SUBSCRIBED") {
console.log("开始接收数据库变更");
}
if (status === "CHANNEL_ERROR") {
console.error(err);
}
});
filter 可以是原始字符串,也可以用 postgresChangesFilter() 构建,二者线格式相同:
import { postgresChangesFilter } from "@cloudbase/js-sdk/realtime-js";
// 字符串
{ event: "UPDATE", schema: "public", table: "users", filter: "id=eq.1" }
// Builder
{
event: "UPDATE",
schema: "public",
table: "users",
filter: postgresChangesFilter().eq("id", 1),
}
| 运算符 | 字符串 | Builder | 含义 |
|---|---|---|---|
eq | id=eq.1 | .eq("id", 1) | 等于 |
neq | id=neq.1 | .neq("id", 1) | 不等于 |
lt / lte / gt / gte | age=gte.18 | .gte("age", 18) | 比较 |
in | status=in.(active,pending) | .in("status", ["active", "pending"]) | 属于列表 |
like / ilike | title=like.%foo% | .like("title", "%foo%") | 模式匹配 |
is | deleted_at=is.null | .is("deleted_at", null) | IS null/true/false |
match / imatch | title=match.^foo | .match("title", "^foo") | POSIX 正则 |
isdistinct | value=isdistinct.1 | .isDistinct("value", 1) | NULL 安全不等于 |
取反:字符串加 not. 前缀,或使用 .not(column, operator, value)。多个条件用逗号(AND)连接,Builder 则链式调用。
channel.on(
"postgres_changes",
{
event: "UPDATE",
schema: "public",
table: "orders",
filter: postgresChangesFilter()
.gt("amount", 100)
.not("status", "in", ["draft", "archived"]),
},
(payload) => console.log(payload)
);