Skip to content

Add hint about missing FROM clause in UNKNOWN_IDENTIFIER error - #101769

Merged
alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
Onyx2406:fix/better-missing-from-error
May 31, 2026
Merged

alexey-milovidov merged 15 commits into
ClickHouse:masterfrom
Onyx2406:fix/better-missing-from-error

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

When a query has no FROM clause (e.g., SELECT x) and an identifier cannot be resolved, the error message now includes a hint: "Note: the query does not have the FROM clause. Did you forget to add it?"

Fixes #56653

Changelog category (leave one):

  • Improvement

Changelog entry:

Improved error message for unresolved identifiers in queries without a FROM clause to suggest adding one.

  • Documentation is written (no docs needed)

Note

Low Risk
Low risk: only augments UNKNOWN_IDENTIFIER exceptions with an extra message when a top-level SELECT has no FROM and no implicit_table_at_top_level is set. Main risk is minor behavior change in error output that could affect tests or tooling that matches error strings.

Overview
Improves UNKNOWN_IDENTIFIER errors by appending a hint when the analyzer detects a top-level SELECT without a FROM clause (and implicit_table_at_top_level is not set), suggesting the user may have forgotten to add FROM.

Adds a stateless test (04260_hint_missing_from_clause) covering cases where the hint should appear (no FROM) and should not (explicit FROM or implicit table configured).

Reviewed by Cursor Bugbot for commit 6836347. Bugbot is set up for automated code reviews on this repo. Configure here.

Version info

  • Merged into: 26.6.1.291

Onyx2406 added 3 commits April 4, 2026 16:56
When a query has no FROM clause (e.g., `SELECT x`) and an identifier
cannot be resolved, append a hint to the error message suggesting the
user may have forgotten the FROM clause.

Fixes ClickHouse#56653
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 7, 2026

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

This is great!

@alexey-milovidov alexey-milovidov self-assigned this May 7, 2026
The check `!query_node->getJoinTree()` never fires because the analyzer
substitutes `system.one` as an implicit join tree when no `FROM` clause
is present (see `QueryTreeBuilder::buildJoinTree`). So the hint was
never emitted in practice.

Inspect the original AST (`ASTSelectQuery::tables`) instead, which is
absent when the user did not write a `FROM` clause.

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

clickhouse-gh Bot commented May 18, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [b7afdb2]

Summary: ✅


AI Review

Summary

This PR improves UNKNOWN_IDENTIFIER diagnostics by appending a missing-FROM hint when the analyzer falls back to system.one. The main behavior is covered for top-level queries, explicit FROM, implicit_table_at_top_level, and expression subqueries, but one no-FROM carrier still misses the hint because CTE query nodes keep ASTWithElement as their original AST.

Findings

⚠️ Majors

  • [src/Analyzer/Resolve/QueryAnalyzer.cpp:3229] CTE bodies with a missing FROM still fall back to system.one, but this unwrap only handles ASTSubquery and ASTSelectWithUnionQuery. QueryTreeBuilder::buildExpression overwrites CTE query nodes' original AST with ASTWithElement, so WITH c AS (SELECT missing_column) SELECT * FROM c never reaches the inner ASTSelectQuery and does not get the new hint.
    Suggested fix: unwrap ASTWithElement::subquery before the existing ASTSubquery/ASTSelectWithUnionQuery handling, or preserve the inner query's original AST for CTEs.
Tests
  • ⚠️ Add a focused 04260_hint_missing_from_clause case for WITH c AS (SELECT missing_column) SELECT * FROM c so the CTE no-FROM path is covered.
Final Verdict

Status: ⚠️ Request changes

Minimum required action: handle ASTWithElement CTE bodies in the missing-FROM detection and add the regression test above.

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label May 18, 2026
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
The test was accidentally added to this branch by an earlier renumber
commit. It belonged to PR ClickHouse#101788 which was closed because the underlying
`coalesce` bug got fixed upstream by the new logical JOIN step
(`d4b469e03a9`). The test is no longer applicable and would conflict
with `04089_decimal_datetime64_minmax_if.sql` on master.
…mplicit_table_at_top_level`

Two issues with the FROM-clause hint reported in CI:

1. `03096_text_log_format_string_args_not_empty` started failing because
   the hint was added by extending the exception format string itself,
   which changed the `message_format_string` column logged in
   `system.text_log`. Construct the `Exception` with the original five
   placeholders and append the hint via `addMessage` so the structured
   logging stays stable.

2. As pointed out by `clickhouse-gh` review, the check only looked at the
   original AST. When `implicit_table_at_top_level` is set, the analyzer
   substitutes that table for the missing `FROM` clause (see
   `QueryTreeBuilder::buildJoinTree`), so suggesting to add `FROM` would
   be misleading. Gate the hint on that setting being empty.

The reworked `04260_hint_missing_from_clause` test (renumbered from
04095 to avoid colliding with later master tests) also stops counting
matches by line, which avoided a separate failure where the
`--send_logs_level=warning` default echoed each exception twice
(server log + final error).
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 20, 2026
Workflow files in this branch were stale or had been deleted as a
workaround for GitHub's workflow-scope check. Restoring them to match
`master` so the PR diff no longer contains those unrelated changes.
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
`Build (arm_tidy)` failed on `cert-err09-cpp`/`cert-err61-cpp` because the
existing `NOLINT(hicpp-exception-baseclass)` only suppressed one of three
checks. Rewrite the throw site to construct the `Exception` as an anonymous
temporary, threading the optional `FROM` hint through the `fmt` format
string instead of a follow-up `addMessage` call. This drops the
`NOLINT` and clears the three diagnostics.

While there, address the AI Review feedback on the prior fix: the hint was
suppressed for *every* `SELECT` without `FROM` whenever
`implicit_table_at_top_level` was set, even though
`QueryTreeBuilder::buildJoinTree` only substitutes that table for
top-level `SELECT`. Subqueries without `FROM` still fall back to
`system.one`, so they should keep the hint. The new condition gates the
suppression on `!query_node->isSubquery()`.

To detect a user-written missing `FROM` from a subquery's `QueryNode`,
unwrap the original AST through `ASTSubquery` →
`ASTSelectWithUnionQuery` → `ASTSelectQuery`: the buildExpression path
overwrites the bare `ASTSelectQuery` with the wrapping `ASTSubquery`.

Extends `04260_hint_missing_from_clause` with the
`SELECT (SELECT nonexistent_column)` + `--implicit_table_at_top_level`
regression case from the AI Review.

Build log:
https://s3.amazonaws.com/clickhouse-test-reports/PRs/101769/68363475054b7d152f7cc73491a92fc944d51288/build_arm_tidy/build_clickhouse/build_clickhouse.log
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
alexey-milovidov and others added 3 commits May 25, 2026 10:45
Commit `7108b79a3e9` ("Restore subquery hint and silence `clang-tidy`
cert-err09/61") fixed the `Build (arm_tidy)` failure by inlining the
exception as an anonymous temporary, but in doing so reintroduced the
`03096_text_log_format_string_args_not_empty` regression that
`8f6ac60f34b` had originally fixed: threading the optional `FROM`-hint
through the `fmt` format string changed `message_format_string` from
`Unknown {}{} identifier {} in scope {}{}` to
`Unknown {}{} identifier {} in scope {}{}{}` for *every* unresolved
identifier, breaking the structured-logging contract consumers rely on
(`03096` and downstream tooling that match on the stable format).

Restore the `addMessage` approach: construct the `Exception` with the
original five-placeholder format string and append the hint as an
extended message. To clear all three `clang-tidy` diagnostics that fired
last time on the named `throw exception;` site
(`cert-err09-cpp`/`cert-err61-cpp`/`misc-throw-by-value-catch-by-reference`),
expand the `NOLINT` annotation to suppress them explicitly alongside
`hicpp-exception-baseclass`.

Verified locally with `cppexpr` that `tryGetMessageFormatString` returns
the original five-placeholder string while `message` still includes the
hint:

  message_format_string -> Unknown {}{} identifier {} in scope {}{}
  message               -> ... in scope SELECT unknown_identifier:
                           Note: the query does not have the FROM clause.
                           Did you forget to add it?

Addresses the unresolved review thread from `clickhouse-gh` on
`src/Analyzer/Resolve/QueryAnalyzer.cpp:3194`.

CI report:
ClickHouse#101769

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
The `Did you forget to add it?` hint is implemented in
`QueryAnalyzer.cpp` and is therefore only produced by the new analyzer.
Without forcing it, the test fails on the
`Stateless tests (amd_llvm_coverage, old analyzer, ...)` shard, which
runs with `allow_experimental_analyzer=0` via
`tests/config/users.d/analyzer.xml` and never emits the hint.

Pass `--enable_analyzer=1` (alongside the existing
`--send_logs_level=fatal`) through a shared `CLIENT` variable so every
query exercises the new-analyzer code path on every shard.

See PR: ClickHouse#101769
Failing report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=101769&sha=f6f2c7075b35115c2307c52a55a5f507c45d8735&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29
/// subquery, an `ASTSubquery` wrapping `ASTSelectWithUnionQuery` over a single
/// `ASTSelectQuery`. Unwrap to find the user-written `SELECT`.
const IAST * original_ast = query_node->getOriginalAST().get();
if (const auto * subquery = original_ast ? original_ast->as<ASTSubquery>() : nullptr)

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.

This misses CTE bodies. QueryTreeBuilder::buildExpression builds an ASTWithElement by calling buildSelectWithUnionExpression with is_subquery = true, then overwrites the resulting QueryNode original AST with the outer ASTWithElement via result->setOriginalAST(expression).

For WITH c AS (SELECT missing_column) SELECT * FROM c, the inner SELECT still has no FROM and buildJoinTree falls back to system.one, but this unwrap never reaches the ASTSelectQuery, so the new hint is absent. Please unwrap ASTWithElement::subquery here, or preserve the inner query's original AST for CTEs, and add this case to 04260_hint_missing_from_clause.

@clickhouse-gh

clickhouse-gh Bot commented May 31, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.40% 84.40% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 77.00% 76.90% -0.10%

Changed lines: Changed C/C++ lines covered by tests: 26/26 (100.00%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov alexey-milovidov removed the manual approve Manual approve required to run CI label May 31, 2026
@alexey-milovidov
alexey-milovidov merged commit 1d70cc5 into ClickHouse:master May 31, 2026
165 of 166 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 1, 2026
sebver pushed a commit to sebver/ClickHouse that referenced this pull request Jun 12, 2026
The check_log retry waited only for any span with parent_span_id=0x73 to
appear before running the assertions. The ===http=== flow produces two such
gateway spans (a local HTTPHandler and a remote TCPHandler), each flushed to
opentelemetry_span_log by an independent background thread. Under the amd_tsan
parallel runner the remote TCPHandler could be flushed first, satisfying the
retry condition while the HTTPHandler and the initial 'select 1 from
remote(...)' query span it parents were not yet in the table. The assertions
then observed 'total spans': 2 instead of 3, or 'initial query spans with
proper parent': 1 instead of 2.

Poll instead until the exact quantities the assertions read are present: the
total number of 'query' spans and the number of initial query spans with a
proper parent, passed per flow (3 2 for HTTP, 3 1 for native). The asserted
output is unchanged, so the .reference file is untouched.

Confirmed root cause from CI failures on PRs ClickHouse#107050 and ClickHouse#101769
(Stateless tests (amd_tsan, parallel, 2/2)). Follow-up to ClickHouse#98552, which fixes
issues ClickHouse#67108 and ClickHouse#93452.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
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 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.

Need better exception message when I forgot to write FROM

3 participants