Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Create Posts “2023-01-19-postgres-dynamic-triggers-for-keeping-updated_at/index” #19

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
---
layout: post
visibility: public
title: "Postgres: dynamic triggers for keeping updated_at"
date: 2023-01-19T21:23:13.278Z
---
```
CREATE OR REPLACE FUNCTION public.set_updated_at_now ()
RETURNS TRIGGER
AS $body$
DECLARE
_q_txt text;
BEGIN
NEW.updated_at = NOW();
RETURN NEW;
END;
$body$
LANGUAGE plpgsql
SECURITY DEFINER SET search_path = pg_catalog, public;

CREATE OR REPLACE FUNCTION public.track_updated_at (target_table regclass)
RETURNS void
AS $body$
DECLARE
_q_txt text;
BEGIN
EXECUTE 'drop trigger if exists track_updated_at on ' || target_table;
_q_txt = 'create trigger track_updated_at before update on ' || target_table || ' for each row execute procedure public.set_updated_at_now();';
RAISE NOTICE '%', _q_txt;
EXECUTE _q_txt;
END;
$body$
LANGUAGE 'plpgsql';

COMMENT ON FUNCTION public.track_updated_at (regclass) IS $body$
Set an automated trigger to set updated_at whenever UPDATE is called on a row in target_table.

Arguments:
target_table: Table name, schema qualified if not on search_path
$body$;
```

Then use with

```
SELECT
track_updated_at ('api_keys');
```