触发触发器时超出堆栈深度限制

时间:2019-06-20 17:45:09

标签: postgresql database-trigger

我正在尝试建立一个变化缓慢的维表,它跟踪所有记录的历史记录。该表的架构如下:

CREATE TABLE test.dim
(id text,
 column1 text,
 column2 text,
 begin_date timestamp without time zone,
 is_current boolean,
 end_date timestamp without time zone)

我定义了一个触发函数,并在每次插入动作之前将其触发:

CREATE OR REPLACE FUNCTION test.slow_change_func()
  RETURNS trigger AS
$BODY$
  DECLARE
    BEGIN
        IF ( NOT EXISTS ( SELECT 1 FROM yang_test.dim
                          WHERE id= NEW.id  
                                AND(column1 = NEW.column1 OR (column1 is null AND NEW.column1 is null))
                                AND (column2 = NEW.column2 OR (column2 is null AND NEW.column2 is null))
                                AND is_current
                          )
            )
        THEN  UPDATE yang_test.dim
               SET (end_date, is_current) = (now(), FALSE)
               WHERE id = NEW.id
                        AND is_current;
               INSERT INTO test.dim (id, column1, column2, begin_date, is_current, end_date)
               VALUES ( NEW.id, NEW.column1, NEW.column2, now(), TRUE, 'infinity'::timestamp );

         END IF;
      RETURN NULL;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;





CREATE TRIGGER slow_change_trigger
  BEFORE INSERT
  ON test.dim
  FOR EACH ROW
  EXECUTE PROCEDURE test.slow_change_func();

当我尝试测试时,

INSERT INTO test.dim (id, column1, column2, begin_date, is_current, end_date)
               VALUES ( 1, 'hello', 'world', now(), TRUE, 'infinity'::timestamp )

它将引发错误:超出堆栈深度限制。该函数似乎正在运行一个循环。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我想我已经弄清楚了,这符合我的要求:

CREATE OR REPLACE FUNCTION yang_test.slow_change_func()
  RETURNS trigger AS
$BODY$
  DECLARE
    BEGIN
        IF ( NOT EXISTS ( SELECT 1 FROM yang_test.dim
                          WHERE id= NEW.id  
                                AND(column1 = NEW.column1 OR (column1 is null AND NEW.column1 is null))
                                AND (column2 = NEW.column2 OR (column2 is null AND NEW.column2 is null))
                                AND is_current
                          )
            )
        THEN  UPDATE yang_test.dim
               SET (end_date, is_current) = (now(), FALSE)
               WHERE id = NEW.id
                        AND is_current;
        ELSE RETURN null;


         END IF;
        RETURN NEW;
    END;
$BODY$
  LANGUAGE plpgsql VOLATILE
  COST 100;