Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Simple stupid function to do python-style dict string replacement.
-- function for doing dictionary-style replacement of varaibles
-- in a SQL string. variables are marked in the text with ${var}
-- and replaced using a json dictionary
create or replace function replace_vars ( somestring text,
vars JSON )
returns text
language plpgsql
immutable
as
$f$
DECLARE newstring TEXT;
varname TEXT;
varval TEXT;
BEGIN
newstring := somestring;
FOR varname, varval IN
SELECT key, value FROM json_each_text(vars)
ORDER BY length(key) DESC, key
LOOP
newstring := replace(newstring, format('${%s}',varname), varval);
END LOOP;
RETURN newstring;
END;
$f$;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.