触发器不允许我在 PostgreSQL 中删除
我正在尝试捕获表上的数据更改,并在插入或更新之后以及更新或删除之前执行以下触发函数:
CREATE OR REPLACE FUNCTION cdc_test_function()
RETURNS trigger AS
$BODY$
DECLARE op cdc_operation_enum;
BEGIN
op = TG_OP;
IF (TG_WHEN = 'BEFORE') THEN
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_BEFORE';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, OLD.*);
ELSE
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_AFTER';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, NEW.*);
END IF;
RETURN NEW;
END;
我的更改表(CDC_TEST)正在正确捕获所有内容,并且我可以在中很好地插入和更新记录我的测试表。但是,当我尝试 DELETE 时,它会在 CDC_TEST 中完美记录 DELETE 条目,但该记录仍保留在我的 TEST 表中。如果我禁用触发器,那么我可以从 TEST 中删除。这是我用来创建表的代码以及枚举的代码:
CREATE TABLE test
(
test_id serial NOT NULL,
value text NOT NULL,
CONSTRAINT test_pkey PRIMARY KEY (test_id )
)
CREATE TABLE cdc_test
(
cdc_test_id bigserial NOT NULL,
cdc_timestamp timestamp with time zone DEFAULT now(),
cdc_opeation cdc_operation_enum,
cdc_user name DEFAULT "current_user"(),
cdc_transaction_id bigint DEFAULT txid_current(),
test_id integer,
value text,
CONSTRAINT cdc_test_pkey PRIMARY KEY (cdc_test_id )
)
CREATE TYPE cdc_operation_enum AS ENUM( 'DELETE', 'INSERT', 'UPDATE_BEFORE', 'UPDATE_AFTER', 'UPDATE' );
I am trying to capture data changes on a table and am executing the following trigger function AFTER INSERT OR UPDATE as well as BEFORE UPDATE OR DELETE:
CREATE OR REPLACE FUNCTION cdc_test_function()
RETURNS trigger AS
$BODY$
DECLARE op cdc_operation_enum;
BEGIN
op = TG_OP;
IF (TG_WHEN = 'BEFORE') THEN
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_BEFORE';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, OLD.*);
ELSE
IF (TG_OP = 'UPDATE') THEN
op = 'UPDATE_AFTER';
END IF;
INSERT INTO cdc_test VALUES (DEFAULT, DEFAULT, op, DEFAULT, DEFAULT, NEW.*);
END IF;
RETURN NEW;
END;
My change table (CDC_TEST) is capturing everything properly and I can both INSERT and UPDATE records just fine in my TEST table. However, when I try to DELETE, it records the DELETE entry perfectly in CDC_TEST, but the record remains in my TEST table. If I disable the trigger, then I can DELETE from TEST just fine. Here is the code I used to create my tables as well as the code for my enum:
CREATE TABLE test
(
test_id serial NOT NULL,
value text NOT NULL,
CONSTRAINT test_pkey PRIMARY KEY (test_id )
)
CREATE TABLE cdc_test
(
cdc_test_id bigserial NOT NULL,
cdc_timestamp timestamp with time zone DEFAULT now(),
cdc_opeation cdc_operation_enum,
cdc_user name DEFAULT "current_user"(),
cdc_transaction_id bigint DEFAULT txid_current(),
test_id integer,
value text,
CONSTRAINT cdc_test_pkey PRIMARY KEY (cdc_test_id )
)
CREATE TYPE cdc_operation_enum AS ENUM( 'DELETE', 'INSERT', 'UPDATE_BEFORE', 'UPDATE_AFTER', 'UPDATE' );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当触发器运行时进行删除,返回
OLD
;运行触发器时,返回NEW
进行更新。Return
OLD
when the trigger runs for a deletion,NEW
for an update.