Created
April 4, 2020 07:04
-
-
Save mubaidr/871d347cd81e18939f4a4e3cd2e2221e to your computer and use it in GitHub Desktop.
Add timestamps columns (created_at, updated_at) and triggers (update updated_at on row update) to all user tables in postgreSQL
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
-- add timestamps (created_at, updated_at) | |
-- add trigger for timestamp updated_at | |
CREATE OR REPLACE FUNCTION add_custom_timestamps() RETURNS void AS $$ | |
DECLARE | |
row_data RECORD; | |
-- row_data information_schema.tables%ROWTYPE; | |
BEGIN | |
FOR row_data IN | |
SELECT * | |
FROM information_schema.tables | |
WHERE table_type = 'BASE TABLE' | |
AND table_schema = 'public' | |
AND table_name NOT LIKE 'pg\_%' | |
LOOP | |
EXECUTE ' ALTER TABLE ' | |
|| row_data.table_name | |
|| ' ADD COLUMN IF NOT EXISTS ' | |
|| ' created_at timestamp with time zone NOT NULL DEFAULT now(), ' | |
|| ' ADD COLUMN IF NOT EXISTS ' | |
|| ' updated_at timestamp with time zone NOT NULL DEFAULT now(); '; | |
EXECUTE ' CREATE TRIGGER update_moddatetime_' || row_data.table_name | |
|| ' BEFORE UPDATE ON ' | |
|| row_data.table_name | |
|| ' FOR EACH ROW' | |
|| ' EXECUTE PROCEDURE moddatetime(updated_at); '; | |
END LOOP; | |
END; $$ LANGUAGE PLPGSQL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment