如何从 Postgres 系统目录中识别用于对表进行分区的列

Con*_*bil 1 postgresql partitioning postgresql-10

鉴于这样创建的表......

CREATE TABLE measurement (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
) PARTITION BY RANGE (logdate);
Run Code Online (Sandbox Code Playgroud)

如何确定它被分区在哪一列上?- 在本例中,仅通过查询 postgres 目录来获取“logdate”。

我查看了目录中明显的位置(pg_class、pg_index),但没有任何结果。

(使用10.5版本)

McN*_*ets 6

我不是 PostgreSQL 专业人士,但经过一番挖掘,我找到了一个可能可以帮助您的解决方案。(仅适用于10或以上版本)

首先,我通过向分区定义添加两列来稍微修改您的表(只是为了向您展示最终结果):

CREATE TABLE measurement (
    city_id         int not null,
    logdate         date not null,
    peaktemp        int,
    unitsales       int
) PARTITION BY RANGE (city_id,logdate);
Run Code Online (Sandbox Code Playgroud)

这是我的解决方案:

select 
    par.relnamespace::regnamespace::text as schema, 
    par.relname as table_name, 
    partnatts as num_columns,
    column_index,
    col.column_name
from   
    (select
         partrelid,
         partnatts,
         case partstrat 
              when 'l' then 'list' 
              when 'r' then 'range' end as partition_strategy,
         unnest(partattrs) column_index
     from
         pg_partitioned_table) pt 
join   
    pg_class par 
on     
    par.oid = pt.partrelid
join
    information_schema.columns col
on  
    col.table_schema = par.relnamespace::regnamespace::text
    and col.table_name = par.relname
    and ordinal_position = pt.column_index;
Run Code Online (Sandbox Code Playgroud)
架构| 表名 | 列数 | 列索引 | 列名
:-------------------------- | :---------- | ----------: | ------------: | :----------
fiddle_ctcqwfrzpcyngmgnqkdy | 测量| 2 | 1 | 城市ID    
fiddle_ctcqwfrzpcyngmgnqkdy | 测量| 2 | 2 | 日志日期    

db<>在这里摆弄

pg_分区表

目录 pg_partitioned_table 存储有关表如何分区的信息。

解除嵌套partattrs可以获得分区中涉及的每一行的列索引。然后您可以加入information_schema.columns只是为了检索每列的名称。

+-----------+------------+---------------------+-------------------------------------------------------------|
| partattrs | int2vector | pg_attribute.attnum | This is an array of partnatts values that indicate          |
|           |            |                     | which table columns are part of the partition key.          |
|           |            |                     | For example, a value of 1 3 would mean that the first       |
|           |            |                     | and the third table columns make up the partition key.      |
|           |            |                     | A zero in this array indicates that the corresponding       |
|           |            |                     | partition key column is an expression, rather than a simple |
|           |            |                     | column reference.                                           |
+-----------+------------+---------------------+-------------------------------------------------------------|
Run Code Online (Sandbox Code Playgroud)