Skip to content

Support query parameters in the SETTINGS clause and SET queries - #108760

Merged
alexey-milovidov merged 12 commits into
masterfrom
settings-query-params
Jul 10, 2026
Merged

alexey-milovidov merged 12 commits into
masterfrom
settings-query-params

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 28, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Query parameters ({name:Type} substitutions) can now be used as setting values, both in the SETTINGS clause of a query (such as SELECT or INSERT) and in standalone SET queries, e.g. SELECT ... SETTINGS max_threads = {threads:UInt64} and SET max_threads = {threads:UInt64}.

Description

Previously, query parameters could be used in place of identifiers and literals in SELECT statements, but not as setting values — SELECT ... SETTINGS max_threads = {threads:UInt64} failed with a syntax error. This PR makes them work as setting values.

How it works (reusing the existing mechanism for disk = disk(...) settings):

  • Parser (ParserSetQuery): a setting value may now be a {name:Type} substitution, stored as an ASTQueryParameter wrapped into a Field (FieldFromAST).
  • Resolution (ReplaceQueryParameterVisitor): a new visitSetQuery / visitSettingsChanges resolves such wrapped parameters into concrete Field values during the normal server-side query-parameter substitution pass in executeQuery.
  • Client paths (InterpreterSetQuery, ClientBase): the client applies settings from a query before the server substitutes parameters, so settings are also resolved at the settings-application layer using the context's query parameters. This makes the feature work through clickhouse-client and clickhouse-local.

disk = disk(...) settings (the other AST-valued setting) are explicitly left untouched.

Scope. The feature works wherever setting values are parsed by ParserSetQuery — standalone SET, the SETTINGS clause of a query (including the trailing SETTINGS clause attached by ParserQueryWithOutput, which covers SELECT / INSERT / EXPLAIN), and the engine/storage SETTINGS of CREATE TABLE.

For BACKUP / RESTORE, a query parameter works only when the SETTINGS clause contains exclusively core query settings (such as max_threads), which fall through to that trailing SETTINGS clause. It cannot be combined with backup/restore-specific settings (such as async or base_backup) in the same clause: those settings are parsed by the separate bare ParserSetQuery::parseNameValuePair path, which does not understand the {name:Type} placeholder, so a mixed clause is rejected with a SYNTAX_ERROR at parse time.

The other boundary is that same bare ParserSetQuery::parseNameValuePair path used by CREATE NAMED COLLECTION and dictionary SETTINGS: a query parameter as a setting value there is rejected with a SYNTAX_ERROR at parse time rather than silently misbehaving. Both boundaries are covered by the regression test.

Examples:

SET param_threads = 4;
SELECT * FROM numbers(10) SETTINGS max_threads = {threads:UInt64};

SET max_threads = {threads:UInt64};

CREATE TABLE t (x UInt64) ENGINE = MergeTree ORDER BY x SETTINGS index_granularity = {threads:UInt64};

Parameters passed via --param_* / the HTTP param_* interface / a preceding SET param_* are all supported. Type mismatches raise BAD_QUERY_PARAMETER; missing parameters raise UNKNOWN_QUERY_PARAMETER.

Added stateless test 04492_query_parameters_in_settings covering the supported carriers (SELECT / SET / CREATE TABLE storage settings / BACKUP / RESTORE) and the CREATE NAMED COLLECTION boundary case, an integration case in test_http_handlers_config covering query parameters in the SETTINGS clause of a predefined HTTP handler query (so that analyzeReceiveQueryParams discovers the placeholder and the handler accepts param_<name>).

🤖 Generated with Claude Code

Query parameters ({name:Type} substitutions) can now be used as setting
values, both in the SETTINGS clause of a query and in standalone SET
queries, e.g.

    SELECT ... SETTINGS max_threads = {threads:UInt64}
    SET max_threads = {threads:UInt64}

The parser stores such a value as an ASTQueryParameter wrapped into a
Field (the same mechanism already used for `disk(...)` settings). It is
resolved into the concrete value by ReplaceQueryParameterVisitor, both
during server-side query-parameter substitution and when settings from a
query are applied on the client side.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [02437e2]

Summary: ✅


AI Review

Summary

This PR extends query-parameter substitution to setting values in SET, query SETTINGS, CREATE TABLE ... SETTINGS, and the HTTP predefined-handler path by threading placeholders through ASTSetQuery and resolving them before settings are applied. The main mechanics look sound, but the BACKUP / RESTORE mixed-clause boundary is still order-dependent, so the current tests and contract overstate what is actually implemented.

Findings

⚠️ Majors

  • [tests/queries/0_stateless/04492_query_parameters_in_settings.sh:51-58] The narrowed BACKUP / RESTORE contract says a clause that mixes backup-specific settings with a parameterized core setting is rejected with SYNTAX_ERROR, but that is only true when the backup-specific setting comes first. With SETTINGS max_threads = {threads:UInt64}, async = true, ParserBackupQuery::parseSettings fails on the first item, ParserQueryWithOutput reparses the whole clause as trailing query SETTINGS, and InterpreterSetQuery then tries to apply async as a query setting instead of rejecting the mix at parse time. The user-visible behavior therefore depends on setting order.
    Suggested fix: reject mixed clauses in both orders, or narrow the promise and add a focused regression covering the reversed order.
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions: make mixed BACKUP / RESTORE clauses fail consistently regardless of setting order, and add regression coverage for the reversed-order case.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 28, 2026
Comment thread src/Parsers/ParserSetQuery.cpp Resolved
- Resolve setting query parameters on a copy of the changes instead of
  mutating the AST, so the placeholders are preserved for the old-server
  compatibility rewrite in ClientBase::processOrdinaryQuery (review major #1).
- Pass the changes to checkSettingsConstraints as const: the non-const
  overload rewrites the list and drops no-op changes, which lost the
  "changed" flag for a setting explicitly set to its current value
  (e.g. SET log_queries = 1) and broke 03595_set_query_no_eq_set_to_one.
- Teach QueryParameterVisitor / analyzeReceiveQueryParams to discover query
  parameters used as setting values (stored inside FieldFromAST), so
  predefined HTTP handlers accept param_<name> for them (review major #2).
- Renumber the stateless test to 04416 to satisfy the test-numbers style check.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Addressed the review feedback in 9d31e4f:

  • Major 1 (client-side AST mutation): setting query parameters are now resolved on a copy of the changes; the AST keeps the placeholders so the old-server compatibility rewrite in ClientBase::processOrdinaryQuery still works.
  • Major 2 (HTTP handler parameter discovery): QueryParameterVisitor / analyzeReceiveQueryParams now inspect ASTSetQuery::changes and unwrap FieldFromAST/ASTQueryParameter, so predefined HTTP handlers accept param_<name> for settings placeholders.
  • Test number: renumbered the stateless test to 04416 to satisfy the test-numbers style check.

I also fixed the root cause of the Fast test failure in 03595_set_query_no_eq_set_to_one: passing the (non-const) changes copy to checkSettingsConstraints selected the non-const overload, which rewrites the list and drops no-op changes — losing the changed flag for a setting explicitly set to its current value (e.g. SET log_queries = 1). The copy is now passed as const. Verified locally that 03595, 02916_set_formatting, and the new test pass.

alexey-milovidov and others added 2 commits June 28, 2026 23:49
Address review feedback: add focused coverage for the
`analyzeReceiveQueryParams` / predefined HTTP handler path. A predefined
HTTP handler builds `receive_params` from `analyzeReceiveQueryParams` over
its query and only substitutes `param_<name>` values that the scanner
discovers, so a setting placeholder hidden inside `FieldFromAST` must be
found by the new `QueryParameterVisitor::visitSetQuery`.

The new predefined handler runs
`SELECT getSetting('max_threads') SETTINGS max_threads = {threads:UInt64}`,
and the test passes `param_threads=5` over HTTP and asserts the setting is
substituted. Without the `visitSetQuery` discovery, `threads` would not be
in `receive_params` and the parameter would be silently dropped.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment thread src/Parsers/ParserSetQuery.cpp Resolved
alexey-milovidov and others added 4 commits June 29, 2026 21:08
The query-parameter substitution for setting values is wired only through
`ParserSetQuery` (`parseNameValuePairWithParameterOrDefault`), which covers
standalone `SET` and the `SETTINGS` clause of regular queries (`SELECT`,
`INSERT`, `EXPLAIN`, ...). The `SETTINGS` lists of `BACKUP` / `RESTORE` (and
other carriers such as `CREATE TABLE ... SETTINGS`) go through the separate
`ParserSetQuery::parseNameValuePair` path and their settings AST is stored
outside `children`, so query parameters are neither parsed, discovered, nor
resolved there.

Rather than thread the placeholder through every settings carrier, narrow the
documented contract to the supported carriers and lock in the boundary with a
regression test: a query parameter as a setting value in `BACKUP` / `RESTORE`
`SETTINGS` is rejected with a `SYNTAX_ERROR` at parse time instead of silently
misbehaving.

Also renumber the stateless test from `04416` to `04489` to avoid colliding
with `04416_*` tests added on master.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…E settings

The new test `04489_query_parameters_in_settings` asserted that a query
parameter used as a setting value in the `SETTINGS` clause of `BACKUP` /
`RESTORE` is rejected at parse time with a `SYNTAX_ERROR`. That boundary is
false: `ParserBackupQuery` is parsed as part of `ParserQueryWithOutput`, whose
trailing `SETTINGS` clause is parsed by `ParserSetQuery` (the same
`parseNameValuePairWithParameterOrDefault` this PR extends). So
`BACKUP ... SETTINGS max_threads = {threads:UInt64}` actually parses fine and
the parameter is accepted; it only fails later at execution if the backup disk
is not configured. In the `Fast test` environment the backup disk exists, so
the query did not emit `SYNTAX_ERROR` and the test failed.

The same is true for the engine/storage `SETTINGS` of `CREATE TABLE`, which are
also parsed by `ParserSetQuery` (`ParserStorage`): a query parameter there is
accepted and resolved (verified via `SHOW CREATE TABLE`).

The genuine boundary is the separate bare `ParserSetQuery::parseNameValuePair`
path used by `CREATE NAMED COLLECTION`, dictionaries, and similar, where a
placeholder is still rejected with a `SYNTAX_ERROR`.

Update the test to assert the real behavior (a positive `CREATE TABLE` case, a
parse-level `EXPLAIN AST` check for `BACKUP` / `RESTORE` that avoids running a
backup, and a negative `CREATE NAMED COLLECTION` case) and correct the
documentation in `docs/en/sql-reference/syntax.md` accordingly.

Verified locally against a server (16/16 lines match; 5/5 runs pass with random
settings).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108760&sha=b1aae2a8e54d4aef501f34919db0ad7d4184e61b&name_0=PR&name_1=Fast%20test

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Fixed the Fast test failure on the PR's own test 04489_query_parameters_in_settings (merged master and pushed bb016882867).

Root cause — the documented BACKUP / RESTORE boundary is false. The test asserted that a query parameter as a setting value in BACKUP / RESTORE SETTINGS is rejected with a SYNTAX_ERROR. It is not: ParserBackupQuery is parsed as part of ParserQueryWithOutput, whose trailing SETTINGS clause is parsed by ParserSetQuery (the same parseNameValuePairWithParameterOrDefault this PR extends). So:

  • BACKUP's internal parseSettings (which uses the bare parseNameValuePair) rejects {threads:UInt64} and backtracks, leaving SETTINGS max_threads = {threads:UInt64} as leftover;
  • ParserQueryWithOutput then consumes it as a trailing SETTINGS clause, which accepts the placeholder.

So BACKUP ... SETTINGS max_threads = {threads:UInt64} parses fine and the parameter is resolved; in clickhouse-local it only fails later with INVALID_CONFIG_PARAMETER (no backup disk), and in the Fast test environment (where the disk exists) it ran without emitting SYNTAX_ERROR — hence the failure.

The same applies to the engine/storage SETTINGS of CREATE TABLE (parsed by ParserStorage's ParserSetQuery): CREATE TABLE t (...) ... SETTINGS index_granularity = {g:UInt64} with --param_g=4096 is accepted and SHOW CREATE TABLE shows index_granularity = 4096.

The genuine boundary is the separate bare ParserSetQuery::parseNameValuePair path used by CREATE NAMED COLLECTION, dictionaries, etc., where a placeholder is still rejected with a parse-time SYNTAX_ERROR.

What I changed:

  • Rewrote the 04489 test to assert the real behavior: a positive CREATE TABLE storage-setting case, a parse-level EXPLAIN AST check for BACKUP / RESTORE (so it does not actually run a backup and stays deterministic across flaky-check reruns), and a negative CREATE NAMED COLLECTION case.
  • Corrected docs/en/sql-reference/syntax.md and the PR description's "Scope" section accordingly.

Verified locally against a server: 16/16 lines match, and 5/5 runs pass with random settings.

If you'd rather actually exclude BACKUP / RESTORE / CREATE TABLE from this feature (to match the original intent), that would require preventing query-parameter substitution in the shared trailing/storage SETTINGS paths, which is a larger and riskier change — happy to take that direction if you prefer it.

… regression

The AI review (#108760) noted that
the documented `BACKUP` / `RESTORE` support is broader than what is implemented:
a query parameter as a setting value reaches the trailing `SETTINGS` clause (parsed
by `ParserSetQuery`) only when that clause contains exclusively core query settings.

`BACKUP` / `RESTORE` parse their own `SETTINGS` through the separate bare
`ParserSetQuery::parseNameValuePair` path, which does not understand the
`{name:Type}` placeholder. When a backup/restore-specific setting (such as `async`
or `base_backup`) is combined with a parameterized core setting in the same clause,
the backup-specific setting is consumed, the placeholder remainder is left unparsed,
and the query is rejected with a `SYNTAX_ERROR` at parse time. That bare path is
unchanged by this PR, so the rejection is identical with or without the feature.

Narrow the documentation in `docs/en/sql-reference/syntax.md` to state this boundary
precisely, and add a focused regression to `04489_query_parameters_in_settings`
asserting that `BACKUP ... SETTINGS async = true, max_threads = {threads:UInt64}` is
rejected with a `SYNTAX_ERROR`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Pushed e65cd9e2c3a addressing the AI review's Request changes verdict (the BACKUP / RESTORE scope Major) and triaging the two remaining CI reds.

AI Review Major — BACKUP / RESTORE scope narrowed to the implemented behavior

I took the lighter of the two suggested options (narrow the docs/scope rather than wire the backup-specific carrier through parsing/discovery/replacement), since the heavier option is the shared-path change deliberately left out of scope.

Confirmed behavior (the trailing SETTINGS clause attached by ParserQueryWithOutput is what carries the placeholder):

  • BACKUP / RESTORE whose SETTINGS clause contains only core query settings works — e.g. BACKUP ... SETTINGS max_threads = {threads:UInt64} (parameter resolved).
  • Mixing a parameterized core setting with a backup/restore-specific setting (async, base_backup, …) in the same clause does not work. BACKUP's own parseSettings uses the bare ParserSetQuery::parseNameValuePair, which doesn't understand the {name:Type} placeholder, so it consumes the backup-specific setting (e.g. async = true) and leaves the , max_threads = {threads:UInt64} remainder unparsed → the query is rejected with a SYNTAX_ERROR at parse time. This bare path is untouched by the PR, so the rejection is identical with or without the feature.

Changes:

  • docs/en/sql-reference/syntax.md and the PR "Scope" section now state this boundary precisely (BACKUP / RESTORE works for core-query-settings-only clauses; mixing with backup/restore-specific settings is rejected with SYNTAX_ERROR).
  • Added the focused regression the review asked for to 04489_query_parameters_in_settings: BACKUP TABLE system.one TO Disk('backups', 'b') SETTINGS async = true, max_threads = {threads:UInt64} → SYNTAX_ERROR.

CI reds — both unrelated known issues

…_threads_auto_parsing_compat

`04489_max_threads_auto_parsing_compat` was merged to `master` after this
branch's last `master` merge, so `04489_query_parameters_in_settings` now
shares its number prefix. Renumber the test (and its internal `04489_*`
table / named-collection identifiers) to `04492`, which is free on `master`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Renumbered the stateless test 04489_query_parameters_in_settings → 04492_query_parameters_in_settings (commit cf85d5e8bfe): 04489_max_threads_auto_parsing_compat was merged to master after this branch's last master merge, so the two tests shared the 04489 prefix. 04490/04491 are taken by other in-flight PRs, so the test (and its internal 04489_* table / named-collection identifiers) moved to 04492, which is free on master. Pure rename — no behavior change. The AI review verdict on e65cd9e2 is ✅ Approve and there are no unresolved review threads; CI is re-running on the renumbered commit.

Comment thread docs/en/sql-reference/syntax.md Resolved
alexey-milovidov and others added 2 commits July 2, 2026 01:53
Address the review comment on `docs/en/sql-reference/syntax.md`: the added
`<details>` block describing query parameters as setting values (including the
`BACKUP` / `RESTORE` boundary) and the extra sentence in the `:::note` only
complicate the docs. Revert all changes in this file so it matches `master`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Comment on lines +51 to +58
# A query parameter (a core query setting) cannot be combined with a backup/restore-specific setting
# (such as `async` or `base_backup`) in the same BACKUP / RESTORE SETTINGS clause: those settings are
# parsed by the separate ParserSetQuery::parseNameValuePair path, which does not understand the
# {name:Type} placeholder. Here `async = true` is consumed as a backup setting and the remainder
# `, max_threads = {threads:UInt64}` is left unparsed, so the query is rejected with a SYNTAX_ERROR at
# parse time rather than misbehaving. (This path is unchanged by this PR, so the rejection is identical
# with or without the feature.)
$CLICKHOUSE_CLIENT --param_threads=4 -q "BACKUP TABLE system.one TO Disk('backups', 'b') SETTINGS async = true, max_threads = {threads:UInt64}" 2>&1 | grep -o "SYNTAX_ERROR" | head -n1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The mixed BACKUP / RESTORE boundary is still order-dependent. This regression only covers SETTINGS async = true, max_threads = {threads:UInt64}, where ParserBackupQuery::parseSettings consumes async first and then leaves the placeholder remainder unparsed. If the parameterized core setting comes first (SETTINGS max_threads = {threads:UInt64}, async = true), parseSettings bails out on the first item, ParserQueryWithOutput reparses the whole clause as trailing query settings_ast, and InterpreterSetQuery::executeForCurrentContext later tries to apply async as a query setting instead of rejecting the mixed clause at parse time. That violates the narrowed contract and leaves the behavior dependent on setting order. Please either reject both orderings consistently in the parser or narrow the promise and add a regression for the reversed order.

@clickhouse-gh

clickhouse-gh Bot commented Jul 7, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.60% 85.60% +0.00%
Functions 92.70% 92.70% +0.00%
Branches 77.90% 77.90% +0.00%

Changed lines: Changed C/C++ lines covered: 92/93 (98.92%) · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@alexey-milovidov alexey-milovidov self-assigned this Jul 10, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 10, 2026
Merged via the queue into master with commit 1626217 Jul 10, 2026
344 of 345 checks passed
@alexey-milovidov
alexey-milovidov deleted the settings-query-params branch July 10, 2026 23:09
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 10, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
… regression

The AI review (ClickHouse#108760) noted that
the documented `BACKUP` / `RESTORE` support is broader than what is implemented:
a query parameter as a setting value reaches the trailing `SETTINGS` clause (parsed
by `ParserSetQuery`) only when that clause contains exclusively core query settings.

`BACKUP` / `RESTORE` parse their own `SETTINGS` through the separate bare
`ParserSetQuery::parseNameValuePair` path, which does not understand the
`{name:Type}` placeholder. When a backup/restore-specific setting (such as `async`
or `base_backup`) is combined with a parameterized core setting in the same clause,
the backup-specific setting is consumed, the placeholder remainder is left unparsed,
and the query is rejected with a `SYNTAX_ERROR` at parse time. That bare path is
unchanged by this PR, so the rejection is identical with or without the feature.

Narrow the documentation in `docs/en/sql-reference/syntax.md` to state this boundary
precisely, and add a focused regression to `04489_query_parameters_in_settings`
asserting that `BACKUP ... SETTINGS async = true, max_threads = {threads:UInt64}` is
rejected with a `SYNTAX_ERROR`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…arams

Support query parameters in the SETTINGS clause and SET queries
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants