在 Postgres 10 中自动创建分区

Automating partitions creation in Postgres 10

我正在尝试通过 BY RANGE (date_created) 在巨大的 table 中自动执行 Postgres 10 中的分区。

我注意到没有自动创建分区 tables,因此我想编写一个程序来自动创建那些 tables。

我在想这样的事情:

CREATE OR REPLACE FUNCTION cdi.automating_partitions()
RETURNS TABLE(natural_id text, name text, natural_id_numeric text) AS
$func$
DECLARE
   formal_table text;
BEGIN
   FOR formal_table IN
       select '2017-01-01'::date + (n || ' months')::interval months,
       '2013-02-01'::date + (n || ' months')::interval monthsplus
       from generate_series(0, 12) n
   LOOP
      RETURN QUERY EXECUTE
   'CREATE TABLE cdi.' || 'document' || to_char(months, 'YYYY')  || ''  || to_char(months, 'MM') || ' PARTITION OF cdi.document
 FOR VALUES FROM  (''' ||  to_char(months, 'YYYY')  || to_char(months, 'MM')  || ''',
''' to_char(monthsplus, 'YYYY')  || to_char(monthsplus, 'MM')   ''');'
   END LOOP;
END
$func$  LANGUAGE plpgsql;

但我在 (

附近收到语法错误

将函数format()execute结合使用以获得清晰易读的代码,示例:

do $do$
declare
    d date;
begin
    for d in
        select generate_series(date '2017-01-01', date '2017-12-01', interval '1 month')
    loop
    execute format($f$
        create table cdi.document%s%s partition of cdi.document
        for values from (%L) to (%L)
        $f$, 
        to_char(d, 'YYYY'), to_char(d, 'MM'), d, d+ interval '1 month');
    end loop;
end 
$do$

我使用了 anonymous code block,因为 create table ... 没有生成任何结果。但是,如果要写函数,注意函数要returnvoid,不能用RETURN QUERY.