From: Ian Meyer <ianmmeyer@gmail.com>
To: pgsql-sql@postgresql.org
Subject: Re: Problem with function and trigger...
Date: Wed, 28 Sep 2005 15:46:07 -0400
Message-ID: <b54105080509281246297684b5@mail.gmail.com> (raw)
In-Reply-To: <7747.1127929968@sss.pgh.pa.us>
References: <b541050805092810357cac86c0@mail.gmail.com>
<7747.1127929968@sss.pgh.pa.us>
On 9/28/05, Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Ian Meyer <ianmmeyer@gmail.com> writes:
> > IF TG_OP = 'DELETE' AND OLD.deleted = FALSE THEN
>
> > ERROR: record "old" is not assigned yet
> > DETAIL: The tuple structure of a not-yet-assigned record is indeterminate.
> > CONTEXT: PL/pgSQL function "thread_sync" line 2 at if
>
> > What am I failing to understand with this?
>
> We don't guarantee short-circuit evaluation of boolean expressions.
> You'll have to break that into two IFs, ie,
>
> IF TG_OP = 'DELETE' THEN
> IF ... test on OLD.something ...
>
> regards, tom lane
>
Ah ha.. that makes sense. I fixed it to be:
CREATE OR REPLACE FUNCTION thread_sync() RETURNS trigger AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
UPDATE member SET total_threads=total_threads-1 WHERE id=OLD.member_id;
RETURN OLD;
ELSEIF TG_OP = 'INSERT' THEN
UPDATE member SET total_threads=total_threads+1 WHERE id=NEW.member_id;
RETURN NEW;
ELSEIF TG_OP = 'UPDATE' THEN
IF NEW.deleted != OLD.deleted THEN
IF NEW.deleted = TRUE THEN
UPDATE member SET total_threads=total_threads-1 WHERE id=NEW.member_id;
RETURN NEW;
ELSEIF NEW.deleted = FALSE then
UPDATE member SET total_threads=total_threads+1 WHERE id=NEW.member_id;
RETURN NEW;
END IF;
RETURN NULL;
END IF;
RETURN NULL;
END IF;
END;
$$ LANGUAGE plpgsql;
Here's my next question(s)... If i have 2 rows in the thread table and
I delete 1 of the rows with: delete from thread where id=26; it ends
up decrementing the total_threads value by 2, instead of one.
bcodev=> select id, total_threads from member;
id | total_threads
----+---------------
1 | 2
(1 row)
bcodev=> delete from thread where id=37;
DELETE 1
bcodev=> select id, total_threads from member;
id | total_threads
----+---------------
1 | 0
(1 row)
I'm confused, to say the least.
Thanks for all the help.
Ian
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: ianmmeyer@gmail.com
Subject: Re: Problem with function and trigger...
In-Reply-To: <b54105080509281246297684b5@mail.gmail.com>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox