PostgreSQL中可以使用逻辑订阅来实现数据的逻辑复制,但是逻辑订阅不支持:临时表、无日志表、外部表、物化视图、 常规视图和分区表。
例如直接在分区表上创建发布就会提示报错:
bill=# create publication testpub1 for table t_range;
psql: ERROR: "t_range" is a partitioned table
DETAIL: Adding partitioned tables to publications is not supported.
HINT: You can add the table partitions individually.
那么对于一张分区表我们该如何进行逻辑订阅来复制数据呢?
因为pg中分区表中的数据其实是存在分区中的,尽管我们对主表创建发布,但是我们可以通过对分区创建发布来复制数据。
bill=# \dt+ t_range*
List of relations
Schema | Name | Type | Owner | Size | Description
--------+-----------+-------------------+-------+------------+-------------
public | t_range | partitioned table | bill | 0 bytes |
public | t_range_1 | table | bill | 8192 bytes |
public | t_range_2 | table | bill | 8192 bytes |
public | t_range_3 | table | bill | 8192 bytes |
(4 rows)
例子:
逻辑订阅前准备:
–发布端:
配置pg_hba.conf,允许订阅端通过流复制连接发布端
wal_level必须设置为logical
发布端的角色必须具备replication权限,或者超级用户权限
然后配置发布:
bill=# create publication testpub1 for table t_range_1,t_range_2,t_range_3;
CREATE PUBLICATION
bill=# select * from pg_publication;
oid | pubname | pubowner | puballtables | pubinsert | pubupdate | pubdelete | pubtruncate
--------+----------+----------+--------------+-----------+-----------+-----------+-------------
201722 | testpub1 | 16384 | f | t | t | t | t
(1 row)
–订阅端:
先定义好同样的分区,然后创建订阅:
bill@bill=>create subscription testsub1 connection 'hostaddr=192.168.7.180 port=1921 user=bill dbname=bill' publication testpub1 with (enabled, create_slot, slot_name='sub1_from_pub1');
NOTICE: created replication slot "sub1_from_pub1" on publisher
CREATE SUBSCRIPTION
查看:
数据已经同步过来了。
bill@bill=>\dt+ t_range*
List of relations
Schema | Name | Type | Owner | Size | Description
--------+-----------+-------------------+-------+------------+-------------
public | t_range | partitioned table | bill | 0 bytes |
public | t_range_1 | table | bill | 8192 bytes |
public | t_range_2 | table | bill | 8192 bytes |
public | t_range_3 | table | bill | 8192 bytes |
(4 rows)