使用 PostgreSQL 更新只读列时引发异常
Raise exception on update of read only column with PostgreSQL
我试图在修改只读列时引发异常。为此,我在更新前使用了触发器,但出现语法错误。
DROP TRIGGER IF EXISTS check_update_guid_line ON line;
CREATE TRIGGER check_update_guid_line
BEFORE UPDATE ON line FOR EACH ROW
WHEN (OLD.guid IS DISTINCT FROM NEW.guid) THEN
RAISE EXCEPTION 'you cant modify the guid of a line');
ERROR: syntax error at or near "THEN" LINE 29: ...OLD.guid
IS DISTINCT FROM NEW.guid) THEN
我想我可以制作一个扩展代码的过程,但我想知道为什么这段代码无论如何都不起作用。
将其分为两步,如下所示:
CREATE OR REPLACE FUNCTION fn_1()
RETURNS trigger
LANGUAGE plpgsql
COST 1
AS $function$
BEGIN
IF NEW.id is distinct from OLD.id then
RAISE EXCEPTION '%','whatever it is';
END IF;
return NEW;
END;
$function$
;
CREATE TRIGGER tgr
BEFORE UPDATE ON line
FOR EACH ROW
EXECUTE PROCEDURE fn_1();
我试图在修改只读列时引发异常。为此,我在更新前使用了触发器,但出现语法错误。
DROP TRIGGER IF EXISTS check_update_guid_line ON line;
CREATE TRIGGER check_update_guid_line
BEFORE UPDATE ON line FOR EACH ROW
WHEN (OLD.guid IS DISTINCT FROM NEW.guid) THEN
RAISE EXCEPTION 'you cant modify the guid of a line');
ERROR: syntax error at or near "THEN" LINE 29: ...OLD.guid IS DISTINCT FROM NEW.guid) THEN
我想我可以制作一个扩展代码的过程,但我想知道为什么这段代码无论如何都不起作用。
将其分为两步,如下所示:
CREATE OR REPLACE FUNCTION fn_1()
RETURNS trigger
LANGUAGE plpgsql
COST 1
AS $function$
BEGIN
IF NEW.id is distinct from OLD.id then
RAISE EXCEPTION '%','whatever it is';
END IF;
return NEW;
END;
$function$
;
CREATE TRIGGER tgr
BEFORE UPDATE ON line
FOR EACH ROW
EXECUTE PROCEDURE fn_1();