Last active
September 4, 2015 05:10
-
-
Save jberkus/43a74b63921aa58f90c8 to your computer and use it in GitHub Desktop.
Simple stupid function to do python-style dict string replacement.
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
-- 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