Files
mctf/dark-tariff/backend/database/sql/functions/reports.sql
T

340 lines
13 KiB
PL/PgSQL
Executable File

create or replace function billing.report_fields(p_report text) returns jsonb
language sql stable as $$
select coalesce(jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id), '[]'::jsonb)
from billing.report_field where report_types @> array[p_report]
$$;
create or replace function billing._parse_predicate_term(
p_types text[], p_vals text[], inout p_pos integer, p_mode text, p_depth integer, out p_sql text
)
language plpgsql immutable as $$
declare
v_has_not boolean := false;
v_col text;
v_col_sql text;
v_op text;
v_lit text;
v_inner text;
begin
if p_depth > 16 then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if p_pos <= coalesce(cardinality(p_types), 0) and p_types[p_pos] = 'KW' and p_vals[p_pos] = 'not' then
v_has_not := true;
p_pos := p_pos + 1;
end if;
if p_pos > coalesce(cardinality(p_types), 0) then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if p_types[p_pos] = 'LPAREN' then
p_pos := p_pos + 1;
select r.p_sql, r.p_pos into v_inner, p_pos
from billing._parse_predicate_expr(p_types, p_vals, p_pos, p_mode, p_depth + 1) r;
if p_pos > coalesce(cardinality(p_types), 0) or p_types[p_pos] <> 'RPAREN' then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
p_pos := p_pos + 1;
p_sql := '(' || v_inner || ')';
elsif p_types[p_pos] = 'BOOL' then
p_sql := p_vals[p_pos];
p_pos := p_pos + 1;
elsif p_types[p_pos] = 'IDENT' then
v_col := p_vals[p_pos];
p_pos := p_pos + 1;
if v_col in ('period', 'resource', 'tariff') then
v_col_sql := format('dimensions.%I', v_col);
elsif p_mode = 'having' and v_col = 'quantity' then
v_col_sql := $expr$sum((c.data->'calculation'->>'quantity')::numeric)$expr$;
elsif p_mode = 'having' and v_col = 'amount' then
v_col_sql := $expr$sum((c.data->'calculation'->>'amount')::numeric)$expr$;
elsif p_mode = 'having' and v_col = 'readings' then
v_col_sql := 'count(*)';
else
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if p_pos > coalesce(cardinality(p_types), 0) then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if p_types[p_pos] = 'KW' and p_vals[p_pos] = 'not' then
p_pos := p_pos + 1;
if p_pos > coalesce(cardinality(p_types), 0) or p_types[p_pos] <> 'OP'
or p_vals[p_pos] not in ('like', 'ilike') then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_op := 'not ' || p_vals[p_pos];
elsif p_types[p_pos] = 'OP' then
v_op := p_vals[p_pos];
else
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
p_pos := p_pos + 1;
if p_pos > coalesce(cardinality(p_types), 0) then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if p_types[p_pos] = 'STR' then
v_lit := quote_literal(p_vals[p_pos]);
elsif p_types[p_pos] = 'NUM' then
v_lit := p_vals[p_pos];
else
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
p_pos := p_pos + 1;
p_sql := v_col_sql || ' ' || v_op || ' ' || v_lit;
else
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
if v_has_not then
p_sql := '(not ' || p_sql || ')';
end if;
end;
$$;
create or replace function billing._parse_predicate_expr(
p_types text[], p_vals text[], inout p_pos integer, p_mode text, p_depth integer, out p_sql text
)
language plpgsql immutable as $$
declare
v_kw text;
v_rhs text;
begin
if p_depth > 16 then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
select r.p_sql, r.p_pos into p_sql, p_pos
from billing._parse_predicate_term(p_types, p_vals, p_pos, p_mode, p_depth) r;
while p_pos <= coalesce(cardinality(p_types), 0)
and p_types[p_pos] = 'KW' and p_vals[p_pos] in ('and', 'or') loop
v_kw := p_vals[p_pos];
p_pos := p_pos + 1;
select r.p_sql, r.p_pos into v_rhs, p_pos
from billing._parse_predicate_term(p_types, p_vals, p_pos, p_mode, p_depth) r;
p_sql := '(' || p_sql || ' ' || v_kw || ' ' || v_rhs || ')';
end loop;
end;
$$;
create or replace function billing.sanitize_predicate(p_expr text, p_mode text) returns text
language plpgsql immutable as $$
declare
v_len integer;
v_i integer := 1;
v_ch text;
v_two text;
v_buf text;
v_closed boolean;
v_word text;
v_num text;
v_types text[] := '{}';
v_vals text[] := '{}';
v_pos integer := 1;
v_sql text;
begin
if p_expr is null or btrim(p_expr) = '' then
return 'true';
end if;
if length(p_expr) > 1024 then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_len := length(p_expr);
while v_i <= v_len loop
v_ch := substr(p_expr, v_i, 1);
if v_ch ~ '^\s$' then
v_i := v_i + 1;
elsif v_ch = '(' then
v_types := array_append(v_types, 'LPAREN');
v_vals := array_append(v_vals, '(');
v_i := v_i + 1;
elsif v_ch = ')' then
v_types := array_append(v_types, 'RPAREN');
v_vals := array_append(v_vals, ')');
v_i := v_i + 1;
elsif v_ch = '''' then
v_i := v_i + 1;
v_buf := '';
v_closed := false;
while v_i <= v_len loop
v_ch := substr(p_expr, v_i, 1);
if v_ch = '''' then
if v_i < v_len and substr(p_expr, v_i + 1, 1) = '''' then
v_buf := v_buf || '''';
v_i := v_i + 2;
else
v_closed := true;
v_i := v_i + 1;
exit;
end if;
else
v_buf := v_buf || v_ch;
v_i := v_i + 1;
end if;
end loop;
if not v_closed then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_types := array_append(v_types, 'STR');
v_vals := array_append(v_vals, v_buf);
elsif v_i < v_len and substr(p_expr, v_i, 2) in ('<=', '>=', '<>', '!=') then
v_two := substr(p_expr, v_i, 2);
v_types := array_append(v_types, 'OP');
v_vals := array_append(v_vals, v_two);
v_i := v_i + 2;
elsif v_ch in ('=', '<', '>') then
v_types := array_append(v_types, 'OP');
v_vals := array_append(v_vals, v_ch);
v_i := v_i + 1;
elsif v_ch ~ '^[0-9]$' or (v_ch = '-' and v_i < v_len and substr(p_expr, v_i + 1, 1) ~ '^[0-9]$') then
v_num := (regexp_match(substr(p_expr, v_i), '^(-?[0-9]+(?:\.[0-9]+)?)'))[1];
if v_num is null then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_types := array_append(v_types, 'NUM');
v_vals := array_append(v_vals, v_num);
v_i := v_i + length(v_num);
elsif v_ch ~ '^[A-Za-z_]$' then
v_word := lower((regexp_match(substr(p_expr, v_i), '^([A-Za-z_][A-Za-z0-9_]*)'))[1]);
v_i := v_i + length(v_word);
if v_word in ('and', 'or', 'not') then
v_types := array_append(v_types, 'KW');
elsif v_word in ('like', 'ilike') then
v_types := array_append(v_types, 'OP');
elsif v_word in ('true', 'false') then
v_types := array_append(v_types, 'BOOL');
else
v_types := array_append(v_types, 'IDENT');
end if;
v_vals := array_append(v_vals, v_word);
else
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
end loop;
if coalesce(cardinality(v_types), 0) = 0 then
return 'true';
end if;
select r.p_sql, r.p_pos into v_sql, v_pos
from billing._parse_predicate_expr(v_types, v_vals, v_pos, p_mode, 0) r;
if v_pos <> cardinality(v_types) + 1 then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
return v_sql;
end;
$$;
create or replace function billing.sanitize_group_by(p_group_by text) returns text
language plpgsql stable as $$
declare
v_item text;
v_col text;
v_parts text[] := '{}';
begin
if p_group_by is null or btrim(p_group_by) = '' then
return 'dimensions.period, dimensions.resource, dimensions.tariff';
end if;
foreach v_item in array string_to_array(p_group_by, ',') loop
v_col := lower(btrim(v_item));
if v_col = '' or not exists (
select 1 from billing.report_field
where id = v_col and report_types @> array['finance'] and not aggregate
) then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_parts := array_append(v_parts, format('dimensions.%I', v_col));
end loop;
return array_to_string(v_parts, ', ');
end;
$$;
create or replace function billing.sanitize_sort(p_sort text) returns text
language plpgsql stable as $$
declare
v_item text;
v_norm text;
v_match text[];
v_part text;
v_parts text[] := '{}';
begin
if p_sort is null or btrim(p_sort) = '' then
return 'resource';
end if;
foreach v_item in array string_to_array(p_sort, ',') loop
v_norm := lower(btrim(v_item));
v_match := regexp_match(v_norm, '^([a-z_]+)(?:\s+(asc|desc))?(?:\s+nulls\s+(first|last))?$');
if v_match is null or not exists (
select 1 from billing.report_field
where id = v_match[1] and report_types @> array['finance']
) then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end if;
v_part := format('%I', v_match[1]);
if v_match[2] is not null then
v_part := v_part || ' ' || upper(v_match[2]);
end if;
if v_match[3] is not null then
v_part := v_part || ' NULLS ' || upper(v_match[3]);
end if;
v_parts := array_append(v_parts, v_part);
end loop;
return array_to_string(v_parts, ', ');
end;
$$;
create or replace function billing.finance_report(
p_period text, p_fields text[], p_sort text, p_group_by text, p_filter text, p_having text
) returns jsonb
language plpgsql stable as $$
declare
v_period text := coalesce(p_period, to_char(current_date, 'YYYY-MM'));
v_fields text[] := p_fields;
v_columns jsonb;
v_context text;
v_select text;
v_group text;
v_values text;
v_filter_sql text;
v_group_sql text;
v_having_sql text;
v_sort_sql text;
v_rows jsonb;
begin
if v_period !~ '^[0-9]{4}-(0[1-9]|1[0-2])$' or left(v_period, 4) = '0000' then
raise exception 'Invalid period. Use YYYY-MM.' using errcode = 'P0400';
end if;
if coalesce(cardinality(v_fields), 0) = 0 then
select array_agg(id order by position, id) into v_fields
from billing.report_field where report_types @> array['finance'];
end if;
if exists (select 1 from unnest(v_fields) field where not exists (
select 1 from billing.report_field where id = field and report_types @> array['finance']
)) then
raise exception 'Unknown financial report column.' using errcode = 'P0400';
end if;
v_filter_sql := billing.sanitize_predicate(p_filter, 'filter');
v_group_sql := billing.sanitize_group_by(p_group_by);
v_having_sql := billing.sanitize_predicate(p_having, 'having');
v_sort_sql := billing.sanitize_sort(p_sort);
select string_agg(format('%s as %I', expression, id), ', ' order by position, id)
into v_context from billing.report_field
where report_types @> array['finance'] and not aggregate;
select jsonb_agg(jsonb_build_object('id', id, 'title', title) order by position, id),
string_agg(format('%s as %I', case when aggregate then expression else format('dimensions.%I', id) end, id), ', ' order by position, id),
string_agg(format('dimensions.%I', id), ', ' order by position, id) filter (where not aggregate),
string_agg(format('report.%I', id), ', ' order by position, id)
into v_columns, v_select, v_group, v_values
from billing.report_field where id = any(v_fields) and report_types @> array['finance'];
execute format(
'select coalesce(jsonb_agg(jsonb_build_array(%s)), ''[]''::jsonb) from (
select %s from billing.receipt c join billing.reading r on r.id = c.reading_id
cross join lateral (select %s) dimensions
where to_char(r.created_at, ''YYYY-MM'') = $1 and (%s)
group by %s having (%s) order by %s
) report', v_values, v_select, v_context,
v_filter_sql,
concat_ws(', ', v_group_sql, v_group),
v_having_sql,
v_sort_sql
) into v_rows using v_period;
return jsonb_build_object('columns', v_columns, 'rows', v_rows);
exception when syntax_error_or_access_rule_violation or data_exception then
raise exception 'Invalid report expression.' using errcode = 'P0400';
end;
$$;