To create an AFTER UPDATE trigger in PostgreSQL that logs the entire NEW row as JSON into a log table whenever any columns except created_date and modified_date change, follow these steps:
1. Create the Log Table
First, create a table to store the logs:
CREATE TABLE log_table (
log_id BIGSERIAL PRIMARY KEY,
modified_row_json JSONB,
log_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
2. Create the Trigger Function
This function compares the NEW and OLD rows (excluding created_date and modified_date), and logs the NEW row if changes are detected:
CREATE OR REPLACE FUNCTION log_updated_row()
RETURNS TRIGGER AS $$
BEGIN
-- Compare JSONB representations of NEW and OLD, excluding the specified columns
IF (to_jsonb(NEW) - 'created_date' - 'modified_date') IS DISTINCT FROM
(to_jsonb(OLD) - 'created_date' - 'modified_date') THEN
-- Insert the NEW row as JSONB into the log table
INSERT INTO log_table (modified_row_json)
VALUES (to_jsonb(NEW));
END IF;
RETURN NEW; -- Required for trigger functions
END;
$$ LANGUAGE plpgsql;
3. Create the Trigger
Bind the trigger to the target table (replace your_table_name with your actual table name):
CREATE TRIGGER after_update_trigger
AFTER UPDATE ON your_table_name
FOR EACH ROW
EXECUTE FUNCTION log_updated_row();
Explanation:
- Log Table: Stores the modified row as JSONB and a timestamp.
- Trigger Function:
- Converts
NEW and OLD rows to JSONB.
- Removes the
created_date and modified_date keys using - operator.
- Compares the modified JSONB objects. If they differ, the
NEW row is logged.
- Trigger: Fires after each row update on the specified table, invoking the function.
This approach efficiently checks for changes while ignoring the excluded columns and ensures only relevant updates are logged.