Created
October 16, 2018 14:30
-
-
Save zukka77/c17511f3767fe7ecf020c6e0fb280913 to your computer and use it in GitHub Desktop.
function to insert a row in a table using json keys and data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE OR REPLACE FUNCTION jsoninsert(relname text, reljson json) | |
RETURNS record AS | |
$BODY$DECLARE | |
ret RECORD; | |
inputstring text; | |
BEGIN | |
SELECT string_agg(quote_ident(key),',') INTO inputstring | |
FROM json_object_keys(reljson) AS X (key); | |
EXECUTE 'INSERT INTO '|| quote_ident(relname) | |
|| '(' || inputstring || ') SELECT ' || inputstring | |
|| ' FROM json_populate_record( NULL::' || quote_ident(relname) || ' , $1) RETURNING *' | |
INTO ret USING reljson; | |
RETURN ret; | |
END; | |
$BODY$ | |
LANGUAGE plpgsql VOLATILE; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment