up vote 0 down vote favorite

trigger:

 CREATE TRIGGER "tr_update_ts" BEFORE INSERT OR UPDATE 
 ON "public"."test" FOR EACH ROW 
 EXECUTE PROCEDURE "public"."update_ts"();

and the function is:

CREATE OR REPLACE FUNCTION "public"."update_ts" () RETURNS trigger AS
$body$
DECLARE
BEGIN
  NEW.ts := now();
RETURN NEW;
END;
$body$
LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;

Why is this not working? No error thrown, but the ts is still null...

link|flag

68% accept rate

2 Answers

up vote 0 down vote accepted

I tested your code and it works:

First, let's create table:

# create table test (x int4, ts timestamptz);
CREATE TABLE

Now, Let's add function:

# CREATE OR REPLACE FUNCTION "public"."update_ts" () RETURNS trigger AS
>> $body$
>> DECLARE
>> BEGIN
>>   NEW.ts := now();
>> RETURN NEW;
>> END;
>> $body$
>> LANGUAGE 'plpgsql' VOLATILE CALLED ON NULL INPUT SECURITY INVOKER;
CREATE FUNCTION

And finally, add a trigger:

#  CREATE TRIGGER "tr_update_ts" BEFORE INSERT OR UPDATE
>>  ON "public"."test" FOR EACH ROW
>>  EXECUTE PROCEDURE "public"."update_ts"();
CREATE TRIGGER

So, now, let's test ON INSERT part of it:

# insert into test (x) values (1);
INSERT 0 1
# select * from test;
 x |              ts
---+-------------------------------
 1 | 2009-09-12 19:54:50.812139+02
(1 row)

Clearly it works.

Now, the update:

# update test set x = 2;
UPDATE 1
# select * from test;
 x |              ts
---+-------------------------------
 2 | 2009-09-12 19:54:57.463933+02
(1 row)

ts has been changed. Clearly the code you shown works, so the error must be someplace else.

Show us "\d test" output from psql, and \df+ of the trigger function.

link|flag
up vote 0 down vote

What is the full syntax of your create function? Here is the full syntax of the function that I created, and it is working as expected.

create function update_timestamp() RETURNS trigger AS $$
BEGIN
  NEW.ts := now();
RETURN NEW;
END;
$$ language plpgsql;
link|flag
i added the complete function above.. but it seems mostly the same – David Sep 12 '09 at 16:01
I compiled the code you provided for your function, and it worked as expected for me. – Steve K Sep 12 '09 at 16:20
Can you do a \d <tablename> and post that? – Steve K Sep 12 '09 at 16:21

Your Answer

 
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.