Skip to content

Add EXPLAIN TEXT for query formatting and pagination rewrites - #119167

Closed
protomn wants to merge 73 commits into
ClickHouse:masterfrom
protomn:feat/explain-text
Closed

protomn wants to merge 73 commits into
ClickHouse:masterfrom
protomn:feat/explain-text

Conversation

@protomn

@protomn protomn commented Sep 10, 2026 •

Copy link
Copy Markdown
Contributor

Adds EXPLAIN TEXT so clients can format SQL and change pagination or output format using ClickHouse's own parser, without executing the source query. Returns exactly one row containing a String column named text.

The motivation follows the query-rewrite RFC: UI tools need to modify SQL without maintaining partial parsers that can corrupt its structure. Issue #75033 selects an EXPLAIN interface so the operation is available through existing ClickHouse interfaces and request handling. The actions edit the source query's AST; they do not apply a limit or sort to a wrapped result set.

Supports ONELINE, MULTILINE, MODIFY LIMIT, MODIFY OFFSET, PAGE, and MODIFY FORMAT, applied from left to right. For example:

EXPLAIN TEXT (SELECT * FROM t LIMIT 100)
MODIFY LIMIT 5, ONELINE
FORMAT JSONEachRow;
{"text":"SELECT * FROM t LIMIT 5"}

Several of the implementation choices were based on the following:

  • Existing formatQuery and the earlier scalar-function proposal provides some background on formatting. The additional capability here is ordered clause rewriting using typed actions on a cloned AST.
  • Both bare and parenthesized source queries are accepted. Action-looking words can also be implicit aliases, so bare parsing validates the action suffix and the complete source prefix before accepting a boundary. Malformed action separators are rejected instead of silently changing the source query.
  • Source and outer output options have separate ownership. The earlier output-option formatting fix and parenthesized EXPLAIN support informed the round-trip requirements. Parentheses preserve nested action boundaries when formatting a query for reparse.
  • Following AST JSON serialization, the new action nodes support JSON serialization, validate caller-authored operand shapes, and have SQL/JSON round-trip coverage.
  • Source settings and query parameters remain preserved through early request processing. Only outer options apply to the formatting request. PAGE uses the current limit, removes the offset for page one, and checks multiplication overflow for UInt64 literal limits.
  • In the bare form, each action-looking word at the top level is a candidate boundary and the source prefix is re-parsed per candidate; a statement with hundreds of such words before SETTINGS/FORMAT can exceed max_parser_backtracks. Use the parenthesized form for such statements.

Pagination rewrites require a single plain SELECT. MODIFY FORMAT also supports unions because their output format has a clear top-level owner. Inline-data INSERT sources, subquery use, and direct viewExplain use are rejected in this initial scope.

KEEP SPACE AND COMMENTS, projection/filter/order rewrites, and multi-branch union pagination remain outside this change. Existing whitespace-preservation helpers in formatQueryFromJSON provide a starting point for later work. The linked feature issue therefore remains open.

Related: #75033
Related: #29922
Related: #48757
Related: #99545
Related: #100136
Related: #100412

Changelog category (leave one):

  • New Feature

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

Added EXPLAIN TEXT to return formatted SQL without executing it, with optional changes to its limit, offset, page, and output format. Supports single-line and multiline output while preserving query parameters.


Workflow [PR]
Sync PR [sync-upstream/pr/119167]

Groundwork for the query rewrite and formatting API: the AST nodes and
serialization for `EXPLAIN TEXT`, without the parser or interpreter yet.

Adds `ASTExplainTextAction`, a typed node for a single rewrite or format
action (`ONELINE`, `MULTILINE`, `MODIFY LIMIT`, `MODIFY OFFSET`, `PAGE`,
`MODIFY FORMAT`), with per-kind shape validation and AST JSON support.

Adds the `FormattedQuery` kind to `ASTExplainQuery` with an `actions` child,
wired through `clone`, `formatQueryImpl`, `writeJSON` and `readJSON`.
Deserialization rejects actions on other kinds, and leading kind-specific
settings on `EXPLAIN TEXT`.

`EXPLAIN TEXT` is not reachable yet: the parser does not accept it, the
interpreter throws, and it is rejected in subqueries and by the `viewExplain`
table function. `QueryFuzzer` skips the kind so it cannot generate invalid
kind/action combinations.
@clickhouse-gh clickhouse-gh Bot added comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. external Author is not a member of the ClickHouse organization labels Sep 10, 2026
@maxknv maxknv removed the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@clickhouse-gh clickhouse-gh Bot added the external Author is not a member of the ClickHouse organization label Sep 11, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Sep 12, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ffbc49c]

Summary: ✅


AI Review

Summary

EXPLAIN TEXT itself now looks much more solid: the earlier parser-boundary, visitor-isolation, and output-ownership issues appear to be addressed in the current head. The one concern I still consider real is on the AST-JSON boundary rather than in the SQL parser path: mixed alias / parametrised_alias shapes are still accepted and can make formatQueryFromJSON disagree with direct clickhouse_json execution.

Missing context / blind spots
  • ⚠️ I did not run the stateless tests locally because this checkout has no build directory or ClickHouse binary; the finding below comes from tracing the current deserialization, formatting, and parameter-substitution code paths.
Findings

⚠️ Majors

  • [src/Parsers/ASTJSONReadHelpers.h:266-283] [dismissed by author -- https://github.com/Add EXPLAIN TEXT for query formatting and pagination rewrites #119167#discussion_r4078001557] readAlias now validates the parametrised_alias node shape, but it still accepts the parser-impossible mixed state where both alias and parametrised_alias are present. formatQueryFromJSON then renders only the plain alias because ASTWithAlias::formatImpl prefers it, while direct clickhouse_json execution still resolves or errors on parametrised_alias in ReplaceQueryParameterVisitor::resolveParameterizedAlias. A caller-authored JSON AST can therefore format as ... AS x yet execute as ... AS y or throw UNKNOWN_QUERY_PARAMETER, so the tightened SQL/JSON parity contract is still incomplete for this shape.
  • Suggested fix: reject simultaneous alias and parametrised_alias during AST JSON deserialization, or canonicalize to one carrier before formatting and execution, and add a focused formatQueryFromJSON plus direct-JSON regression.
Final Verdict
  • Status: ⚠️ Needs follow-up
  • The parser/rewriter work looks solid overall, but the AST-JSON alias gate is still incomplete on a surface this PR explicitly tightens.

LLVM Coverage Report

Measured on commit ffbc49c.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 91.80% 91.80% +0.00%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 1107/1168 (94.78%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 12, 2026
Comment thread src/Parsers/ASTExplainQuery.h Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing ffbc49cc4 with master a95819412 (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

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.

Object file sizes ⚠️

387 object files changed (+620.29 KiB total), 3 added.

Object file Master PR Δ
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ASTExplainTextAction.cpp.o new 317.38 KiB +317.38 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserExplainTextActions.cpp.o new 80.61 KiB +80.61 KiB
src/CMakeFiles/dbms.dir/Interpreters/ExplainTextRewrite.cpp.o new 71.81 KiB +71.81 KiB
src/Parsers/CMakeFiles/clickhouse_parsers.dir/ParserExplainQuery.cpp.o 148.10 KiB 191.82 KiB +43.72 KiB (+29.52%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

1897 translation units recompiled, 10559 s compile time in total, 1894 of them have a recent master baseline.

Job report

Comment thread src/Interpreters/executeQuery.cpp Resolved
@protomn
protomn force-pushed the feat/explain-text branch 2 times, most recently from fd80610 to b9d6f8c Compare September 13, 2026 05:22
Comment thread src/Interpreters/ExplainTextRewrite.cpp Resolved
Comment thread src/Interpreters/ExplainTextRewrite.cpp Resolved
@protomn

protomn commented Sep 26, 2026 •

Copy link
Copy Markdown
Contributor Author

cc @alexey-milovidov - I think I've covered everything I had in mind in this PR and responded to all of the AI review. Could you take a look whenever you get a chance and let me know if there's anything that I've missed? Thanks! All CI checks are green except amd_release.

Comment thread src/Parsers/ASTWithAlias.cpp Resolved
Comment thread src/Parsers/ASTQueryWithOutput.cpp Resolved
@protomn

protomn commented Sep 30, 2026

Copy link
Copy Markdown
Contributor Author

Workflow [PR], commit [ffbc49c]

AI Review

Summary

EXPLAIN TEXT itself now looks much more solid: the earlier parser-boundary, visitor-isolation, and output-ownership issues appear to be addressed in the current head. The one concern I still consider real is on the AST-JSON boundary rather than in the SQL parser path: mixed alias / parametrised_alias shapes are still accepted and can make formatQueryFromJSON disagree with direct clickhouse_json execution.

Missing context / blind spots
  • ⚠️ I did not run the stateless tests locally because this checkout has no build directory or ClickHouse binary; the finding below comes from tracing the current deserialization, formatting, and parameter-substitution code paths.
Findings

⚠️ Majors

  • [src/Parsers/ASTJSONReadHelpers.h:266-283] [dismissed by author -- https://github.com/Add EXPLAIN TEXT for query formatting and pagination rewrites #119167#discussion_r4078001557] readAlias now validates the parametrised_alias node shape, but it still accepts the parser-impossible mixed state where both alias and parametrised_alias are present. formatQueryFromJSON then renders only the plain alias because ASTWithAlias::formatImpl prefers it, while direct clickhouse_json execution still resolves or errors on parametrised_alias in ReplaceQueryParameterVisitor::resolveParameterizedAlias. A caller-authored JSON AST can therefore format as ... AS x yet execute as ... AS y or throw UNKNOWN_QUERY_PARAMETER, so the tightened SQL/JSON parity contract is still incomplete for this shape.
  • Suggested fix: reject simultaneous alias and parametrised_alias during AST JSON deserialization, or canonicalize to one carrier before formatting and execution, and add a focused formatQueryFromJSON plus direct-JSON regression.
Final Verdict
  • Status: ⚠️ Needs follow-up
  • The parser/rewriter work looks solid overall, but the AST-JSON alias gate is still incomplete on a surface this PR explicitly tightens.

Out of scope here. Tracked separately in #121679

@alexey-milovidov

Copy link
Copy Markdown
Member

This is a good implementation, and thanks for contributing!

However, I'd like to cancel the original task. The reason is that the JSON AST looks more interoperable, while inventing a new class of language inside SQL might be way too much.

@alexey-milovidov

alexey-milovidov commented Oct 17, 2026 •

Copy link
Copy Markdown
Member

What was the reason for coming back to this task and reconsidering it?

In one context, I needed a way to programmatically wrap a subquery in GROUP BY. And I thought, maybe I can use an API for query rewrite that we've proposed? But it does not cover this use case. Then I found that the proposed API for query rewrite is very limited and will not cover many other use cases.

This sort of problem appears again and again in various programming languages. Some solve it with Lisp, some solve it with AST matching macros. When we just exposed AST as JSON, we put the problem aside, and now we can avoid solving it.

@clickhouse-gh clickhouse-gh Bot added comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... and removed comp-sql-syntax SQL/grammar parsing, AST nodes, syntax-level features. labels Nov 22, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-explain EXPLAIN and query profiling output: EXPLAIN PLAN / PIPELINE / AST / SYNTAX / ESTIMATE, pretty EXP... external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants