1- -- TODO https://wiki.postgresql.org/wiki/Multi_Replace_plpgsql
2- -- TODO добавить альтернативную функцию со вторым параметром text[], чтобы передавать array['search1', 'replace1', 'search2', 'replace2', ...]
3- 4- create or replace function replace_pairs (
1+ /*
2+ TODO Добавить альтернативную функцию со вторым и третьим параметром text[], чтобы передавать
3+ array['search1', 'search2', ...],
4+ array['replace1','replace2', ...]
5+ TODO См. ещё https://wiki.postgresql.org/wiki/Multi_Replace_plpgsql
6+ Логика работы как у PHP strtr(), но реализация сложная, на ходу строится регулярное выражение
7+ */
8+ create or replace function public .replace_pairs(
59 str text ,
6- input json -- don't use jsonb type, because it reorder pairs positions!
10+ pairs json -- don't use jsonb type, because it reorder pairs positions!
711)
812 returns text
913 immutable
@@ -19,7 +23,8 @@ declare
1923begin
2024 for rec in
2125 select *
22- from json_each_text(input)
26+ from json_each_text(pairs)
27+ -- where json_typeof(pairs) = 'object' --DO NOT USE, we need raise error
2328 -- order by length(key) desc --DO NOT SORT, we need preserve pairs positions!
2429 loop
2530 str := replace(str, rec .key , rec .value );
@@ -32,11 +37,11 @@ $func$;
3237-- TEST
3338do $$
3439begin
35- assert replace_pairs(' aaabaaba' , json_build_object(
40+ assert public . replace_pairs (' aaabaaba' , json_build_object(
3641 ' aa' , 2 ,
3742 ' a' , 1
3843 )) = ' 21b2b1' ;
39- assert replace_pairs(' aaabaaba' , json_build_object(
44+ assert public . replace_pairs (' aaabaaba' , json_build_object(
4045 ' a' , 1 ,
4146 ' aa' , 2
4247 )) = ' 111b11b1' ;
0 commit comments