Created
January 25, 2022 16:41
-
-
Save sscovil/137d36a023bd51e71c660d21bf015f8e to your computer and use it in GitHub Desktop.
Example of update trigger to set updated_at to current timestamp
This file contains hidden or 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
CREATE TABLE IF NOT EXISTS foobar ( | |
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), | |
created_at TIMESTAMPTZ NOT NULL DEFAULT timezone('utc', now()), | |
updated_at TIMESTAMPTZ | |
); | |
CREATE OR REPLACE FUNCTION foobar_table_but() | |
RETURNS TRIGGER | |
LANGUAGE plpgsql | |
AS ' | |
BEGIN | |
NEW.updated_at := timezone(''utc'', now()); | |
RETURN NEW; | |
END; | |
'; | |
CREATE TRIGGER foobar_table_but | |
BEFORE UPDATE ON foobar | |
FOR EACH ROW EXECUTE PROCEDURE foobar_table_but(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment