PostgreSQL继承了表和插入触发器

时间:2016-08-22 21:26:36

标签: sql postgresql partitioning database-trigger

我试图按照建议here创建一个垂直分区表来存储时间序列数据。

到目前为止,我的架构看起来像这样:

CREATE TABLE events 
(
     topic text, 
     t timestamp, 
     value integer, 
     primary key(topic, t)
);

CREATE TABLE events_2014 
(
     primary key (topic, t), 
     check (t between '2014-01-01' and '2015-01-01') 
) INHERITS (events);

现在我尝试创建一个INSTEAD OF INSERT触发器,以便可以在events表上插入事件,并且该行最终会出现在右侧子表中。但文档说只能在视图上创建INSTEAD OF INSERT触发器,而不是表(或子表):

CREATE OR REPLACE FUNCTION insert_events () RETURNS TRIGGER AS $insert_events$ BEGIN
  IF new.t between '2014-01-01' and '2015-01-01' THEN
    INSERT INTO events_2014 SELECT new.*;
  ...
  END IF
  RETURN NULL;
END;
$insert_events$ LANGUAGE PLPGSQL;

CREATE TRIGGER insert_events INSTEAD OF INSERT ON events FOR EACH ROW EXECUTE PROCEDURE insert_events();
ERROR:  "events" is a table
DETAIL:  Tables cannot have INSTEAD OF triggers.

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

您需要声明BEFORE INSERT次触发器。

Documentation on partitioning 是这方面知识的重要来源,并且充满了例子。

来自文档的示例功能

CREATE OR REPLACE FUNCTION measurement_insert_trigger()
RETURNS TRIGGER AS $$
BEGIN
    IF ( NEW.logdate >= DATE '2006-02-01' AND
         NEW.logdate < DATE '2006-03-01' ) THEN
        INSERT INTO measurement_y2006m02 VALUES (NEW.*);
    ELSIF ( NEW.logdate >= DATE '2006-03-01' AND
            NEW.logdate < DATE '2006-04-01' ) THEN
        INSERT INTO measurement_y2006m03 VALUES (NEW.*);
    ...
    ELSIF ( NEW.logdate >= DATE '2008-01-01' AND
            NEW.logdate < DATE '2008-02-01' ) THEN
        INSERT INTO measurement_y2008m01 VALUES (NEW.*);
    ELSE
        RAISE EXCEPTION 'Date out of range.  Fix the measurement_insert_trigger() function!';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

来自文档的示例触发器

CREATE TRIGGER insert_measurement_trigger
    BEFORE INSERT ON measurement
    FOR EACH ROW EXECUTE PROCEDURE measurement_insert_trigger();

NULL触发器返回BEFORE将使父表保持为空。