Created
August 24, 2020 02:22
-
-
Save sgoley/5fdadc20ae32e191bf1f8db172d002dd to your computer and use it in GitHub Desktop.
easiest way to manage both "created" and "updated" timestamps on a record in postgesql
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
-- in schema as procedure: | |
create function manage_magic_timestamp_columns() returns trigger | |
strict | |
cost 1 | |
language plpgsql | |
as | |
$$ | |
BEGIN | |
-- is a new record? | |
IF TG_OP = 'INSERT' THEN | |
-- yes, set created at | |
NEW.created_at = current_timestamp; | |
END IF; | |
-- bump updated at column | |
NEW.updated_at = current_timestamp; | |
-- all done | |
RETURN NEW; | |
END; | |
$$; | |
comment on function manage_magic_timestamp_columns() is 'Manage magic timestamp columns'; | |
alter function manage_magic_timestamp_columns() owner to --your username here--; | |
-- on table: | |
-- Trigger: table_magic_ts_tr | |
-- DROP TRIGGER table_magic_ts_tr ON public.table; | |
CREATE TRIGGER table_magic_ts_tr | |
BEFORE INSERT OR UPDATE | |
ON public.table | |
FOR EACH ROW | |
EXECUTE PROCEDURE public.manage_magic_timestamp_columns(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment