Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit d9aca21

Browse files
authored
comments improved
1 parent 2a19c2d commit d9aca21

File tree

1 file changed

+13
-8
lines changed

1 file changed

+13
-8
lines changed

‎functions/replace_pairs.sql‎

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,13 @@
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
1923
begin
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
3338
do $$
3439
begin
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

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /