From c463fe197aa9d727de76dba35d5866a30687e3a6 Mon Sep 17 00:00:00 2001 From: Julien Rouhaud Date: Wed, 2 Dec 2026 15:22:26 +0800 Subject: [PATCH v1] Fix quadratic complexity in scan_quoted_identifier Collapsing two consecutive double quote characters is now done in place to avoid moving the remainder of the string. --- src/backend/utils/adt/varlena.c | 32 ++++++++++++++++++-------------- 1 file changed, 18 insertions(+), 14 deletions(-) diff --git a/src/backend/utils/adt/varlena.c b/src/backend/utils/adt/varlena.c index 2b03a2b621c..7225f1b6f43 100644 --- a/src/backend/utils/adt/varlena.c +++ b/src/backend/utils/adt/varlena.c @@ -2755,33 +2755,37 @@ textToQualifiedNameList(text *textval) * scan_quoted_identifier - In-place scanner for quoted identifiers. * * *nextp should point to the opening double-quote character, and will be - * updated to point just past the end. *endp is set to the position of - * the closing quote. The return value is the identifier, or NULL if the - * matching close-quote cannot be found. + * updated to point just past the closing quote. *endp is set to the position + * where the caller should null-terminate the token. The return value is the + * identifier, or NULL if the matching closing quote cannot be found. * * If we find two consecutive double quote characters, that doesn't end the * identifier: instead, we collapse them into a double quote and include them - * in the resulting token. Note that this requires overwriting the rest of the - * string in place, including the portion beyond the final value of *nextp. + * in the resulting token. This is done in place without moving the remainder + * of the string, so that scanning takes linear time. */ char * scan_quoted_identifier(char **endp, char **nextp) { char *token = *nextp + 1; + char *readp = token; + char *writep = token; for (;;) { - *endp = strchr(*nextp + 1, '"'); - if (*endp == NULL) + if (*readp == '\0') return NULL; /* mismatched quotes */ - if ((*endp)[1] != '"') - break; /* found end of quoted identifier */ - /* Collapse adjacent quotes into one quote, and look again */ - memmove(*endp, *endp + 1, strlen(*endp)); - *nextp = *endp; + if (*readp == '"') + { + if (readp[1] != '"') + break; /* found end of quoted identifier */ + /* Collapse adjacent quotes into one quote. */ + readp++; + } + *writep++ = *readp++; } - /* *endp now points at the terminating quote */ - *nextp = *endp + 1; + *endp = writep; + *nextp = readp + 1; return token; } -- 2.56.1