开发者

How can I use "IF statements" in a postgres trigger

I have a trigger function that I only want to fire on certain instances of INSERTS, in this case, if do_backup = true. If it fires in all instances, I get an infinite loop. The logic seems pretty simple to me, and the rest of the function works. But the trigger function does not seem to register my conditional and always runs, even when backup = true.

CREATE OR REPLACE FUNCTION table_styles_backup() RETURNS
 TRIGGER AS $table_styles_backup$

 DECLARE
 ...
 do_backup  boolean;

    BEGIN
 SELECT backup INTO do_backup FROM table_details WHERE id=NEW.table_meta_id;

        IF (do_backup = true) THEN 

  ...


            INSERT INTO table_styles_versions 
   (
   ...
   )

  VALUES (
   ...
   );
 END IF;

    RETURN NULL;

    END;

$table_styles_backup$  LANGUAGE plpgsql;

CREATE TRIGGER tab开发者_运维百科le_styles_backup AFTER INSERT ON table_styles

FOR EACH ROW EXECUTE PROCEDURE table_styles_backup();


Per the documentation, you don't need to explicitly test boolean data types in an IF statement - they default to test for being true so you'd use:

IF do_backup THEN
  ...
  INSERT INTO table_styles_versions (...
ELSE
  -- omit this & the ELSE keyword if nothing needs to happen if do_backup is false
END IF;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜