Skip to content

Parameterized views: Support DESCRIBE queries & scalar expressions in the analyzer - #68978

Merged
alexey-milovidov merged 39 commits into
masterfrom
param-view-analyze
Jul 28, 2026
Merged

alexey-milovidov merged 39 commits into
masterfrom
param-view-analyze

Conversation

@novikd

@novikd novikd commented Aug 27, 2024 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Improve DESCRIBE query support for parameterized views. Support parameterized views in scalar expressions in the new analyzer. Closes #66307. Closes #69598.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

CI Settings (Only check the boxes if you know what you are doing):

  • Allow: All Required Checks
  • Allow: Stateless tests
  • Allow: Stateful tests
  • Allow: Integration Tests
  • Allow: Performance tests
  • Allow: All Builds
  • Allow: batch 1, 2 for multi-batch jobs
  • Allow: batch 3, 4, 5, 6 for multi-batch jobs

  • Exclude: Style check
  • Exclude: Fast test
  • Exclude: All with ASAN
  • Exclude: All with TSAN, MSAN, UBSAN, Coverage
  • Exclude: All with aarch64, release, debug

  • Run only fuzzers related jobs (libFuzzer fuzzers, AST fuzzers, etc.)
  • Exclude: AST fuzzers

  • Do not test
  • Woolen Wolfdog
  • Upload binaries for special builds
  • Disable merge-commit
  • Disable CI cache

Version info

  • Merged into: 26.8.1.325 (included in 26.8 and later)

@robot-ch-test-poll robot-ch-test-poll added the pr-bugfix Pull request with bugfix, not backported by default label Aug 27, 2024
@novikd
novikd marked this pull request as ready for review September 2, 2024 13:38
@novikd novikd added pr-improvement Pull request with some product improvements and removed pr-bugfix Pull request with bugfix, not backported by default labels Sep 2, 2024
@novikd novikd changed the title Parameterized views: Analyze SELECT query Parameterized views: Support DESCRIBE queries & scalar expressions in new analyzer Sep 2, 2024
@novikd novikd added the analyzer Issues and pull-requests related to new analyzer label Sep 2, 2024
@KochetovNicolai KochetovNicolai self-assigned this Sep 2, 2024
Comment thread src/Analyzer/Resolve/QueryAnalyzer.cpp Resolved
@novikd
novikd force-pushed the param-view-analyze branch from 7138fef to 31026aa Compare September 3, 2024 13:04
@clickhouse-gh

clickhouse-gh Bot commented Dec 10, 2024

Copy link
Copy Markdown
Contributor

Dear @KochetovNicolai, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@alexey-milovidov

Copy link
Copy Markdown
Member

CI triage for a523494092a (maintenance pass): the two previously-red jobs are gone — 03742_nested_loop_join_long MEMORY_LIMIT_EXCEEDED cleared with #111644 (merged 2026-07-26), and the Upgrade check (amd_release) t_plt_evict_reinsert CORRUPTED_DATA red did not recur.

Sole remaining red is unrelated to this PR:

Branch is up to date with master (merge-base 2026-07-26), mergeable = MERGEABLE, and the PR diff is unchanged (the same 13 files).

The AI review's three findings (only_analyze subquery access walk in checkAccessRightsForSubquery/extractAllTableReferences, describe_include_virtual_columns for DESCRIBE pv(...), and DESCRIBE-vs-analyzer table-function precedence) are unchanged and are still design calls reserved for @novikd — they touch the SQL-security and name-precedence contract, so I am flagging rather than guessing.

@alexey-milovidov

Copy link
Copy Markdown
Member

Maintenance pass: merged current `master` into the branch (new head `6a8d10d61db`, clean merge, zero conflicts; the PR diff is still exactly the same 13 files).

Reason for the re-merge: the sole remaining red on `a523494092a` was `Stress test (amd_debug)` — `Logical error: Inconsistent KeyCondition behavior` from `MergeTreeDataSelectExecutor::markRangesFromPKRange` (the wider-typed-key-comparison family, issue #111421). Its fix #109023 merged into master on 2026-07-27 (merge commit `107980ea2e3`), which is after this branch's previous merge-base, so pulling master in should clear that red on the next CI run.

Build-verified the five affected translation units (`QueryAnalyzer.cpp`, `Analyzer/Utils.cpp`, `CollectSets.cpp`, `PlannerJoinTree.cpp`, `InterpreterDescribeQuery.cpp`) against current master — exit 0, no API drift.

The three unresolved review threads (`InterpreterDescribeQuery.cpp` virtual columns, `PlannerJoinTree.cpp` `only_analyze` subquery walk, and the `DESCRIBE` precedence question) are unchanged and still awaiting @novikd's design decision.

@clickhouse-gh

clickhouse-gh Bot commented Jul 28, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.30% 86.30% +0.00%
Functions 92.10% 92.00% -0.10%
Branches 78.50% 78.40% -0.10%

Changed lines: Changed C/C++ lines covered: 90/91 (98.90%) · Uncovered code

Full report · Diff report

@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.

LGTM

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 28, 2026
@alexey-milovidov

Copy link
Copy Markdown
Member

@clickgapai, you may send follow-ups according to the remaining review comments.

@clickgapai

Copy link
Copy Markdown
Contributor

Thanks, @alexey-milovidov. I've gone back through the open comments on #68978 and want to make sure I prioritize correctly before pushing changes.

Could you confirm which of the remaining comments you consider blocking for this PR versus follow-up material? Once I know that, I'll address the blocking ones directly and leave the rest for a later round.

Merged via the queue into master with commit 0ad3ed4 Jul 28, 2026
179 checks passed
@alexey-milovidov
alexey-milovidov deleted the param-view-analyze branch July 28, 2026 23:32
@robot-ch-test-poll robot-ch-test-poll added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 29, 2026
pull Bot pushed a commit to mikeyhodl/ClickHouse that referenced this pull request Aug 6, 2026
A parameterized view referenced unqualified in a query that is shipped to a shard arrived at the
shard without its database, because TableFunctionNode::toASTImpl emitted table_function_name --
the identifier as the user wrote it -- and never consulted storage_id. The shard then re-resolved
the name against its own default database.

Measured on a two-shard cluster with the session database set to the view's database and the call
unqualified: non-GLOBAL IN through a Distributed table, JOIN ... ON, JOIN ... USING and remote()
all failed with UNKNOWN_FUNCTION raised by the remote shard. When the shard's default database
happened to hold a same-named parameterized view the query instead returned a silently wrong
answer -- 3 rows where 6 is correct, with the failing shard contributing none and nothing on
stderr. Before ClickHouse#68978 a parameterized view became a TableNode, whose toASTIdentifier qualifies
from storage_id, so this path is the one that lost the database.

The initiator's database is the correct target. A parameterized view is expanded against the
initiator's catalog and storage_id can never lack a database, since
extractDatabaseAndTableNameForParameterizedView defaults it to the current database. The
cross-replication case that TableNode::toASTIdentifier guards against is expressed by
Cluster::maybeCrossReplication, which buildQueryTreeForShard consults to hand TableNode a
deliberately empty database; no cluster or context reaches toASTImpl, so that signal cannot apply
here.

The parameterized-view discriminator is required rather than decorative: a regular table function
also carries a real storage id, so unconditional qualification would render numbers(3) as
system.numbers(3). Qualification is also skipped unless the result is a two-part identifier,
because extractDatabaseAndTableNameForParameterizedView resolves only one or two parts -- a
database whose name contains a dot has no resolvable qualified spelling and is left as it is
today.

The change is confined to rendering, so query-tree identity is untouched: EXPLAIN QUERY TREE and
EXPLAIN SYNTAX are byte-identical before and after, which is why the name is not rewritten at
resolve time.

Closes ClickHouse#65318
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
The `DESCRIBE` over a `UNION ALL` of two parameterized views whose columns
have types `Int64` and `UInt64` relies on the common supertype being
`Variant(Int64, UInt64)`. This only holds when `use_variant_as_common_type`
is enabled; with it disabled the query fails with `NO_COMMON_TYPE`. Pin the
setting on that query so the test does not depend on the ambient value.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68978&sha=2f58adba21165a26c5b8684e369f2089c26fbfc6&name_0=PR&name_1=Stateless%20tests%20%28amd_llvm_coverage%2C%20old%20analyzer%2C%20s3%20storage%2C%20DatabaseReplicated%2C%20WasmEdge%2C%20parallel%29
PR: ClickHouse#68978

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
A parameterized view is resolved as a `TableFunctionNode` that wraps a real
`StorageView`. The planner skips access checks for `TableFunctionNode`,
because regular table functions are checked inside `ITableFunction::execute`.
For a parameterized view no `ITableFunction` runs, so `SELECT * FROM pv(...)`
could read the view without any `SELECT` grant.

Apply the same column-aware `SELECT` check that the underlying view would
receive as a `TableNode`. To do so, `checkAccessRights` is generalized to
take the storage, storage id and storage snapshot instead of a `TableNode`.

PR: ClickHouse#68978

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
Two fixes to `DESCRIBE pv(args...)`:

- Look up the parameterized view in the catalog before consulting the
  table-function factory, mirroring `Context::executeTableFunction`. Otherwise
  a view whose name collides with a built-in table function would never be
  described as a view, behaving differently from `SELECT * FROM pv(args...)`.

- Analyze the substituted query under the view's SQL-security-overridden
  context (`getSQLSecurityOverriddenContext`), matching execution via
  `Context::buildParameterizedViewStorage`. This way a user with `SHOW COLUMNS`
  on a `SQL SECURITY DEFINER` view but without direct grants on the inner
  tables can still describe it.

PR: ClickHouse#68978

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
Both tests exercise parameterized-view features that are implemented only in
the analyzer, but they ran with the analyzer disabled on the old-analyzer
stateless config and failed there:

- `03228_param_view_metadata_columns`: the `DESCRIBE` of a `UNION` of two
  parameterized views with `use_variant_as_common_type = 1` is expected to
  yield the common supertype `Variant(Int64, UInt64)`. The old interpreter
  does not honor `use_variant_as_common_type` here and throws
  `NO_COMMON_TYPE`. Pin `allow_experimental_analyzer = 1` for that query.

- `04324_parameterized_view_access`: honoring `SQL SECURITY DEFINER` for a
  parameterized view (so a grant on the view alone suffices, without a grant on
  the inner table) works only in the analyzer; the old interpreter still
  requires access to the inner table and returns `ACCESS_DENIED`. Pin
  `allow_experimental_analyzer = 1` only for that `SELECT`; the access-denial
  checks are valid for both interpreters and stay unpinned.

CI report: ClickHouse#68978

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
A column used in ORDER BY ... WITH FILL must not also be an INTERPOLATE
output. The validation in `FillingTransform` only compared the INTERPOLATE
output set against the sort description alias, which is empty for a constant
ORDER BY expression. Under the old analyzer a constant fill column and a
matching INTERPOLATE target are folded to the same source column, so the
conflict slipped through and the query aborted later with `Invalid number
of rows in Chunk` (`LOGICAL_ERROR`) instead of a clean
`INVALID_WITH_FILL_EXPRESSION` exception.

Also check the sort description column name, which holds the resolved name
of the constant, so the conflict is rejected up front.

Found by the AST fuzzer on ClickHouse#68978:

    SELECT 1024 AS a, a AS b ORDER BY 1 DESC NULLS FIRST
    WITH FILL STALENESS -2 INTERPOLATE (`a` AS b)

Report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=68978&sha=26b3af8d64543b2cd912305df751a31e967c03bf&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 20, 2026
PR ClickHouse#68978 stopped replacing a parameterized-view call with an
argument-less TableNode and now keeps it as a resolved
TableFunctionNode. That node-type flip is not behaviour-preserving: the
view stopped carrying a name through analysis, so two spellings that
work in 26.6 and 26.7 started throwing on master.

  SELECT pv.host_id FROM pv(tenants = ['t1']);
  -- Code: 47. Unknown expression or function identifier `pv.host_id`

  SELECT count() FROM local_data JOIN pv(tenants = ['t1']) USING (tenant_id);
  -- Code: 206. no alias for subquery or table function pv(...)

QueryAnalyzer::initializeTableExpressionData fills
AnalysisTableExpressionData per node type. Its table_node branch copies
database_name, table_name and table_expression_name from
getStorageID(); the table_function_node branch leaves the first two
empty. Empty is correct for a real table function, since numbers(3) has
no bindable name, but a parameterized view does have one:
TableFunctionNode::resolve stores the StorageID that
Context::buildParameterizedViewStorage built.

Both symptoms follow from that one empty pair.
IdentifierResolver::tryBindIdentifierToTableExpression binds pv.col by
comparing against exactly those two fields, so nothing binds. And
validateJoinTableExpressionWithoutAlias throws for TABLE_FUNCTION while
returning for TABLE; the rule exists because such expressions have no
name to qualify columns with, which is precisely the property a
parameterized view does have. They are separate carriers: with
joined_subquery_requires_alias = 0 the alias rows pass while the
qualified rows still fail, hence two hunks.

Populate the identity at the producer rather than special-casing each
consumer, and exempt a parameterized view from the un-aliased-join check
as a plain table already is. The discriminator is the one ClickHouse#68978 itself
added in PlannerJoinTree.cpp, so a regular table function cannot match:
view(), viewIfPermitted() and eval() all leave is_parameterized_view
false, and the only other TableFunctionNode::resolve call sites resolve
a StorageDummy or take a path that constructs no StorageView.

The alias-gate change is a deliberate semantic choice: a parameterized
view again behaves like a table for joined_subquery_requires_alias. It
restores released behaviour and is sound because the view now has a
bindable name, so colliding columns stay reachable as pv.col.

Master-only, in unreleased 26.8, so there is nothing to backport and no
setting or format changes.

The new test covers 15 previously working spellings, each verified to
fail on a ClickHouse#68978 build and pass with this change, plus four
must-not-change controls; two of them pin that a real table function
gains neither a bindable name nor an alias exemption. Deleting either
hunk reddens a disjoint set of rows.

The AST sent to a remote shard still renders the call without its
database, so a shard resolves it against its own default. That is a
different root cause in TableFunctionNode::toASTImpl and is tracked
separately.
pull Bot pushed a commit to SINHASantos/ClickHouse that referenced this pull request Sep 20, 2026
Third carrier of the ClickHouse#68978 regression, in
QueryAnalyzer::qualifyColumnNodesWithProjectionNames. The function derives
matcher qualification parts from four table-expression shapes: an alias, a
TableNode, a CTE QueryNode and a CTE UnionNode. A parameterized view is now a
TableFunctionNode, which matches none of them, so the parts vector stays empty
and every matcher-expanded column keeps its bare name.

This is part of the same regression rather than a pre-existing wart. On 26.7 a
parameterized view was a TableNode: QueryAnalyzer replaced the TableFunctionNode
with a fake_table_node, and TableNode's constructor initialises storage_id from
storage->getStorageID(). qualifyColumnNodesWithProjectionNames itself is
byte-identical on 26.7 and master, so 26.7 contributed {database, table} parts
through its TableNode branch and master contributes none. The gap only became
reachable through this PR's alias-gate hunk, which newly admits an un-aliased
parameterized-view join at all; before it such a query threw ALIAS_REQUIRED.

Contribute {database_name, table_name} for a parameterized-view
TableFunctionNode, mirroring the TableNode branch so the existing progressive
qualification loop can escalate col -> pv.col -> db.pv.col exactly as it does
for a table. The discriminator is byte-for-byte the one ClickHouse#68978 introduced in
PlannerJoinTree.cpp, including the null guard, since getStorage() returns
nullptr for an unresolved node while getStorageID() throws.

Also pin SET enable_analyzer = 1 in the test. The whole fix lives in the
query-tree analyzer, while the old analyzer CI jobs link users.d/analyzer.xml
and the randomized compatibility setting below 24.3 also reverts
allow_experimental_analyzer. On the legacy path a JOINed parameterized view is
not expanded at all, only the left table storage is, so the assertions would be
decided by a different code path. A session SET is used rather than a
no-old-analyzer tag because applyCompatibilitySetting skips any setting the
session changed manually, so one SET covers both routes without removing the
test from that lane.

Three DESCRIBE rows cover the new behaviour and one covers a real table
function, which must gain no qualifier. Deleting the new branch reddens only
those three rows.

This branch was successfully deployed

1 active deployment
staging - docs — 6a8d10d6 Deployed Jul 28, 2026 by mintlify[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

analyzer Issues and pull-requests related to new analyzer 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.

Parametrized view in WITH (constant expression) : Identifier cannot be resolved Issues with parametrized views and new analyzer/recent versions

6 participants