2017-10-17 1 views
1

Postgres 10의 파티션을 BY RANGE (date_created)로 거대한 테이블에 자동화하려고합니다.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; 

을하지만 (

+2

PL/pgSQL 블록 외부에서'execute'를 사용할 수 없습니다 (SQL 쿼리의 일부가 아닌) –

+1

어떤 오류가 발생합니까? – JustMe

답변

1

사용 execute과 함께 기능 format() 명확하고 읽을 수있는 코드를 얻기 위해 근처의 구문 오류, 예 :

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 ...은 결과를 생성하지 않습니다. 그러나 함수를 작성하려면 함수가 void을 반환하고 RETURN QUERY을 사용하지 않아야합니다.