Skip to content

Commit 1b49317

Browse files
author
Rinat Mukhtarov
committed
public. added to many functions
1 parent f851392 commit 1b49317

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

53 files changed

+588
-536
lines changed

Diff for: functions/app_progress.sql

+6-7
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
create or replace function app_progress(
1+
create or replace function public.app_progress(
22
done_percent numeric, --прогресс выполнения некого запроса
33
prefix char default '#', --символ-маркер, после которого должно быть число процентов
44
is_local bool default false --false allow pass application_name's value to subtransaction
@@ -9,6 +9,7 @@ create or replace function app_progress(
99
volatile --NOT stable!
1010
language plpgsql
1111
set search_path = ''
12+
cost 5
1213
as
1314
$$
1415
declare
@@ -25,16 +26,14 @@ end
2526
$$;
2627
2728
28-
comment on function app_progress(
29+
comment on function public.app_progress(
2930
done_percent numeric,
3031
prefix char,
3132
is_local bool
3233
) is $$
33-
Дописывает или заменяет прогресс выполнения (в процентах) в application_name.
34-
Сценарий использования.
35-
Внутри процедуры с длительным временем работы после выполнения части работы нужно вызывать функцию app_progress().
36-
Т.о. в списке процессов БД можно наблюдать вашу процедуру и отслеживать ход выполнения.
34+
Дописывает или заменяет прогресс выполнения (в процентах) "тяжёлого" запроса в application_name.
35+
Т.о. его можно наблюдать в списке процессов БД и отслеживать ход выполнения.
3736
$$;
3837
3938
--TEST
40-
--select app_progress(0), current_setting('application_name'), app_progress(1), current_setting('application_name');
39+
--select public.app_progress(0), current_setting('application_name'), public.app_progress(1), current_setting('application_name');

Diff for: functions/benchmark.sql

+25-18
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,8 @@
1-
-- PostgreSQL equivalent of MySQL's BENCHMARK() function
2-
3-
CREATE OR REPLACE FUNCTION benchmark(loop_count int, sql_expr text) returns interval
4-
volatile
1+
CREATE OR REPLACE FUNCTION public.benchmark(loop_count int, sql_expr text)
2+
returns interval
3+
volatile --!!!
54
returns null on null input -- = strict
6-
parallel unsafe -- Postgres 10 or later
5+
parallel unsafe --!!! -- Postgres 10 or later
76
security invoker
87
language plpgsql
98
set search_path = ''
@@ -20,12 +19,17 @@ BEGIN
2019
END
2120
$$;
2221

23-
comment on function benchmark(loop_count int, sql_expr text) is 'Measures the speed of expressions and functions for a given number of calls. Returns period of time.';
22+
comment on function public.benchmark(loop_count int, sql_expr text) is $$
23+
Measures the speed of expressions and functions for a given number of calls. Returns period of time.
24+
PostgreSQL equivalent of MySQL's BENCHMARK() function.
25+
$$;
2426
25-
CREATE OR REPLACE FUNCTION benchmark(timeout interval, sql_expr text) returns int
26-
volatile
27+
------------------------------------------------------------------------------------------------------------------------
28+
CREATE OR REPLACE FUNCTION public.benchmark(timeout interval, sql_expr text)
29+
returns int
30+
volatile --!!!
2731
returns null on null input -- = strict
28-
parallel unsafe -- Postgres 10 or later
32+
parallel unsafe --!!! -- Postgres 10 or later
2933
security invoker
3034
language plpgsql
3135
set search_path = ''
@@ -49,26 +53,29 @@ BEGIN
4953
END
5054
$$;
5155
52-
comment on function benchmark(timeout interval, sql_expr text) is 'Measures the speed of expressions and functions for a given period of time. Returns number of calls.';
56+
comment on function public.benchmark(timeout interval, sql_expr text) is $$
57+
Measures the speed of expressions and functions for a given period of time. Returns number of calls.
58+
$$;
5359
60+
------------------------------------------------------------------------------------------------------------------------
5461
-- TESTS
5562
do $$
5663
begin
57-
assert benchmark(1000, 'gen_random_uuid()') > '0'::interval;
58-
assert benchmark('10ms'::interval, 'gen_random_uuid()') > 0;
64+
assert public.benchmark(1000, 'gen_random_uuid()') > '0'::interval;
65+
assert public.benchmark('10ms'::interval, 'gen_random_uuid()') > 0;
5966
end;
6067
$$;
6168
6269
-- EXAMPLE 1: parse URL
63-
select benchmark(100000, $$substring(format('https://www.domain%s.com/?aaa=1111&b[2]=3#test', (random()*1000)::int::text) from '^[^:]+://([^/]+)')$$);
70+
select public.benchmark(100000, $$substring(format('https://www.domain%s.com/?aaa=1111&b[2]=3#test', (random()*1000)::int::text) from '^[^:]+://([^/]+)')$$);
6471

6572
-- EXAMPLE 2: generate UUID
66-
SELECT benchmark(100000, $$uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring)$$);
67-
SELECT benchmark(100000, $$md5(random()::text || clock_timestamp()::text)::uuid$$);
73+
SELECT public.benchmark(100000, $$uuid_in(overlay(overlay(md5(random()::text || ':' || clock_timestamp()::text) placing '4' from 13) placing to_hex(floor(random()*(11-8+1) + 8)::int)::text from 17)::cstring)$$);
74+
SELECT public.benchmark(100000, $$md5(random()::text || clock_timestamp()::text)::uuid$$);
6875

6976
-- EXAMPLE 3: benchmark generate UUID
70-
SELECT benchmark('1s'::interval, 'public.gen_random_uuid()'), public.gen_random_uuid() as guid
77+
SELECT public.benchmark('1s'::interval, 'public.gen_random_uuid()'), public.gen_random_uuid() as guid
7178
union all
72-
SELECT benchmark('1s'::interval, 'public.uuid_generate_v7()'), public.uuid_generate_v7()
79+
SELECT public.benchmark('1s'::interval, 'public.uuid_generate_v7()'), public.uuid_generate_v7()
7380
union all
74-
SELECT benchmark('1s'::interval, 'public.uuid_generate_v8()'), public.uuid_generate_v8();
81+
SELECT public.benchmark('1s'::interval, 'public.uuid_generate_v8()'), public.uuid_generate_v8();

Diff for: functions/bit/bit_get.sql

+10-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
CREATE OR REPLACE FUNCTION bit_get(num bigint, pos int)
2-
-- проверяет для числа в заданной позиции, установлен ли бит в 1
3-
RETURNS bool
1+
CREATE OR REPLACE FUNCTION public.bit_get(num bigint, pos int)
2+
returns bool
43
stable
54
returns null on null input
6-
SECURITY INVOKER
7-
PARALLEL SAFE
8-
LANGUAGE plpgsql
5+
security invoker
6+
parallel safe
7+
language plpgsql
98
set search_path = ''
109
AS $$
1110
begin
@@ -18,12 +17,14 @@ begin
1817
end
1918
$$;
2019

20+
comment on function public.bit_get(num bigint, pos int)
21+
is 'Проверяет для числа в заданной позиции, установлен ли бит в 1';
2122

2223
--TEST
2324
do $$
2425
begin
25-
assert not bit_get(7, 4);
26-
assert bit_get(8, 4);
27-
assert bit_get(13, 4);
26+
assert not public.bit_get(7, 4);
27+
assert public.bit_get(8, 4);
28+
assert public.bit_get(13, 4);
2829
end;
2930
$$;

Diff for: functions/bit/bit_set.sql

+11-9
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,10 @@
1-
CREATE OR REPLACE FUNCTION bit_set(num bigint, pos int, val boolean)
2-
-- устанавливает для числа в заданной позиции бит в 1 или 0
3-
RETURNS bigint
1+
CREATE OR REPLACE FUNCTION public.bit_set(num bigint, pos int, val boolean)
2+
returns bigint
43
stable
54
returns null on null input
6-
SECURITY INVOKER
7-
PARALLEL SAFE
8-
LANGUAGE plpgsql
5+
security invoker
6+
parallel safe
7+
language plpgsql
98
set search_path = ''
109
AS $$
1110
DECLARE
@@ -24,11 +23,14 @@ begin
2423
end
2524
$$;
2625

26+
comment on function public.bit_set(num bigint, pos int, val boolean)
27+
is 'Устанавливает для числа в заданной позиции бит в 1 или 0';
28+
2729
--TEST
2830
do $$
2931
begin
30-
assert bit_set(8, 4, false) = 0;
31-
assert bit_set(9, 4, false) = 1;
32-
assert bit_set(25, 5, false) = 9;
32+
assert public.bit_set(8, 4, false) = 0;
33+
assert public.bit_set(9, 4, false) = 1;
34+
assert public.bit_set(25, 5, false) = 9;
3335
end;
3436
$$;

Diff for: functions/column_description.sql

+4-4
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
create or replace function column_description(
1+
create or replace function public.column_description(
22
table_name regclass,
33
column_name name,
44
new_description text default null
@@ -45,7 +45,7 @@ begin
4545
end;
4646
$$;
4747

48-
comment on function column_description is 'Get or set table column description, like COMMENT ON COLUMN command, but it can set description dynamically';
48+
comment on function public.column_description is 'Get or set table column description, like COMMENT ON COLUMN command, but it can set description dynamically';
4949

5050
--TEST
5151

@@ -54,8 +54,8 @@ begin
5454
create schema if not exists test;
5555
create table test.d(i int);
5656

57-
assert column_description('test.d'::regclass, 'i') is null; --GET
58-
assert column_description('test.d'::regclass, 'i', 'col''i') = 'col''i'; --SET
57+
assert public.column_description('test.d'::regclass, 'i') is null; --GET
58+
assert public.column_description('test.d'::regclass, 'i', 'col''i') = 'col''i'; --SET
5959

6060
drop table test.d;
6161
end

Diff for: functions/crc32.sql

+7-5
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,11 @@
1-
--Adapted from https://stackoverflow.com/questions/28179335/crc32-function-with-pl-pgsql/28179336
2-
3-
--вычисляет crc32 от строки, возвращает число
4-
create or replace function crc32(t text)
1+
create or replace function public.crc32(t text)
52
returns bigint
63
immutable
74
returns null on null input
85
parallel safe
96
language plpgsql
107
set search_path = ''
8+
cost 10
119
as $$
1210
declare
1311
crc bigint default 0;
@@ -54,12 +52,14 @@ declare
5452
];
5553

5654
begin
55+
--Adapted from https://stackoverflow.com/questions/28179335/crc32-function-with-pl-pgsql/28179336
5756

5857
crc = ~crc;
5958
len = bit_length(t) / 8;
6059
bytes = decode(t, 'escape');
6160

62-
for i in 0..len-1 loop
61+
for i in 0..len - 1
62+
loop
6363
byte = (get_byte(bytes, i))::bigint;
6464
crc = (crc >> 8 & rt8_mask) # crc_table[((crc # byte) & byte_mask) + 1];
6565
end loop;
@@ -68,3 +68,5 @@ begin
6868
return crc & long_mask;
6969
end
7070
$$;
71+
72+
comment on function public.crc32(t text) is 'Вычисляет crc32 от строки';

Diff for: functions/csv_parse.sql

+10-25
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
1-
-- Parse CSV strings with PostgreSQL
2-
-- PostgreSQL умеет читать и писать CSV в файл на сервере БД. А это парсер CSV (по спецификации) из строки.
3-
create or replace function csv_parse(
1+
create or replace function public.csv_parse(
42
data text, -- данные в формате CSV
53
delimiter char(1) default ',', -- задайте символ, разделяющий столбцы в строках файла, возможные вариаты: ';', ',', E'\t' (табуляция)
64
header boolean default true -- содержит строку заголовка с именами столбцов?
75
) returns setof text[]
86
immutable
9-
strict
7+
strict -- returns null if any parameter is null
108
parallel safe -- Postgres 10 or later
119
language plpgsql
1210
set search_path = ''
11+
cost 10
1312
as
1413
$func$
15-
-- https://en.wikipedia.org/wiki/comma-separated_values
14+
-- https://en.wikipedia.org/wiki/comma-separated_values
1615
-- https://postgrespro.ru/docs/postgresql/13/sql-copy
1716
declare
1817
parse_pattern text default replace($$
@@ -25,7 +24,8 @@ declare
2524
$$, '<delimiter>', replace(delimiter, E'\t', '\t'));
2625
begin
2726
return query
28-
select * from (
27+
select *
28+
from (
2929
select
3030
(select array_agg(
3131
case when length(field) > 1 and
@@ -46,22 +46,7 @@ begin
4646
end;
4747
$func$;
4848

49-
-- TEST
50-
select
51-
CASE WHEN row[1] ~ '^\d+$' THEN row[1]::integer ELSE NULL END AS id,
52-
row[2] AS kladr_id,
53-
row[3] AS name
54-
from csv_parse($$
55-
id; kladr_id; name
56-
501 ; 8300000000000 ; ";Автономный ;"";округ""
57-
""Ненецкий"";";unknown
58-
751;8600800000000; " Автономный округ ""Ханты-Мансийский"", Район Советский" ;
59-
1755;8700300000000; Автономный округ Чукотский, Район Билибинский
60-
1725;7501900000000;Край Забайкальский, Район Петровск-Забайкальский
61-
62-
;;
63-
711;2302100000000;Край Краснодарский, Район Лабинский
64-
729;2401600000000;Край Красноярский, Район Иланский
65-
765;2700700000000;Край Хабаровский, Район Вяземский
66-
765;;
67-
$$, ';', false) as row;
49+
comment on function public.csv_parse(data text, delimiter char(1), header boolean) is $$
50+
Parse CSV strings with PostgreSQL.
51+
PostgreSQL умеет читать и писать CSV в файл на сервере БД. А это парсер CSV (по спецификации) из строки.
52+
$$;

Diff for: functions/gc_dist.sql

+12-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
create or replace function gc_dist(
1+
create or replace function public.gc_dist(
22
lat1 double precision, lon1 double precision,
33
lat2 double precision, lon2 double precision
44
) returns double precision
@@ -22,3 +22,14 @@ WHEN numeric_value_out_of_range
2222
THEN RETURN 0;
2323
END;
2424
$$;
25+
26+
27+
--TEST
28+
with t as (
29+
SELECT 37.61556 AS msk_x, 55.75222 AS msk_y, -- координаты центра Москвы
30+
30.26417 AS spb_x, 59.89444 AS spb_y, -- координаты центра Санкт-Петербурга
31+
1.609344 AS mile_to_kilometre_ratio
32+
)
33+
select (point(msk_x, msk_y) <@> point(spb_x, spb_y)) * mile_to_kilometre_ratio AS dist1_km,
34+
public.gc_dist(msk_y, msk_x, spb_y, spb_x) AS dist2_km
35+
from t;

Diff for: functions/gender_by_name/triggers/gender_0_triggers.sql

+4-2
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
-- Дать возможность в триггере для определения пола указывать пол явно
22

3-
CREATE OR REPLACE FUNCTION trigger_save_update_of() RETURNS TRIGGER
3+
CREATE OR REPLACE FUNCTION trigger_save_update_of()
4+
RETURNS TRIGGER
45
LANGUAGE plpgsql AS
56
$$
67
BEGIN
@@ -20,7 +21,8 @@ BEGIN
2021
END;
2122
$$;
2223

23-
CREATE OR REPLACE FUNCTION gender_determine() RETURNS TRIGGER
24+
CREATE OR REPLACE FUNCTION gender_determine()
25+
RETURNS TRIGGER
2426
LANGUAGE plpgsql AS
2527
$$
2628
DECLARE

Diff for: functions/grep_ip.sql

+3-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
create or replace function grep_ip(str text)
1+
create or replace function public.grep_ip(str text)
22
returns table (order_num int, "all" text, addr inet, port int, mask int)
33
stable
44
returns null on null input
@@ -30,7 +30,7 @@ as $func$
3030
and (m[7] is null or m[7]::int < 33);
3131
$func$;
3232

33-
comment on function grep_ip(str text) is $$
33+
comment on function public.grep_ip(str text) is $$
3434
Захватывает из строки все существующие IP адреса.
3535
IP адрес может иметь необязательный порт или маску.
3636
$$;
@@ -99,6 +99,6 @@ declare
9999
begin
100100
--positive and negative both
101101
assert (select json_agg(to_json(t))::text = str_out
102-
from grep_ip(str_in) as t);
102+
from public.grep_ip(str_in) as t);
103103
end;
104104
$do$;

Diff for: functions/hex_to_bigint.sql

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
-- Adapted by Rinat from https://stackoverflow.com/questions/8316164/convert-hex-in-text-representation-to-decimal-number/8316731
44

55
-- maximum length(hexval) is 32!
6-
create or replace function hex_to_bigint(hexval text)
6+
create or replace function public.hex_to_bigint(hexval text)
77
returns bigint
88
returns null on null input
99
stable
@@ -21,6 +21,6 @@ $$;
2121
-- TEST
2222
do $$
2323
begin
24-
assert hex_to_bigint(md5('test')) = -3756160627640895497; --convert MD5 to BigInt
24+
assert public.hex_to_bigint(md5('test')) = -3756160627640895497; --convert MD5 to BigInt
2525
end
2626
$$;

0 commit comments

Comments
 (0)