[PATCH] Avoid quadratic rescans in plpgsql_location_to_lineno()

Поиск
Список
Период
Сортировка
Искать

[PATCH] Avoid quadratic rescans in plpgsql_location_to_lineno()

От:
Bjorn Pagen <hello@bjornpagen.com>
Дата:
Вложения:
Hi,

Compiling a PL/pgSQL function is quadratic in the number of IF, ELSIF
and CASE WHEN statements it has. The grammar asks for their line
numbers only after parsing their bodies, so the location goes
backwards, and plpgsql_location_to_lineno() then rescans the source
from the start.

A CASE with 40000 WHEN arms takes about 15 s to compile here, both at
CREATE FUNCTION and at the first call in each session:

SET check_function_bodies = on;
\timing on
SELECT format('CREATE FUNCTION f(k int) RETURNS int LANGUAGE plpgsql AS %L',
E'BEGIN\n CASE k\n'
|| string_agg(format(E' WHEN %s THEN\n RETURN %s;', i, i), E'\n')
|| E'\n END CASE;\nEND')
FROM generate_series(1, 40000) i \gexec

The attached patch walks the current line back instead, which brings
that down to about 80 ms. It also adds a test of the reported line
numbers, since nothing in the regression tests checks an error at an
IF.

We ran into this with generated trigger functions.

Thanks,
Bjorn Pagen
FAQ