This question relates to Update dynamic column names using keys from jsonb argument and my code is based on the answer provided there by https://dba.stackexchange.com/users/3684/erwin-brandstetter
I'm trying to write a generic function that inserts data into a table with multiple data types from a jsonb record. How can I dynamically cast each value to the data type for the respective column?
I'm using PostgreSQL version 15.2
A typical call to this function would be:
json_data = '{
"text_field": "Some text",
"numeric_field": 17,
"datetime_field": "2023-04-24 11:06:50.36758-04",
"boolean_field": true
}'
SELECT * FROM insert_jsonb('schema_name', 'table_name', json_data);
My function:
CREATE OR REPLACE FUNCTION insert_from_jsonb(
sch_name text,
tbl_name text,
js jsonb,
out new_id uuid;
) AS
$func$
DECLARE
_sql text;
BEGIN
SELECT INTO _sql
'INSERT INTO ' || sch_name || '.' || tbl_name || ' ('
|| string_agg(format('%I', key), ', ') || ') VALUES ('
|| string_agg(format('%L', value), ', ') || ')' -- < how can I cast each value?
|| ' RETURNING uuid'
FROM jsonb_each_text(js);
IF _sql IS NOT NULL THEN
-- RAISE NOTICE '%', _sql; -- uncomment for debugging
EXECUTE _sql INTO new_id; -- comment out for debugging
END IF;
END
$func$ LANGUAGE plpgsql ;