Skip to content

Instantly share code, notes, and snippets.

@jberkus
Last active September 4, 2015 05:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jberkus/43a74b63921aa58f90c8 to your computer and use it in GitHub Desktop.
Save jberkus/43a74b63921aa58f90c8 to your computer and use it in GitHub Desktop.
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