私はそれをscdr_buzと呼ぶテーブルを持っており、月ごとにパーティション化しています。挿入時にトリガーを作成し、アップサートを処理し、存在しない場合はテーブルを作成してからアップサートします。1増分のシーケンスi_buz_scdrシーケンスがありますが、1の増分ではなく、ランダムに行を追加したときの動作です。トリガーのコードは次のとおりです。
CREATE OR REPLACE FUNCTION tbl_scdr_buz_insert_trigger() RETURNS TRIGGER AS $$
BEGIN
EXECUTE 'UPDATE scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' sc SET c_total_calls = sc.c_total_calls + ($1).c_total_calls WHERE (sc.c_prefix_id = ($1).c_prefix_id AND sc.v_prefix_id = ($1).v_prefix_id AND sc.start_time = ($1).start_time)'
USING NEW;
EXECUTE 'INSERT INTO scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||'(customer_name, ...) Select ($1).*
WHERE NOT EXISTS (SELECT * FROM scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' WHERE (...))'
USING NEW;
RETURN NULL;
EXCEPTION
WHEN undefined_table THEN
EXECUTE 'CREATE TABLE IF NOT EXISTS scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (CHECK ( start_time >= '''|| to_char(NEW.start_time, 'YYYY-MM-01 00:00') ||''' AND start_time < '''|| to_char(NEW.start_time + INTERVAL '1 month', 'YYYY-MM-01 00:00') ||''' )) INHERITS (scdr_buz)';
EXECUTE 'CREATE INDEX i_buz_scdr_'|| to_char(NEW.start_time, 'YYYY_MM') ||' ON scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (switch_name, customer_name, client_name_id, vendor_name_id, vendor_connection, c_prefix_id, v_prefix_id, start_time, c_billing_prefix, v_billing_prefix)';
EXECUTE 'CREATE INDEX i_buz_scdr_starttime_'|| to_char(NEW.start_time, 'YYYY_MM') ||' ON scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' (start_time)';
EXECUTE 'UPDATE scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' sc SET c_total_calls = sc.c_total_calls + ($1).c_total_calls WHERE (sc.c_prefix_id = ($1).c_prefix_id AND sc.v_prefix_id = ($1).v_prefix_id AND sc.start_time = ($1).start_time)'
USING NEW;
EXECUTE 'INSERT INTO scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||'(customer_name, ...) Select ($1).*
WHERE NOT EXISTS (SELECT * FROM scdr_buz_'|| to_char(NEW.start_time, 'YYYY_MM') ||' WHERE (...))'
USING NEW;
RETURN NULL;
END
$$
LANGUAGE plpgsql;
CREATE TRIGGER fk_checkTrigger_buz_scdr
BEFORE INSERT ON scdr_buz
FOR EACH ROW
EXECUTE PROCEDURE tbl_scdr_buz_insert_trigger();