You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Allow Identifier query parameters to name a parameterized view - #124023
Closes#105037. Finishes #112877, which was closed without merge.
Why
A parameterized view is queried like a table function, and the client docs say Identifier parameters are for database, table and function names. So SELECT * FROM {view:Identifier}(id = 1) is what you write when the view is picked at runtime. It fails. ParserFunctionName rejects a query parameter in function-name position, the table expression never parses, and the error surfaces as UNKNOWN_FUNCTION on releases and SYNTAX_ERROR on master. Argument names and values can already be parameters, the view name could not.
We hit this while building a lineage dump that probes every view in a catalog with LIMIT 0. The workaround is to run the view's stored SELECT instead of naming the view.
What
The function-name parser gets a flag that permits a parameterized name, and only the table-expression parser sets it. Scalar function names keep rejecting query parameters, which is what #106635 introduced to stop a formatting logical error. The unresolved name stays on ASTFunction::query_parameter_name until ReplaceQueryParameterVisitor resolves it, and the visitor resolves it only on ASTTableExpression::table_function, including the table expression of DESCRIBE TABLE. Formatting, column naming, clone and the AST JSON round trip print the placeholder while the name is unknown.
A clickhouse_json AST can put such a name on a scalar function, which the SQL parser never does. IAST::createFromJSON walks the tree once after deserialization and rejects query_parameter_name anywhere but on the table function of a table expression with BAD_ARGUMENTS, so both the dialect and formatQueryFromJSON refuse the document before it is formatted or run. The visitor keeps the same check as an invariant.
The placeholder goes through the ordinary function-call grammar, so after substitution it names a parameterized view or a table function that takes ordinary arguments. Anything decided before substitution is out of reach. The bare SELECT argument grammar of view, viewIfPermitted and eval is one such thing: {f:Identifier}(SELECT 1) is a syntax error, and {f:Identifier}((SELECT 1)) with f = 'view' fails with BAD_ARGUMENTS from the table function, while eval('SELECT 1') works through a placeholder. Inline insert data for input is another, since the insert parser and the client look for input before substitution. The docs say so.
A stored parameterized view keeps the placeholder with an empty function name, and the secret-argument finder keys on that name, so SHOW CREATE and system.tables would print the arguments in clear with secret display off. The formatter now masks every argument of an unresolved table function and hasSecretParts reports it, since the function may take a password.
The visitor recomputes isCompoundName() from the substituted string. A single {view:Identifier} holding db.pv is one identifier part at parse time, but the legacy execution path and the EXPLAIN SYNTAX expansion split on that flag to find the database. The review of #112877 caught this.
The query-parameter section of docs/reference/syntax.mdx said an Identifier parameter can name a function. It now lists database, table, column and other identifiers, shows the parameterized view call, and names the unsupported cases.
Compared with #112877: rebased onto master. The qualified-name test is a shell test on the per-test database, so it is safe under parallel and flaky-check runs. It also covers {db:Identifier}.{name:Identifier}(...) and a call where the name, the argument name and the value are all parameters. The EXPLAIN SYNTAX assertion that failed Fast test compared against WHERE id = 1, but explain renders equals(id, _CAST(1, 'UInt64')), so the test records the explain output itself, as 04105_explain_syntax_parameterized_view does.
You can now pass the name of a parameterized view, or of a table function with ordinary arguments, as an Identifier query parameter in a table expression, for example SELECT * FROM {view:Identifier}(id = {id:UInt64}), the same way you already can for tables. Scalar function names remain unsupported, as does the bare SELECT argument grammar of view, viewIfPermitted and eval, while eval('SELECT 1') works. Tooling that picks a view at runtime no longer has to build the query text itself.
Parameterized views are queried like table functions, and Identifier
parameters are documented for database, table and function names, but
ParserFunctionName rejected a query parameter in function-name position,
so SELECT * FROM {view:Identifier}(id = 1) failed with UNKNOWN_FUNCTION.
Keep the unresolved name on ASTFunction::query_parameter_name for the
function-like table expression only, resolve it in
ReplaceQueryParameterVisitor, and recompute isCompoundName() from the
substituted value so a single parameter holding db.view is split on both
the legacy execution path and the EXPLAIN SYNTAX expansion. Ordinary
scalar function names still reject query parameters.
Based on ClickHouse#112877. ClosesClickHouse#105037.
This PR allows Identifier query parameters to name parameterized views and ordinary table functions in table expressions, preserves unresolved names through AST operations, and masks their potentially secret arguments. The main regression has focused coverage: both new tests, 05325_parameterized_view_name_query_parameter and 05326_parameterized_view_qualified_name_query_parameter, pass in the Fast test report for f7b4a5e268c37cce815f8f9edcad777a25314814. One JSON validation issue remains.
Consumers traced for the new unresolved AST form:
ReplaceQueryParameterVisitor, stored-view parameter discovery, and StorageView expansion: preserve deferred names and substitute them before analysis.
ASTFunction formatting, column naming, cloning, hashing, and JSON serialization: carry the placeholder; metadata formatting masks unresolved arguments.
ClientBase query rewriting, table-function analysis, DESCRIBE, and EXPLAIN SYNTAX: use the substituted name. Early input detection and special argument grammars have documented exclusions.
IAST::createFromJSON, formatQueryFromJSON, and the clickhouse_json execution path: share the incomplete placement validation described below.
Findings
⚠️ Majors
src/Parsers/ASTFromJSON.cpp:385: The JSON placement check does not cover all owned AST expressions.rejectMisplacedParameterizedFunctionName follows only children, but ASTTTLElement::group_by_key and group_by_assignments are deserialized and formatted separately. Starting with the JSON for CREATE TABLE t (ts DateTime, k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k TTL ts GROUP BY k SET v = max(v), replace the max node's name with an empty name and an otherwise valid query_parameter_name. The current readers accept it, the placement walk misses it, and formatQueryFromJSON reaches SET v = {f:Identifier}(v), which the SQL parser rejects. This violates the explicit contract that parameterized scalar-function names are rejected at the JSON boundary. ASTBackupQuery::elements[*].partitions is another separately owned expression path omitted by this walk. Include these fields in validation, or enforce placement during construction. The source trace and SQL reproducer were added to the existing validation thread, which was reopened; no duplicate finding was posted.
Tests
⚠️ Add focused rejection tests for parameterized scalar-function names inside TTL aggregation expressions and backup partition tuples, asserting BAD_ARGUMENTS during JSON deserialization. The existing placement tests exercise ordinary SELECT expressions. The additional reproducer was source-traced, not executed locally; this review job has no ClickHouse binary.
Final Verdict
Status: ⚠️ Request changes
Complete JSON placement validation for expressions stored outside children and add the focused rejection coverage.
…ed-name test
`FunctionLayer::function_name` becomes `std::optional<String>` so a
parameterized table-function name is not represented by an empty string.
`DISTINCT` with such a name is rejected at parse time instead of
dereferencing an empty optional.
`ASTFunction::appendColumnNameImpl` renders the unresolved identifier
placeholder instead of calling `appendColumnName` on it, which printed
nothing because `ASTIdentifier::name` is empty for a query parameter.
The qualified-name test now also executes the backquoted form
`db.view` that `formatWithSecretsOneLine` produces for a resolved
compound name, showing it still resolves when reparsed. The formatting
itself is unchanged by this pull request and is the same for a literal
`db.view(...)` call on master.
Review: ClickHouse#124023
Comparing e8f38a51e with master b8b277d5d (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).
✅ No significant changes.
Binary sizes
programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.
The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.
Compile time of recompiled translation units
1033 translation units recompiled, 7134 s compile time in total, 1032 of them have a recent master baseline.
Translation units without a recent master baseline:
programs/keeper/Keeper.cpp (clickhouse-keeper): 7.5 s
The reason will be displayed to describe this comment to others. Learn more.
Allowing query_parameter_name through generic ASTFunction JSON deserialization opens a second entrypoint that bypasses the parser restriction you kept in ParserFunctionName. With dialect = 'clickhouse_json', a client can now send a scalar function AST whose name is parameterized, and ReplaceQueryParameterVisitor::visit will resolve it unconditionally for every ASTFunction (src/Interpreters/ReplaceQueryParameterVisitor.cpp:52). That breaks the contract from this PR that only function-like table expressions accept parameterized names. Please reject query_parameter_name outside table-function context (or track that context explicitly) instead of accepting it on every ASTFunction.
The reason will be displayed to describe this comment to others. Learn more.
Agreed. Fixed in b02d2eb: ReplaceQueryParameterVisitor now resolves query_parameter_name only on ASTTableExpression::table_function and throws BAD_QUERY_PARAMETER for any other ASTFunction. The visitor runs for every clickhouse_json query (the JSON text always contains {), so the JSON entrypoint gets the same restriction as the SQL parser. 05326_parameterized_view_qualified_name_query_parameter.sh submits a JSON AST with the placeholder on a scalar function and checks the rejection.
The reason will be displayed to describe this comment to others. Learn more.
b02d2eb closes the execution-time bypass, but ASTFunction::readJSON still accepts query_parameter_name on any ASTFunction at src/Parsers/ASTFunction.cpp:225.
That means formatQueryFromJSON (or any other JSON-only consumer that only deserializes and formats) still accepts a scalar {x:Identifier}(...) AST and emits SQL that the ordinary parser cannot produce or parse back. So the parser restriction is still not enforced at the AST-JSON boundary; it is only enforced later by ReplaceQueryParameterVisitor during execution.
The reason will be displayed to describe this comment to others. Learn more.
Fair point, the visitor only caught it at execution time. 7cd71bc moves the check to the JSON boundary. After IAST::createFromJSON builds the tree it walks it once and rejects query_parameter_name on any ASTFunction that is not the table_function of an ASTTableExpression. The dialect and formatQueryFromJSON both enter through that function, so a document with {x:Identifier}(1) in an expression now fails with BAD_ARGUMENTS before anything gets formatted or run. The visitor keeps its check as an invariant. The shell test exercises both consumers.
The reason will be displayed to describe this comment to others. Learn more.
[Major] The boundary fix in 7cd71bc still misses AST-owned expressions outside children. The walk at src/Parsers/ASTFromJSON.cpp:385 cannot reach ASTTTLElement::group_by_key or group_by_assignments: ASTTTLElement::readJSON stores them separately at src/Parsers/ASTTTLElement.cpp:138 and :154.
For a focused reproducer, start with the JSON for a valid TTL aggregation and change only the aggregate's name:
SELECT formatQueryFromJSON(replaceOne(
parseQueryToJSON('CREATE TABLE t (ts DateTime, k UInt64, v UInt64) ENGINE = MergeTree ORDER BY k TTL ts GROUP BY k SET v = max(v)'),
'"name":"max"',
'"name":"","query_parameter_name":{"type":"Identifier","name":"","children":[{"type":"QueryParameter","name":"f","param_type":"Identifier"}]}'
));
Tracing the current readers, the injected function passes ASTFunction::readJSON, the placement walk skips the assignment, and formatting reaches SET v = {f:Identifier}(v), which the SQL parser rejects. This is source-traced; I could not execute the reproducer in this review job. ASTBackupQuery::elements[*].partitions is another separately owned expression path the walk misses.
Please validate the separately owned AST fields as well, or enforce the permitted slot during construction, and add focused rejection tests for these paths.
The substituted name goes through `TableFunctionFactory` before the
parameterized view lookup, so `{f:Identifier}(10)` with `f = 'numbers'`
runs the `numbers` table function. State that in the field comment.
`ReplaceQueryParameterVisitor` resolved `ASTFunction::query_parameter_name`
on any function node. The SQL parser produces it only for a table
expression, but a `clickhouse_json` AST can put it on a scalar function,
which bypassed that restriction. The visitor now resolves the name only on
`ASTTableExpression::table_function` and throws `BAD_QUERY_PARAMETER`
anywhere else.
Narrow the documented contract: the placeholder uses the ordinary call
grammar, so it cannot name `view`, `viewIfPermitted` or `eval`. The tests
cover the JSON rejection and the special-grammar cases.
ClickHouse#124023
…expression
The test covered only the rejection of a misplaced placeholder on the
`clickhouse_json` path. Add the positive case: the JSON document of
`SELECT id FROM {view:Identifier}(id = {value:UInt64})` runs with both
parameters bound, the same as the SQL form.
ClickHouse#124023
`ASTFunction::readJSON` accepted `query_parameter_name` on any function
node, so a `clickhouse_json` document or `formatQueryFromJSON` could build
a tree the SQL parser never produces, such as `{f:Identifier}(x)` in an
expression. `IAST::createFromJSON` now walks the finished tree once and
rejects the placeholder anywhere except the table function of a table
expression. Both consumers go through that entry point.
The visitor keeps its check as an explicit invariant. The test covers the
dialect and `formatQueryFromJSON`.
ClickHouse#124023
`ReplaceQueryParameterVisitor` walked only the children of the describe
query's table expression, so the table expression node itself never took
the branch that resolves `ASTFunction::query_parameter_name`, and
`DESCRIBE TABLE {view:Identifier}(...)` failed with `BAD_QUERY_PARAMETER`
since b02d2eb. Visit the node itself, as `FROM` does. The test covers it.
ClickHouse#124023
…e expression
The syntax docs said an Identifier parameter can name a function. It can name a parameterized
view or a table function with ordinary arguments in a table expression, not a scalar function
nor view, viewIfPermitted and eval.
PR: ClickHouse#124023
Validate identifier parameter types in clickhouse_json payloads
src/Parsers/ASTFunction.cpp:233
This only checks that the identifier contains a parameter; it does not verify that each parameter's type is Identifier. Unlike the SQL parser, which rejects other types in ParserIdentifier::parseImpl, a clickhouse_json payload can therefore use query_parameter_name with param_type: "String" (or any other type), and ReplaceQueryParameterVisitor::visitIdentifier will still substitute it as a raw function name. Validate every child parameter's type here so JSON cannot create a function-name shape the SQL grammar rejects.
… read from JSON
The SQL parser accepts only {name:Identifier} inside an identifier, but the JSON readers of
ASTIdentifier and ASTTableIdentifier checked only that each placeholder child is a query
parameter. A clickhouse_json document could therefore carry {name:String} as a table name or,
with this PR, as a table function name. One helper now does both checks in all four places.
PR: ClickHouse#124023
Re the Copilot finding on ASTFunction::readJSON accepting a non-Identifier parameter type in query_parameter_name: that check lives one level down. query_parameter_name is read through ASTIdentifier::readJSON, which, like ASTTableIdentifier::readJSON, only verified that each placeholder child is an ASTQueryParameter, so the same gap already existed for {t:String} as a table name. 118fbf7 adds the type check there: one helper now requires an Identifier query parameter in all four places, and the shell test feeds a String-typed placeholder as a function name through formatQueryFromJSON and checks for BAD_ARGUMENTS.
The promised exclusion of eval is not enforced after resolving the placeholder. Unlike view, EvalLayer accepts ordinary expression arguments, and TableFunctionEval::parseArguments accepts one constant String; therefore {f:Identifier}('SELECT 1') executes when f = 'eval' and the experimental setting is enabled. Either reject the resolved eval name here (case-insensitively), or update the PR description, documentation, and tests to declare it supported.
Reject aliases in query parameter names
src/Parsers/ASTFunction.cpp:233
This validation still accepts alias metadata on the name identifier (and on its ASTQueryParameter children), because their JSON readers call readAlias. Such a document passes the new placement check, but formatQueryFromJSON emits an invalid shape such as {view:Identifier} AS x(...), while execution discards that alias when the name node is reset. Reject aliases and parameterized aliases throughout query_parameter_name so malformed JSON cannot format and execute with different semantics.
Cover ordinary table functions with parameterized names
This literal numbers call does not exercise the PR's claimed support for naming an ordinary table function through an Identifier parameter. Replace it with a parameterized call so the non-view branch is covered and would fail if name substitution only worked for parameterized views.
… name, narrow the documented exclusions
A stored parameterized view keeps the placeholder with an empty function name, and the
secret-argument finder keys on that name, so SHOW CREATE and system.tables printed the
arguments in clear with secret display off. The formatter now hides every argument of an
unresolved table function and hasSecretParts reports it.
ASTFunction::readJSON rejects an alias on query_parameter_name and on its placeholders,
since {f:Identifier} AS a(...) cannot be parsed back.
The docs, the header comment and the changelog entry now say that only the bare SELECT
argument grammar of view, viewIfPermitted and eval is out of reach, that eval('SELECT 1')
works, and that inline insert data is not detected for input.
PR: ClickHouse#124023
Conflict in src/Parsers/ASTFunction.cpp: master replaced FunctionSecretArgumentsFinderAST
with findSecretArguments, keep the unresolved-name masking on top of the new call.
The reason will be displayed to describe this comment to others. Learn more.
🟢 Approval recommended
The implementation is consistently scoped and has focused regression coverage for execution, formatting, qualification, secrets, and JSON AST validation.
Merged master to fix the conflicts. All builds pass. The two failing perf shards flag array_reverse_generic and complex_array_creation. This PR only changes parsing and formatting of parameterized table function names, so I don't think it can affect those array benchmarks. Could someone re-run those jobs or take a look? Thanks!
Dear @scanhex12, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
can be testedAllows running workflows for external contributorscomp-sql-syntaxSQL/grammar parsing, AST nodes, syntax-level features.externalAuthor is not a member of the ClickHouse organizationpr-bugfixPull request with bugfix, not backported by default
3 participants
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #105037. Finishes #112877, which was closed without merge.
Why
A parameterized view is queried like a table function, and the client docs say
Identifierparameters are for database, table and function names. SoSELECT * FROM {view:Identifier}(id = 1)is what you write when the view is picked at runtime. It fails.ParserFunctionNamerejects a query parameter in function-name position, the table expression never parses, and the error surfaces asUNKNOWN_FUNCTIONon releases andSYNTAX_ERRORon master. Argument names and values can already be parameters, the view name could not.We hit this while building a lineage dump that probes every view in a catalog with
LIMIT 0. The workaround is to run the view's stored SELECT instead of naming the view.What
The function-name parser gets a flag that permits a parameterized name, and only the table-expression parser sets it. Scalar function names keep rejecting query parameters, which is what #106635 introduced to stop a formatting logical error. The unresolved name stays on
ASTFunction::query_parameter_nameuntilReplaceQueryParameterVisitorresolves it, and the visitor resolves it only onASTTableExpression::table_function, including the table expression ofDESCRIBE TABLE. Formatting, column naming, clone and the AST JSON round trip print the placeholder while the name is unknown.A
clickhouse_jsonAST can put such a name on a scalar function, which the SQL parser never does.IAST::createFromJSONwalks the tree once after deserialization and rejectsquery_parameter_nameanywhere but on the table function of a table expression withBAD_ARGUMENTS, so both the dialect andformatQueryFromJSONrefuse the document before it is formatted or run. The visitor keeps the same check as an invariant.The placeholder goes through the ordinary function-call grammar, so after substitution it names a parameterized view or a table function that takes ordinary arguments. Anything decided before substitution is out of reach. The bare
SELECTargument grammar ofview,viewIfPermittedandevalis one such thing:{f:Identifier}(SELECT 1)is a syntax error, and{f:Identifier}((SELECT 1))withf = 'view'fails withBAD_ARGUMENTSfrom the table function, whileeval('SELECT 1')works through a placeholder. Inline insert data forinputis another, since the insert parser and the client look forinputbefore substitution. The docs say so.A stored parameterized view keeps the placeholder with an empty function name, and the secret-argument finder keys on that name, so
SHOW CREATEandsystem.tableswould print the arguments in clear with secret display off. The formatter now masks every argument of an unresolved table function andhasSecretPartsreports it, since the function may take a password.The visitor recomputes
isCompoundName()from the substituted string. A single{view:Identifier}holdingdb.pvis one identifier part at parse time, but the legacy execution path and theEXPLAIN SYNTAXexpansion split on that flag to find the database. The review of #112877 caught this.The query-parameter section of
docs/reference/syntax.mdxsaid anIdentifierparameter can name a function. It now lists database, table, column and other identifiers, shows the parameterized view call, and names the unsupported cases.Compared with #112877: rebased onto master. The qualified-name test is a shell test on the per-test database, so it is safe under parallel and flaky-check runs. It also covers
{db:Identifier}.{name:Identifier}(...)and a call where the name, the argument name and the value are all parameters. TheEXPLAIN SYNTAXassertion that failed Fast test compared againstWHERE id = 1, but explain rendersequals(id, _CAST(1, 'UInt64')), so the test records the explain output itself, as04105_explain_syntax_parameterized_viewdoes.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
You can now pass the name of a parameterized view, or of a table function with ordinary arguments, as an
Identifierquery parameter in a table expression, for exampleSELECT * FROM {view:Identifier}(id = {id:UInt64}), the same way you already can for tables. Scalar function names remain unsupported, as does the bareSELECTargument grammar ofview,viewIfPermittedandeval, whileeval('SELECT 1')works. Tooling that picks a view at runtime no longer has to build the query text itself.Workflow [PR]
Sync PR [sync-upstream/pr/124023]