Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger to create record from JSON object in PostgreSQL

Concept: a trigger what creates a new record in a table after a new JSON object has been created in another table. I don't want to make any modifications yet, just to "convert" JSON objects to records with a trigger.

like image 289
Bence László Avatar asked Oct 18 '25 04:10

Bence László


1 Answers

Use the function jsonb_populate_record() in the trigger function, e.g.

create or replace function json_input_trigger()
returns trigger language plpgsql as $$
begin
    insert into main_table
    select *
    from jsonb_populate_record(null::main_table, new.data);
    return new;
end $$;

Fully working example.

like image 147
klin Avatar answered Oct 20 '25 18:10

klin