Created
September 11, 2024 17:02
-
-
Save guillaumeduhan/9783841d9bbd9b77e68f4a9dd9fd4aa8 to your computer and use it in GitHub Desktop.
Datamodeling part I
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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