Re: Does trigger only accept functions?

From: Adrian Klaver <adrian(dot)klaver(at)aklaver(dot)com>
To: veem v <veema0000(at)gmail(dot)com>, depesz(at)depesz(dot)com
Cc: pgsql-general <pgsql-general(at)lists(dot)postgresql(dot)org>
Subject: Re: Does trigger only accept functions?
Date: 2024-06-11 19:46:24
Message-ID: 7169c618-3975-4149-b3a5-00b26aef4268@aklaver.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 6/11/24 12:20, veem v wrote:
>
>
> On Wed, 12 Jun 2024 at 00:26, hubert depesz lubaczewski
> <depesz(at)depesz(dot)com <mailto:depesz(at)depesz(dot)com>> wrote:
>
>
>
> No, I meant building dynamic queries and then EXECUTE-ing, like docs
> show:
> https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN <https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN>
>
> Best regards,
>
> depesz
>
>
> My apology, if interpreting it wrong way. It doesn't make much
> difference though, but do you mean something like below?
>
> CREATE OR REPLACE FUNCTION log_deletes()
> RETURNS TRIGGER AS $$
> DECLARE
>     audit_table_name TEXT;
>     audit_query TEXT;
> BEGIN
>     IF TG_TABLE_NAME = 'source_table1' THEN
>         audit_table_name := 'delete_audit1';
>         audit_query := 'INSERT INTO ' || audit_table_name || '
> (record_id, delete_timestamp, col1, col2, col3) VALUES ( $2, $3, $4)';
>         EXECUTE audit_query USING OLD.id, OLD.col1, OLD.col2, OLD.col3;
>     ELSIF TG_TABLE_NAME = 'source_table2' THEN
>         audit_table_name := 'delete_audit2';
>         audit_query := 'INSERT INTO ' || audit_table_name || ' ( col4,
> col5, col6) VALUES ( $2, $3, $4)';
>         EXECUTE audit_query USING OLD.id, OLD.col4, OLD.col5, OLD.col6;
>
>     ELSE
>         RAISE EXCEPTION 'Audit table not defined for %', TG_TABLE_NAME;
>     END IF;
>
>     RETURN OLD;
> END;
> $$ LANGUAGE plpgsql;

I'm guessing depesz meant using TG_TABLE_NAME to pull column information
from:

https://www.postgresql.org/docs/current/catalog-pg-attribute.html

and use that to build the INSERT query. The issue with dynamic or a
fixed SQL is going to be with audit_query, in particular
audit_table_name := 'delete_audit2. If your source tables change, add or
delete columns or column types change, your audit table will need to
change to match.

One possible solution is something I outlined here:

https://aklaver.org/wordpress/2021/12/07/postgres-and-json/

Other folks have done similar things, you can search on

postgresql audit tables using json

for alternatives.

--
Adrian Klaver
adrian(dot)klaver(at)aklaver(dot)com

In response to

Browse pgsql-general by date

  From Date Subject
Next Message hubert depesz lubaczewski 2024-06-11 19:58:43 Re: Does trigger only accept functions?
Previous Message veem v 2024-06-11 19:20:27 Re: Does trigger only accept functions?