我必须对数据库进行分区以提高性能。但是插入速度减慢了2-3倍。
我们在一个查询中插入了大量数据,并且我读取了触发器的内容是为每一行运行的,但规则只在每个查询中运行。这是我怀疑的问题。
我甚至不确定这是否可以在规则中做到。 所以我需要帮助优化此触发器或将其转换为规则。
CREATE OR REPLACE FUNCTION create_partition_and_insert() RETURNS trigger AS
$BODY$
DECLARE
partition_date TEXT;
partition TEXT;
BEGIN
partition_date := to_char((SELECT time from timestamps where ID=NEW.timestamp_id),'YYYY_MM_DD');
partition := TG_RELNAME || '_' || partition_date;
IF to_regclass(partition) IS NULL THEN
RAISE NOTICE 'A partition has been created %',partition;
EXECUTE 'CREATE TABLE ' || partition ||'(
timestamp_id integer references timestamps(id),
channel_id integer references channels(id)
) INHERITS (' || TG_RELNAME || ');';
EXECUTE 'CREATE INDEX ' || partition ||'_timestamp_id_index ON ' || partition || ' (timestamp_id);';
EXECUTE 'CREATE INDEX ' || partition ||'_channel_id_index ON ' || partition || ' (channel_id);';
END IF;
EXECUTE 'INSERT INTO ' || partition || ' SELECT ($1).*;' USING NEW;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;
"