Question

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' );
Was it helpful?

Solution

Return OLD when the trigger runs for a deletion, NEW for an update.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top