0

I have very simple trigger and trigger function. Trigger function should insert GUID in every row after insert operation.

SQL:

CREATE TABLE "USERS"
(
  id integer,
  guid uuid,
  name text
)

Trigger function:

CREATE OR REPLACE FUNCTION insertGUID() RETURNS trigger AS
$BODY$BEGIN
    INSERT INTO "USERS" ("guid") VALUES (md5(random()::text || clock_timestamp()::text)::uuid);
END$BODY$
LANGUAGE plpgsql;

Trigger:

CREATE TRIGGER example_trigger BEFORE INSERT ON "USERS" EXECUTE PROCEDURE insertGUID();

But after after every insert. Like:

INSERT INTO "USERS"(name)  VALUES ('foo1');

I am getting error: max_stack_depth

CONTEXT: SQL: "INSERT INTO "USERS" ("Joe") VALUES (md5(random()::text || clock_timestamp()::text)::uuid)"

UPD: I am getting same problem even if I use BEFORE INSERT

1 Answer 1

1

Your insert fires the trigger which inserts a new row, which then fires the trigger, which inserts a new row, which fires the trigger, which inserts a new row, which fires the trigger which inserts a new row.... (you get the picture).

You want to change the new row, not insert a new one. So your trigger function needs to be like this:

CREATE OR REPLACE FUNCTION insertGUID() 
  RETURNS trigger AS
$BODY$BEGIN
    new.guid := md5(random()::text || clock_timestamp()::text;
    return new;
END$BODY$
LANGUAGE plpgsql;

For this to work the trigger itself has to be defined as before insert.

CREATE TRIGGER example_trigger 
    BEFORE INSERT ON "USERS" EXECUTE PROCEDURE insertGUID();

Unrelated, but: you should really avoid quoted identifiers ("USERS"). They are much more trouble than they are worth it

Sign up to request clarification or add additional context in comments.

8 Comments

Strange, but it's look like it's work same even with BEFORE snag.gy/hyth5.jpg
but on my screenshot is before. Or am wrong? I will try check all again
@user1432751: I have no idea what that screen shot is supposed to show me. The problem with the endless recursion has nothing to do whether it's a before or after trigger. But changing the column value will only work in a before trigger.
I checked all my code. I am getting same error even if I use BEFORE INSERT.
@user1432751 Again: did you remove (replace) the insert statement from the trigger function?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.