I am trying to write a Postgres trigger to unnest an array field before inserting or updating a new row. E.g.
SELECT
unnest(something)
FROM NEW
However, this seems to lead to an error:
relation 'new' does not exist
How can I use the NEW row inside of the trigger function, in such a way that allows me to unnest an array field for further processing?
CREATE TABLE statements
Below are examples of the table structures:
CREATE TABLE parent_table (
id uuid NOT NULL,
jsonb_array_field jsonb[] NOT NULL DEFAULT '{}'::jsonb[],
CONSTRAINT "parent_table_pkey" PRIMARY KEY (id),
);
CREATE TABLE many_to_one_table (
id serial primary key,
parent_table_id uuid references parent_table(id),
subfield_a text,
subfield_a text
);
TRIGGER function
Here is the essence of the TRIGGER function:
CREATE OR REPLACE FUNCTION unnest_and_normalize_json() RETURNS TRIGGER AS
$body$
begin
if NEW.jsonb_array_field is null then
raise exception 'jsonb_array_field is null';
else
insert into
many_to_one_table(subfield_a, subfield_b)
select
parent_table_id, -- this is to be the ForeignKey
json_data->>'subfieldA' as subfield_a,
json_data->>'subfieldB' as subfield_b
from (
select
id, -- need ID for ForeignKey relationship
unnest(jsonb_array_field) as json_data
from new
) as unnested_json;
end if;
RETURN new;
end;
$body$
LANGUAGE plpgsql;
TRIGGER statement
The trigger statement can be run either before or after INSERT and UPDATE, so long as the data are mirrored in the 'migration' table.
CREATE TRIGGER unnest_and_normalize_json_on_insert AFTER INSERT ON parent_table
FOR EACH ROW EXECUTE PROCEDURE unnest_and_normalize_json();
CREATE TRIGGER unnest_and_normalize_json_on_update AFTER UPDATE ON parent_table
FOR EACH ROW EXECUTE PROCEDURE unnest_and_normalize_json();
ForeignKey clarification
We are trying to transition this part of our data model to use a ForeignKey relationship rather than JSON field. The trigger is intended as a temporary step to ensure the normalized_table has data going forward, while we backfill/migrate data from older records.
CREATE TABLEstatement and the whole trigger code.jsonb[]almost never makes sense. It's much better to usejsonband store a proper JSON array inside the json value