Re: help with plpgsql function called by trigger

From: Alban Hertroys <alban(at)magproductions(dot)nl>
To: Heather Johnson <hjohnson(at)nypost(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: help with plpgsql function called by trigger
Date: 2005-03-17 09:51:53
Message-ID: 42395339.1080708@magproductions.nl
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-admin pgsql-general

Heather Johnson wrote:
> Hello--
>
> I need to make sure that every time a row is inserted into a table
> called "users" rows are automatically inserted into two other tables:
> "join_bd" and "behavior_demographics". The inserts on join_bd and
> behavior_demographics need to create rows that are keyed to the users
> table with an integer id (called "users_id"). The join_bd row that's
> created also needs to contain a key for a record in
> behavior_demographics (bd_id). Here's what I did to try and accomplish
> this:
>
> CREATE FUNCTION insert_bd_join_bd (integer) RETURNS opaque AS '
> declare
> r RECORD;
> uid ALIAS FOR $1;
> begin
> INSERT INTO behavioral_demographics (users_id) VALUES (uid);
> SELECT INTO r bdid FROM behavioral_demographics WHERE users_id=uid;
> INSERT INTO join_bd (bd_id, users_id) VALUES (bdid, uid);
> end;
> ' LANGUAGE 'plpgsql';

Wouldn't it be nicer to put the second part of that SP in a trigger on
behavioral_demographics? That can only work if inserting into users is
the only way to insert records into behavioral_demographics, of course.

I don't know the names of your columns in behavioral_demographics, but
it would look something like this:

CREATE FUNCTION insert_bd () RETURNS trigger AS '
begin
INSERT INTO behavioral_demographics (users_id)
VALUES (NEW.users_id); -- fires trigger on bd
end;
' LANGUAGE 'plpgsql';

CREATE FUNCTION insert_join_bd () RETURNS trigger AS '
begin
INSERT INTO join_bd (bd_id, users_id)
VALUES (NEW.bd_id, NEW.users_id);
end;
' LANGUAGE 'plpgsql';

CREATE TRIGGER insert_bd_on_users
AFTER INSERT ON users
FOR EACH ROW EXECUTE PROCEDURE insert_bd();

CREATE TRIGGER insert_join_bd_on_users
AFTER INSERT ON behavioral_demographics
FOR EACH ROW EXECUTE PROCEDURE insert_join_bd();

Considering these SP's are basically simple SQL statements, the triggers
could also be implemented as a set of query rewrite rules (see CREATE
RULE). That's usually more efficient, but I don't have a lot of
experience with those...

Regards,

--
Alban Hertroys
MAG Productions

In response to

Responses

Browse pgsql-admin by date

  From Date Subject
Next Message Martin Thoma 2005-03-17 10:48:10 initdb failed with PostgreSQL 7.4
Previous Message Christopher Browne 2005-03-17 05:22:43 Re: Scheduling/Automated Jobs in Postgre

Browse pgsql-general by date

  From Date Subject
Next Message Richard Huxton 2005-03-17 10:03:54 Re: Query performance problem
Previous Message Együd Csaba (Freemail) 2005-03-17 09:47:41 Re: Best practices: Handling Daylight-saving time