在 Postgres 10 中自动创建分区

Gab*_*rio 3 postgresql partitioning date dynamic-sql plpgsql

我正在尝试按范围(创建日期)在一个巨大的表中自动执行 Postgres 10 中的分区。

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

我在想这样的事情:

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;
Run Code Online (Sandbox Code Playgroud)

但我在 (

kli*_*lin 6

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$
Run Code Online (Sandbox Code Playgroud)

我使用了匿名代码块,因为create table ...它不会生成任何结果。但是,如果您想编写一个函数,请注意该函数应该返回void而不是使用RETURN QUERY.