Thread: Passing arguments to a trigger function

Passing arguments to a trigger function

From
"Harpreet Dhaliwal"
Date:
Hi,
Can anyone give me pointers for how to pass arguments to a trigger function.
I think it is done using tg_argv or something but not very sure how to do it.

Regards,
Harpreet

Re: Passing arguments to a trigger function

From
Michael Fuhr
Date:
On Tue, Aug 22, 2006 at 01:18:44PM -0400, Harpreet Dhaliwal wrote:
> Can anyone give me pointers for how to pass arguments to a trigger function.
> I think it is done using tg_argv or something but not very sure how to do
> it.

Here's an example:

CREATE TABLE foo (id integer PRIMARY KEY, t text, x integer);
CREATE TABLE bar (id integer PRIMARY KEY, t text, x integer);

CREATE FUNCTION trigfunc() RETURNS trigger AS $$
BEGIN
    NEW.t := TG_ARGV[0];
    NEW.x := TG_ARGV[1];
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER footrig BEFORE INSERT OR UPDATE ON foo
  FOR EACH ROW EXECUTE PROCEDURE trigfunc('test on foo', 123);

CREATE TRIGGER bartrig BEFORE INSERT OR UPDATE ON bar
  FOR EACH ROW EXECUTE PROCEDURE trigfunc('test on bar', 456);

INSERT INTO foo (id) VALUES (1);
SELECT * FROM foo;
 id |      t      |  x
----+-------------+-----
  1 | test on foo | 123
(1 row)

INSERT INTO bar (id) VALUES (1);
SELECT * FROM bar;
 id |      t      |  x
----+-------------+-----
  1 | test on bar | 456
(1 row)

--
Michael Fuhr