[PATCH] Avoid quadratic rescans in plpgsql_location_to_lineno()

Started by Bjorn Pagen12 days ago1 messageshackers

Thread notes

1 note#performance#moderate#enhancement
hackorum-bot#performance#moderate#enhancement
hackorum-bot
2 days ago

@global #performance #moderate #enhancement

#performance#moderate#enhancement
Jump to latest
#1Bjorn 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

Attachments:

t259266_1
v1-0001-Avoid-quadratic-rescans-in-plpgsql_location_to_li.patchtext/x-patch; charset=UTF-8; name=v1-0001-Avoid-quadratic-rescans-in-plpgsql_location_to_li.patchDownload+91-7