PostgreSQL自定义表分区函数

PostgreSQL自定义表分区函数

hash

--建表时指定分区列 partition by hash (c_bh)
CREATE TABLE t_table1
(
    c_bh   character(32) NOT NULL,
    c_name character varying(300)
) partition by hash (c_bh);

--创建分区函数
create or replace function create_hash_partition(t text, n int) returns text as
$body$
begin
    for i in 0..n - 1
        loop
            execute format('create table %s_p%s partition of %s for values WITH (MODULUS %s, REMAINDER %s)', t, i, t, n, i);
            raise info 'create %_p%',t,i;
        end loop;
    return 'success';
end;
$body$ LANGUAGE plpgsql;

-- 执行分区
select create_hash_partition('t_table1', 4);

range

--建表时指定分区列 partition by range (c_status)
CREATE TABLE t_table1
(
    c_bh   character(32) NOT NULL,
    c_name character varying(300),
    c_status varchar
) partition by range (c_status);

drop function create_range_partition;
create or replace function create_range_partition(t text, n int) returns text as
$body$
begin
    for i in 0..n - 1
        loop
            execute format('create table %s_p%s partition of %s for values from  (%s) to (%s)', t, i, t, i, i+1);
            raise info 'create %_p%',t,i;
        end loop;
    return 'success';
end;
$body$ LANGUAGE plpgsql;

select create_range_partition('t_table1', 4);

list

--建表时指定分区列 partition by list (c_status)
CREATE TABLE t_table1
(
    c_bh   character(32) NOT NULL,
    c_name character varying(300),
    c_status varchar
) partition by list (c_status);

--创建List分区函数
create or replace function create_list_partition(t text, val text) returns text as
$body$
    DECLARE
    -- 分区参数(用英文【,】号分割)
    v varchar;
begin
    for v in (select regexp_split_to_table(val, ','))
        loop
            execute format('create table %s_%s partition of %s for values in (''%s'')', t, v, t, v);
            raise info 'create %_p%',t,v;
        end loop;
    -- 创建默认分区
    execute format('create table %s_%s partition of %s default', t, 'default', t);
    return 'success';
end;
$body$ LANGUAGE plpgsql;

select create_list_partition('t_table1', '100,200,300,400');

统计分区情况

SELECT nmsp_parent.nspname AS parent_schema,
       parent.relname      AS parent,
       nmsp_child.nspname  AS child,
       child.relname       AS child_schema
FROM pg_inherits
         JOIN pg_class parent
              ON pg_inherits.inhparent = parent.oid
         JOIN pg_class child
              ON pg_inherits.inhrelid = child.oid
         JOIN pg_namespace nmsp_parent
              ON nmsp_parent.oid = parent.relnamespace
         JOIN pg_namespace nmsp_child
              ON nmsp_child.oid = child.relnamespace
WHERE parent.relname = 't_table1';
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

dushuaifeng

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值