从 master table 中查找所有分区 tables "inheriting"

Find all partition tables "inheriting" from master table

假设我有一个 table、"foo",分区为 table、"foo1"、"foo2" 和 "foo3"。但目前我所知道的是有从 table "foo" 继承的分区 tables。如何找到 foo 有 3 个分区,foo1、foo2 和 foo3?

我挖掘此类目录信息的方法是使用 psql。使用 -eE 选项启动 psql:

psql -eE <your database>

然后展示你的table:

\d <your table>

这将列出 psql 为从目录中获取信息而生成的所有查询。这包括继承的 tables.

请记住,目录有可能从一个主要版本更改为另一个主要版本 - 尽管对于此类基本功能而言,这种情况不太可能发生。

使用pg_inherits。示例:

create table my_parent_table (id int);
create table my_child_table_no_1 (check (id < 10)) inherits (my_parent_table);
create table my_child_table_no_2 (check (id >= 10)) inherits (my_parent_table);

select relname
from pg_inherits i
join pg_class c on c.oid = inhrelid
where inhparent = 'my_parent_table'::regclass

       relname       
---------------------
 my_child_table_no_1
 my_child_table_no_2
(2 rows)    

您还可以 select 使用 pg_constraint 检查约束:

select relname "child table", consrc "check"
from pg_inherits i
join pg_class c on c.oid = inhrelid
join pg_constraint on c.oid = conrelid
where contype = 'c'
and inhparent = 'my_parent_table'::regclass

     child table     |   check    
---------------------+------------
 my_child_table_no_1 | (id < 10)
 my_child_table_no_2 | (id >= 10)
(2 rows)

列出所有分区(子表)- 使用 PG v9-v13 测试:

SELECT c.relname FROM pg_inherits i JOIN pg_class p ON i.inhparent = p.oid
JOIN pg_class c ON i.inhrelid = c.oid WHERE p.relname='parentTableName';

从 Postgres 12 开始,有一个 built-in function:

select *
from  pg_partition_tree('the_table'::regclass)
where parentrelid is not null;