Repository navigation
Fix AST formatting roundtrip for any used as a function name with a subquery argument - #120175
Conversation
`any` is an aggregate function, and a bare `ANY` before a subquery is also
the SQL quantifier that the parser rewrites to `IN` at parse time
(ExpressionListParsers.cpp, `ParserKeyword{Keyword::ANY}` matches a BareWord
token only, never a quoted identifier). ASTFunction::formatImplWithoutAlias
printed the name through `backQuoteIfNeed`, whose force-quote list in
`writeProbablyQuotedStringImpl` holds `all` but not `any`, so a function
literally named `any` holding one subquery argument was emitted bare and its
own output read back as the quantifier: `equals(1, any(Subquery))` became
`in(1, Subquery)`.
The two spellings are different queries, so this is not only a debug-build
assertion. Measured: SELECT 1 = `any`((SELECT NULL)) returns NULL while the
formatter's output SELECT 1 = any((SELECT NULL)) returns 0, and with a
multi-row subquery the quoted form raises INCORRECT_RESULT_OF_SCALAR_SUBQUERY
where the unquoted one returns a boolean. Every text path is affected: stored
view and MV definitions, SHOW CREATE, system.tables.create_table_query, and
the query an initiator sends to shards. Under `#ifndef NDEBUG` the same
divergence aborts on the format-consistency check in executeQuery.cpp.
The query text does not have to contain a back-quote for this to happen.
`any_value` and `first_value` are registered aliases of `any`, and
FunctionNameNormalizer rewrites them to the canonical name inside the
interpreter, which is after the parse-time format-consistency check has run,
so nothing aborts even on a debug build. Measured on a debug server:
`CREATE VIEW v AS SELECT 1 = first_value((SELECT 1))`, ordinary unquoted SQL,
stored `AS SELECT 1 = any((SELECT 1))` in its metadata file, and
`system.tables.create_table_query` for that view then read back
`AS SELECT 1 IN (SELECT 1)` while the view's declared column name still said
`equals(1, any(_subquery_1))`. That is a view returning a different value
from the one its own definition asked for, in a release build, with no
back-quote typed anywhere.
`any` cannot join the force-quote list, which is why this is a formatter
predicate instead. That list is consulted for every identifier and function
name, and `any` is the only entry it would need which is a registered
function, so an entry would back-quote every `any(...)` in EXPLAIN SYNTAX and
SHOW CREATE output, in stored view/MV definitions, and the inner aggregate
name of `AggregateFunction(any, T)` type text on disk. `any` is also
perfectly safe as an identifier (`ORDER BY any`, `t.any`, `SELECT 1 AS any`,
`HAVING 1 = any` all round-trip today), so quoting it in all positions is the
wrong granularity.
The predicate keys on name plus argument shape rather than on the enclosing
comparison, so `SELECT any((SELECT 1))` is quoted as well even though the
quantifier could not have been parsed there. That is harmless: quoting a
function name never affects name resolution, so the change can only ever add
a pair of back-quotes.
The `tryGetQueryArgument()` branch is deliberately left alone. A single bare
`ASTSelectWithUnionQuery` argument is not parser-reachable for any name but
`view`/`viewIfPermitted`, and quoting there would make the text a syntax
error rather than a faithful round-trip, so that shape belongs to the JSON
boundary that can construct it.
New test 05218_any_function_subquery_quoting pins the shape, formatting
idempotency, the `RESPECT NULLS` and view-definition carriers, and the alias
carrier as an executed `CREATE VIEW` whose stored definition is then read
back through `system.tables`. `anyLast`, `any_value`, `any(number)`, the
two-argument call and `ALL` are the controls against over-quoting. The
formatter cases are formatted and not executed, because a regressed formatter
aborts a debug server on the offending shape instead of reddening one line.
Co-Authored-By: Claude Opus 5 <[email protected]>
Internal second-model review: adjudication log (click to expand)Pre-publication review by an independent model (engine: codex; 10 findings over 2 rounds, Gate B
Severity: ❌ blocker / Session id: cron:clickhouse-review-slot-9:20260915-112300 |
|
Workflow [PR], commit [0f7ac5d] Summary: ✅
AI ReviewSummaryThis PR fixes the common SQL path by forcing quotes around Findings
Final VerdictStatus: Minimum required actions:
LLVM Coverage ReportMeasured on commit 0f7ac5d.
Changed lines: Changed C/C++ lines covered: 6/6 (100.00%) · Uncovered code |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Compile time of recompiled translation units7 translation units recompiled, 9 s compile time in total, 7 of them have a recent master baseline. |
| static bool quantifierNameNeedsQuoting(const String & name, const ASTPtr & arguments) | ||
| { | ||
| return equalsCaseInsensitive(name, "any") && arguments && arguments->children.size() == 1 | ||
| && arguments->children[0]->as<ASTSubquery>(); |
There was a problem hiding this comment.
This only fixes the parser-produced ASTSubquery carrier. IAST::createFromJSON still accepts an ASTFunction named any whose sole child is a bare ASTSelectWithUnionQuery, and formatImplWithoutAlias returns via tryGetQueryArgument before it ever reaches this predicate. On that supported JSON surface (formatQueryFromJSON and dialect = clickhouse_json), the AST still serializes as bare any(SELECT ...), which a comparison re-parses as the ANY quantifier instead of the function.
If the intent is to keep the tryGetQueryArgument path unquoted, this PR still needs the matching BAD_ARGUMENTS check in readJSON for non-view / non-viewIfPermitted bare-query arguments; otherwise the round-trip contract remains broken for JSON AST input.
There was a problem hiding this comment.
Confirmed, and the mechanism is exactly as described. I built the payload by hand and measured it on a debug master build (bdd39260f887d, whose readJSON differs from today's master only by #120483's lambda check):
-- payload: parseQueryToJSON('SELECT 1 = `any`((SELECT 1))'), with the Subquery
-- wrapper replaced by its bare SelectWithUnionQuery child
formatQueryFromJSON(payload) -> SELECT 1 = any(SELECT 1)
formatQuerySingleLineOrNull('SELECT 1 = any(SELECT 1)') -> SELECT 1 IN (SELECT 1)
It reaches stored DDL too. CREATE VIEW v AS SELECT 1 = <any + bare select> submitted with dialect = clickhouse_json is accepted with no error and no debug abort, and in the next process:
create_table_query = CREATE VIEW default.v (`equals(1, any(_subquery_1))` Nullable(UInt8)) AS SELECT 1 IN (SELECT 1)
SELECT * FROM v -> Code: 47. Unknown expression identifier `equals(1, any(_subquery_1))`. (UNKNOWN_IDENTIFIER)
The readJSON gate you name is the right remedy; quoting the tryGetQueryArgument path is measurably not. With the name quoted the emitted text is unparseable, which is where every sibling name already sits: in the same payload foo, some and all all return NULL from formatQuerySingleLineOrNull (the last two are force-quoted in writeProbablyQuotedStringImpl), and the foo shape executed through the dialect gives Code: 46 UNKNOWN_FUNCTION. So any is not special at that boundary, it is only the one name whose breakage is silent instead of loud.
The gate is not any-specific either: ASTFunction::readJSON rejects a bare SelectWithUnionQuery argument only under if ((is_view || is_view_if_permitted) && arguments), so every other name passes with one. #120483, merged this morning, added only the is_lambda_function shape check there.
That is a different layer and a different entry surface from this PR, whose carrier is the parser-produced ASTSubquery shape reachable from plain SQL, and the gate covers every function name rather than any. So I am sending it as a separate PR rather than widening this one, and I will link it here.
There was a problem hiding this comment.
Yes, let's do it in a follow-up PR. I can try to review it.
There was a problem hiding this comment.
Thanks. The follow-up is in progress; I will post its link here when it opens and request you as a reviewer.
Heads-up on scope: the same check also closes three shapes the current view / viewIfPermitted gate lets through (a bare select in parameters, and a window or NULLS clause silently dropped from view(SELECT ...)), so it is a little wider than the any carrier alone.
There was a problem hiding this comment.
Opened as #120725. It adds the readJSON check at this boundary, extended past the shape asked for here: all four select query node types the AST JSON factory can build are matched, in parameters as well as arguments, and the accepted view / viewIfPermitted shape additionally rejects a window, a NULLS action and query output options on the select, each of which the formatter drops or prints unparseably.
Closes: #120256
Related: #120096 (comment)
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed formatting of a function named
anyholding a single subquery argument:SELECT 1 = `any`((SELECT 1))lost its back-quotes, and because a bareANYbefore a subquery is the SQL quantifier, that text reads back asIN. Any such query round-tripped through the formatter, such as a stored view definition orSHOW CREATE, silently changed meaning.Description
anyis an aggregate function, and before a subquery it is also theANYquantifier that the parser rewrites toIN. The formatter dropped the back-quotes, so the statement means two things across a format:SELECT 1 = `any`((SELECT NULL))returnsNULL, the formattedSELECT 1 = any((SELECT NULL))returns0. On a debug build the divergence trips the format-and-re-parse check as aLOGICAL_ERROR.No back-quote has to be typed.
any_valueandfirst_valueare registered aliases thatFunctionNameNormalizercanonicalises toanyinside the interpreter, after that check has run, so nothing is reported. Measured:CREATE VIEW v AS SELECT 1 = first_value((SELECT 1))stores= any((SELECT 1)), andsystem.tables.create_table_queryreads that view back as1 IN (SELECT 1)while its declared column name still saysequals(1, any(_subquery_1)).ParserKeyword{Keyword::ANY}matches a BareWord only, so the quoted spelling is safe. The force-quote list inwriteProbablyQuotedStringImpldoes that forall, and #120096 addssome, butanycannot join it: it is the only such name that is a registered function, so an entry would back-quote everyany(...)inEXPLAIN SYNTAX,SHOW CREATE, stored definitions andAggregateFunction(any, T)type text.Instead
ASTFunction::formatImplWithoutAliasquotes the name only when it isanywith a single subquery argument, the one shape the parser misreads. Name resolution uses the unquoted string, so the change can only add back-quotes. It keys on shape, not on the comparison context, soSELECT any((SELECT 1))is quoted too; harmless, and the test pins it. The keyword-list entry I mentioned on #120096 stays available if you prefer the uniform shape, at the cost above.New test
05218_any_function_subquery_quotingpins the shape plus theRESPECT NULLS, view-definition and alias carriers, withanyLast,any_value,any(number), the two-argument call andALLas controls; seven of its thirteen lines redden when the change is reverted.Workflow [PR]
Sync PR [sync-upstream/pr/120175]
Version info
26.10.1.34(included in26.10and later)