mbarish-me
mbarish-me

Reputation: 957

postgresql trigger NEW row as a json

I am writing a trigger where I need to convert NEW row into a json and insert into an other table. I am not getting it right.

     CREATE OR REPLACE FUNCTION public.eventlogs_add_user()
      RETURNS trigger AS

    $BODY$
    DECLARE newRecord JSON;
    BEGIN

    newRecord :=  row_to_json(row)
        from (NEW) row;


// Insert newRecord into another table


    RETURN NEW;
    END$BODY$
      LANGUAGE plpgsql VOLATILE
      COST 100;
    ALTER FUNCTION public.eventlogs_add_user()
      OWNER TO postgres;

    -----------------------------------------------------------

Upvotes: 10

Views: 4328

Answers (2)

Carlos Daniel Vilaseca
Carlos Daniel Vilaseca

Reputation: 318

since Trigger.NEW is already a row you should try passing it as is to row_to_json

like

row_to_json(NEW)

Upvotes: 0

Vao Tsun
Vao Tsun

Reputation: 51659

changing

newRecord :=  row_to_json(row)
        from (NEW) row;

to

newRecord :=  row_to_json(NEW.*);

should help

Upvotes: 14

Related Questions