使用逻辑复制将数据复制到另一个 Postgres 数据库
这个例子,你需要:
🌐 For this example, you will need:
- 一个 Supabase 项目
- 一个 Postgres 数据库(运行 v10 或更新版本)
你将会在这两个数据库上运行命令,以将 Supabase 数据库的更改发布到外部数据库。
🌐 You will be running commands on both of these databases to publish changes from the Supabase database to the external database.
- 在 Supabase 数据库 上创建一个
publication:
1CREATE PUBLICATION example_pub;- 同样在 Supabase 数据库 上,创建一个
replication slot:
1select pg_create_logical_replication_slot('example_slot', 'pgoutput');- 现在连接到你的外部数据库并订阅
publication
这需要与你的数据库建立直接连接(不是连接池),你可以在 Direct connection 部分的 Connect 面板 中找到连接信息。
🌐 This needs a direct connection (not a Connection Pooler) to your database and you can find the connection info in the Connect panel in the Direct connection section.
你还需要确保你的复制目标支持 IPv6(或者你可以启用 IPv4 插件)
🌐 You will also need to ensure that IPv6 is supported by your replication destination (or you can enable the IPv4 add-on)
如果你不想使用 postgres 用户,那你可以用 postgres 用户运行 CREATE ROLE <user> WITH REPLICATION;。
1CREATE SUBSCRIPTION example_sub2CONNECTION 'host=db.oaguxblfdassqxvvwtfe.supabase.co user=postgres password=YOUR_PASS dbname=postgres'3PUBLICATION example_pub4WITH (copy_data = true, create_slot=false, slot_name=example_slot);对于运行 Postgres 17 及以上版本的项目,可以使用你的只读副本的连接字符串订阅一个 只读副本。
🌐 For projects running Postgres 17+, it is possible to subscribe to a Read Replica by using your Read Replica's connection string.
create_slot 被设置为 false,因为提供了 slot_name 并且插槽已经在步骤 2 中创建。要复制插槽创建之前的数据,请将 copy_data 设置为 true。
- 现在我们回到 Supabase 数据库,添加你想要复制到发布中的所有表。
1ALTER PUBLICATION example_pub ADD TABLE example_table;- 使用
pg_stat_replication检查复制状态
1select * from pg_stat_replication;你可以在初始发布中添加更多表,但你需要对订阅数据库执行刷新。
详见 https://www.postgresql.org/docs/current/sql-alterpublication.html
🌐 You can add more tables to the initial publication, but you're going to need to do a REFRESH on the subscribing database. See https://www.postgresql.org/docs/current/sql-alterpublication.html