0

I am trying to write a trigger in which I have to create a Json after getting data(multiple rows) from another table. I have two table task and data. data table contains multiple information about the task in key/value pair.

 task schema
 taskid
 description 
 value

data table schema

  id
  taskid
  key
  value

Now in trigger I want to fetch all data corresponding to a task and prepare a JSON from that. I am using below

 CREATE OR REPLACE FUNCTION event()
  RETURNS trigger AS
     $BODY$

        DECLARE
         _message json; 
         _data data;

         BEGIN

         SELECT * INTO _data FROM data WHERE data.taskid = New.taskid;
          IF      TG_OP = 'INSERT' THEN
                          _messag:=json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);

          END IF;


       INSERT INTO events(message)
       VALUES(_messag);

       RETURN NULL;
       END;

        $BODY$
LANGUAGE plpgsql VOLATILE

Here, I am using below query to get all data from data table corresponding to a taskid

SELECT * INTO _data FROM data WHERE data.taskid = New.taskid;

Here, the problem is that I am getting only one row. How can all rows will be fetched? If anyone has any idea?

1
  • I have to get all the data from the table corresponding to a task. I tried jsonb_agg(to_jsonb(data)) ; but it is not working. Commented Apr 14, 2020 at 12:33

2 Answers 2

0

You can aggregate everything into a single JSON value:

declare
...
  _data jsonb; --<< change the data type to jsonb
begin
...
IF TG_OP = 'INSERT' THEN
  -- only select everything if you really need it
  SELECT jsonb_agg(to_jsonb(data)) 
    INTO _data 
  FROM data 
  WHERE data.taskid = New.taskid;

  _message := json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);
END IF;
...
Sign up to request clarification or add additional context in comments.

Comments

0

It works for me:

CREATE OR REPLACE FUNCTION event()
 RETURNS trigger AS
 $BODY$

    DECLARE
    _message json; 
    _data jsonb;

     BEGIN

   *****SELECT json_agg(tmp)  
    INTO _data
  FROM (
    -- Your subquery goes here, for example:
    SELECT data.key, data.value
    FROM.data
    WHERE data.taskid = New.taskid
    ) tmp;*****

      IF      TG_OP = 'INSERT' THEN
                      _messag:=json_build_object('taskId',NEW.taskid,'description',NEW.description,'value',NEW.value,'clientis',_data);

      END IF;

   INSERT INTO events(message)
   VALUES(_messag);

   RETURN NULL;
   END;

    $BODY$
  LANGUAGE plpgsql VOLATILE 

Research link: select statement in postgres function called inside a trigger

Comments

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.