I have a function that does an insert in a parent table then inserts into a child table. The last parameter is an array of variable length. I use this to do the insert into the child table by sending an array of comma delimited pairs and parsing these out.
create or replace function neil_test(time_stamp timestamp with time zone, type_id text, raw_message text,field_values text[])
returns void
AS $$
DECLARE
last_message_id bigint;
x text;
BEGIN
INSERT INTO message(time_stamp,type_id,raw_message) values(time_stamp,type_id,raw_message);
select into last_message_id currval(pg_get_serial_sequence('message', 'id'));
foreach x in ARRAY field_values
LOOP
insert into message_field_value(last_message_id,field_id,fieldValue) select left(x,strpos(x,',')-1), right(x,length(x)-strpos(x,','));
END LOOP;
END
$$LANGUAGE plpgsql
It's called like this:
select neil_test('2001-01-01 08:00:00.1234','F','RAW',ARRAY['One,value1','two,value2','three,value3'])
This works OK but what I'd really like to do is use the array directly. Something like :
select neil_test('2001-01-01 08:00:00.1234','F',
'RAW',ARRAY[['One', 'value1'],['two','value2'],['three','value3']])
...
insert into message_field_value(last_message_id,fieldid, field value)
select field_values[1], field_values[2]
I've tried the unnest function but this doesn't work as it seems to flatten out the whole array and I lose the pairs. Is something like this even possible with Postgres arrays?