如何在PostgreSQL中调试触发器递归?

时间:2017-09-09 17:58:14

标签: postgresql debugging recursion triggers plpgsql

如何判断我的触发器是否在PostgreSQL中递归或循环? 是否有如何使用它的示例?

我正在寻找一个示例,说明如何add code to my current trigger检查失败的原因是否是递归。

1 个答案:

答案 0 :(得分:1)

您可以RAISE NOTICE pg_trigger_depth();这是一个我们也使用TG_NAME的例子

CREATE TABLE foo (id int primary key);

CREATE FUNCTION bar()
RETURNS trigger
AS $$
  BEGIN
    -- Debugging information
    RAISE NOTICE '[%] TRIGGER DEPTH %', TG_NAME, pg_trigger_depth();
    INSERT INTO foo VALUES (42);
    RETURN null;
  END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER bar
  AFTER INSERT ON foo
  FOR EACH ROW
  EXECUTE PROCEDURE bar();

INSERT INTO foo VALUES (41);

运行此产生

NOTICE:  [bar] TRIGGER DEPTH 1
NOTICE:  [bar] TRIGGER DEPTH 2
ERROR:  duplicate key value violates unique constraint "foo_pkey"
DETAIL:  Key (id)=(42) already exists.
CONTEXT:  SQL statement "INSERT INTO foo VALUES (42)"
PL/pgSQL function bar() line 5 at SQL statement
SQL statement "INSERT INTO foo VALUES (42)"
PL/pgSQL function bar() line 5 at SQL statement

虽然这有助于调试情况making a system dependent on this behavior is not a good idea