是否可以使用逻辑解码来复制单个 table?

It's possible to use logical decoding to replicate a single table?

我正在研究 logical decoding and I've been able to create a slot and replicate all transactions in a database to another using streaming replication protocol,效果非常好。

但我只需要复制一个 table 而不是数据库中的所有 table。

所以,我的问题是:logical decoding 是否允许过滤单个 table 的流?

我目前的提示是创建自定义 logical decoding output plugin,我错了吗?

更新

我已经基于来自 postgresql 源的 contrib/test decoding 构建了一个 output plugin,这是一个很好的解决方法。然而它对实际用例没有用,所以我决定将其他一些项目作为参考来进行分叉和更新。

对我来说最好的是 wal2json,所以我决定分叉它并添加 table 过滤器作为一个选项,而不是对 table 名称进行硬编码。

Here is the fork and this is the changeset.

如何使用

首先使用 wal2json 插件创建插槽:

pg_recvlogical -d postgres --slot test_slot --create-slot -P wal2json

然后开始收流

pg_recvlogical -d postgres --slot test_slot --start -o limit-to=table_foo,table_bar -f -

现在我们已准备好接收仅 table_footable_bar 的更新。


这是一个非常好的挑战,我不是 c 开发人员,我知道代码需要一些优化,但目前它的效果比预期的要好。

根据 documentation you can implement your own synchronous replication solutions by implementing streaming replication interface methods:

  • CREATE_REPLICATION_SLOT slot_name LOGICAL options
  • DROP_REPLICATION_SLOT slot_name
  • START_REPLICATION SLOT slot_name LOGICAL options

除了上面的接口你还需要实现Logical Decoding Output plugin. In this plugin interface you need to adjust Change Callback操作,监听所有的DML操作:

The required change_cb callback is called for every individual row modification inside a transaction, may it be an INSERT, UPDATE, or DELETE. Even if the original command modified several rows at once the callback will be called individually for each row.

这是您要检查特定 table 复制的函数。还要注意 Change Callback 不会处理 UNLOGGED and TEMP tables 的事实,但我想这不是严格的限制。

wal2json 的当前版本有这些选项:

* `filter-tables` - tables to exclude
* `add-tables`- tables to include

用法:

pg_recvlogical -slot test_slot -o add-tables=myschema.mytable,myschema.mytable2

参考:https://github.com/eulerto/wal2json#parameters