Last active
June 14, 2025 13:01
-
-
Save carl0smat3us/f9ec4c2d6628c8ab83ebcb4c5542457e to your computer and use it in GitHub Desktop.
Create a trigger to update the updated_at field for every table that has it.
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
| SET TIME ZONE 'America/New_York'; | |
| create extension if not exists moddatetime schema extensions; | |
| DO $$ | |
| DECLARE | |
| r RECORD; | |
| trigger_name text; | |
| BEGIN | |
| FOR r IN | |
| SELECT table_schema, table_name | |
| FROM information_schema.columns | |
| WHERE column_name = 'updated_at' | |
| AND table_schema = 'public' | |
| LOOP | |
| trigger_name := format('handle_updated_at_%s', lower(r.table_name)); | |
| BEGIN | |
| EXECUTE format(' | |
| CREATE TRIGGER %I | |
| BEFORE UPDATE ON %I.%I | |
| FOR EACH ROW | |
| EXECUTE FUNCTION moddatetime(''updated_at'')', | |
| trigger_name, r.table_schema, r.table_name); | |
| EXCEPTION | |
| WHEN duplicate_object THEN | |
| END; | |
| END LOOP; | |
| END; | |
| $$; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment