Skip to content

Instantly share code, notes, and snippets.

@guillaumeduhan
Created September 11, 2024 17:02
Show Gist options
  • Save guillaumeduhan/9783841d9bbd9b77e68f4a9dd9fd4aa8 to your computer and use it in GitHub Desktop.
Save guillaumeduhan/9783841d9bbd9b77e68f4a9dd9fd4aa8 to your computer and use it in GitHub Desktop.
Datamodeling part I
-- 1. create the function
CREATE OR REPLACE FUNCTION log_post_update()
RETURNS TRIGGER AS $$
BEGIN
NEW.updated_at = NOW();
IF NEW.title <> OLD.title THEN
INSERT INTO posts_logs (post_id, log_message)
VALUES (NEW.id, 'Updated title');
ELSEIF NEW.description <> OLD.description THEN
INSERT INTO posts_logs (post_id, log_message)
VALUES (NEW.id, 'Updated description');
END IF;
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
-- 2. create the trigger that is calling our function
CREATE TRIGGER post_update_trigger
AFTER UPDATE ON posts
FOR EACH ROW
EXECUTE FUNCTION log_post_update();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment