1
0
mirror of https://github.com/postgres/postgres.git synced 2026-01-27 21:43:08 +03:00

Get rid of O(N^2) script-parsing overhead in pgbench.

pgbench wants to record the starting line number of each command
in its scripts.  It was computing that by scanning from the script
start and counting newlines, so that O(N^2) work had to be done
for an N-command script.  In a script with 50K lines, this adds
up to about 10 seconds on my machine.

To add insult to injury, the results were subtly wrong, because
expr_scanner_offset() scanned to find the NUL that flex inserts
at the end of the current token --- and before the first yylex
call, no such NUL has been inserted.  So we ended by computing the
script's last line number not its first one.  This was visible only
in case of \gset at the start of a script, which perhaps accounts
for the lack of complaints.

To fix, steal an idea from plpgsql and track the current lexer
ending position and line count as we advance through the script.
(It's a bit simpler than plpgsql since we can't need to back up.)
Also adjust a couple of other places that were invoking scans
from script start when they didn't really need to.  I made a new
psqlscan function psql_scan_get_location() that replaces both
expr_scanner_offset() and expr_scanner_get_lineno(), since in
practice expr_scanner_get_lineno() was only being invoked to find
the line number of the current lexer end position.

Reported-by: Daniel Vérité <daniel@manitou-mail.org>
Author: Tom Lane <tgl@sss.pgh.pa.us>
Discussion: https://postgr.es/m/84a8a89e-adb8-47a9-9d34-c13f7150ee45@manitou-mail.org
This commit is contained in:
Tom Lane
2025-02-27 10:53:38 -05:00
parent e167191dc1
commit c8c74ad7e1
6 changed files with 89 additions and 55 deletions

View File

@@ -87,4 +87,7 @@ extern void psql_scan_reselect_sql_lexer(PsqlScanState state);
extern bool psql_scan_in_quote(PsqlScanState state);
extern void psql_scan_get_location(PsqlScanState state,
int *lineno, int *offset);
#endif /* PSQLSCAN_H */

View File

@@ -104,6 +104,10 @@ typedef struct PsqlScanStateData
const char *curline; /* actual flex input string for cur buf */
const char *refline; /* original data for cur buffer */
/* status for psql_scan_get_location() */
int cur_line_no; /* current line#, or 0 if no yylex done */
const char *cur_line_ptr; /* points into cur_line_no'th line in scanbuf */
/*
* All this state lives across successive input lines, until explicitly
* reset by psql_scan_reset. start_state is adopted by yylex() on entry,