Skip to content

Add eval table function - #104396

Closed
niyue wants to merge 63 commits into
ClickHouse:masterfrom
niyue:feat/eval-table-func
Closed

niyue wants to merge 63 commits into
ClickHouse:masterfrom
niyue:feat/eval-table-func

Conversation

@niyue

@niyue niyue commented May 8, 2026

Copy link
Copy Markdown
Contributor

Description

  • This PR addresses Table function eval #101293
  • Add a table function eval for constructing a query from a constant expression or another SELECT query.

Changelog category (leave one):

  • Experimental Feature

Changelog entry:

  • Add experimental table function eval, which evaluates a constant expression or single-row SELECT query to a query string and executes the resulting single SELECT query. The feature is disabled by default and can be enabled with setting allow_experimental_eval_table_function.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

@niyue niyue mentioned this pull request May 8, 2026
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 8, 2026
@clickhouse-gh

clickhouse-gh Bot commented May 8, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [056b8a4]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DBReplicated, WasmEdge, parallel, 3/3) FAIL
04210_eval_table_function FAIL cidb
Integration tests (amd_asan_ubsan, db disk, old analyzer, 3/6) FAIL
test_replicated_database/test.py::test_replicated_table_structure_alter FAIL cidb

AI Review

Summary

This PR adds the experimental eval table function and wires it into distributed execution, view-style analysis, and both analyzer modes. The remaining issues are both old-analyzer compatibility regressions around remote(...) named-collection overrides, so the feature contract is still not met on one supported execution path.

Findings

⚠️ Majors

  • [src/TableFunctions/TableFunctionRemote.cpp:117] The SQL-UDF compatibility fix for remote(..., database = eval(...)) only updates the analyzer metadata helper, but the old-analyzer execution path still goes through TableFunctionRemote::parseArguments on the raw AST and keeps the name-only isTableFunctionName check. SELECT count() FROM remote(remote_eval_scalar, database = eval(1)) SETTINGS enable_analyzer = 0 can still reinterpret the SQL UDF as the experimental table function and fail before the RHS is folded.

  • [src/Interpreters/ApplyWithSubqueryVisitor.cpp:104] The old-analyzer WITH-literal substitution for named-collection overrides still stops at the wrapper function itself. ASTFunction::children only contains the ASTExpressionList, so equals(database, eval(q)) never descends to the nested eval(q). WITH 'SELECT ...' AS q SELECT * FROM remote(remote_eval, database = eval(q)) SETTINGS allow_experimental_eval_table_function = 1, enable_analyzer = 0 can still ship an unresolved q to the shard.

Final Verdict

Status: ⚠️ Request changes

Minimum required actions: fix the old-analyzer named-collection override paths in TableFunctionRemote::parseArguments and ApplyWithSubqueryVisitor, and cover both with focused regressions.

@clickhouse-gh clickhouse-gh Bot added the pr-experimental Experimental Feature label May 8, 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.

The rest LGTM

@alexey-milovidov alexey-milovidov self-assigned this May 8, 2026
@niyue
niyue force-pushed the feat/eval-table-func branch 2 times, most recently from 962cf52 to 003efb1 Compare May 9, 2026 02:07
@niyue

niyue commented May 9, 2026

Copy link
Copy Markdown
Contributor Author

Hi @alexey-milovidov,

I've addressed the review comments above. The CI is still failing, but the remaining failed tests appear to be unrelated to this change. Could you please take another look when you have a moment? Thanks.

@niyue
niyue force-pushed the feat/eval-table-func branch from 003efb1 to 5f730c6 Compare May 9, 2026 13:16
niyue added 3 commits May 16, 2026 23:20
…n or a subquery returning single string row.
Run the normal set-operation normalization visitors on the generated `SELECT` before passing it to `StorageView`.

This keeps generated `UNION ALL`, `UNION DISTINCT`, `INTERSECT`, and `EXCEPT` queries on the same path as regular queries and avoids planner exceptions from `UNION_DEFAULT`.
…ntalSettings`, add `eval` to the aspell dictionary, and make nested `eval` detection use a case-sensitive comparison.
@niyue
niyue force-pushed the feat/eval-table-func branch from 5f730c6 to 86e74bb Compare May 16, 2026 15:24
Allow `StorageView` to assign a temporary table identifier for the `eval` table function before replacing it with the generated subquery. This avoids a `LOGICAL_ERROR` from `StorageView::replaceWithSubquery` for queries such as `SELECT * FROM eval(...)`.
Avoid resolving nested `eval` table function arguments on the initiator when they are used under `remote` or `cluster`. Like `view`, `eval` can generate a `SELECT` that references tables available only on shards.

Reuse the `view` distributed rewrite path for table functions that expose an inner `SELECT`, and add an integration regression test for a remote-only table.

Addresses reviewer feedback on ClickHouse#104396 (comment)
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
Permit `eval(SELECT ...)` in `QueryNormalizer` for the old analyzer path, matching the parser and `TableFunctionEval` behavior.

Add a stateless regression test with `enable_analyzer` disabled.

Addresses reviewer feedback on ClickHouse#104396 (comment)
Document that `eval` is normally analyzed on the initiator, but nested usage under `remote` or `cluster` is resolved on remote shards.

Addresses reviewer feedback on ClickHouse#104396 (comment)
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

alexey-milovidov and others added 6 commits May 17, 2026 20:54
Drop the old `kql` table function layer left in `ExpressionListParsers.cpp` after merging `master`. The layer referenced removed `ParserKQLTableFunction` code and broke the parser build, while current `master` parses `kql` through the normal table function path.

Issue: ClickHouse#101293

Tests:
- `ninja -C build clickhouse_parsers`
- `git diff --check -- src/Parsers/ExpressionListParsers.cpp`
- `build/programs/clickhouse local --multiquery < tests/queries/0_stateless/04241_kql_array_index_no_oom.sql`
# Conflicts:
#	ci/jobs/scripts/check_style/aspell-ignore/en/aspell-dict.txt
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master into the branch to resolve the merge conflict — the branch had fallen ~1216 commits behind and GitHub marked it CONFLICTING/DIRTY, which blocks merging.

This is a pure master merge with no code changes: the net diff versus master is still exactly the eval feature (36 files, all eval sources/tests/docs), and the setting allow_experimental_eval_table_function remains in the 26.7 section of SettingsChangesHistory (dev version is still 26.7, so 02995_new_settings_history stays green). I verified all 17 changed translation units still compile against the merged tree with -fsyntax-only — no API drift from the master churn.

The two Stress test (amd_tsan/arm_tsan) failures on the previous run were the chronic Hung-check flake (#107941), not related to this PR. Fresh CI is now running on the up-to-date base.

Comment thread src/Storages/StorageView.cpp Resolved
alexey-milovidov and others added 2 commits July 6, 2026 15:30
The `eval` table function builds its inner `StorageView` from a generated
query that may pin its own `SETTINGS enable_analyzer = ...`, captured in the
view's inner query context. `TableFunctionEval::getActualTableStructure`
infers the structure with that inner context, and `StorageView::readImpl`
executes the inner query with the same analyzer mode.

With `analyzer_inline_views = 1`, `QueryAnalyzer::inlineViewSubqueryIfNeeded`
rebuilt and re-resolved the view with the new analyzer using the outer
scope's settings, ignoring the inner analyzer mode. When the two differed
(for example an `eval` query pinned to the old analyzer under a new-analyzer
outer query), the inlined subquery produced a different column name than the
inferred structure (`abs(a)` vs `abs(1)`), so the inlined result disagreed
with the inferred schema.

Skip inlining for views whose inner analyzer mode differs from the outer
one, falling back to the non-inlined read path (`readImpl`), which already
honors the inner context. Ordinary views have no inner query context and are
unaffected.

Addresses the review on `src/Storages/StorageView.cpp:130`.
ClickHouse#104396

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

Copy link
Copy Markdown
Member

Updating the branch to fix the 04001_join_reorder_through_expression test, which was broken today in master.

alexey-milovidov and others added 5 commits July 7, 2026 09:28
Wrap the generated query with an explicit column alias list derived from
the inferred schema, so anonymous generated projection names stay stable
between schema inference and execution.
Teach `remote` to mark named-collection `database` and `db` overrides
whose value is a table function as table-expression arguments.
Resolve `eval` expression arguments through those wrappers before sending
the query to shards, so outer `WITH` aliases are preserved for both AST
and serialized-plan distributed paths.
Merge `niyue/feat/eval-table-func` into the local feature branch while
preserving the already-pushed remote history. Resolve the overlapping
`QueryAnalyzer` changes so shard-side wrappers and named-collection
overrides both resolve nested `eval` expression arguments before shipping
table-function ASTs to remote shards.
Keep the nested `eval` table-function guard in table-expression mode while
walking wrapper expressions such as `equals(database, eval(...))`. This prevents
generated `eval` queries from bypassing the nested `eval` restriction through
`remote` named collection overrides.
niyue added 2 commits July 10, 2026 08:08
Build a settings-aware context before analyzing or executing the input
`SELECT` query passed to the `eval` table function. This keeps interpreter
selection consistent with the input query's own `SETTINGS` and reuses the same
helper for generated query schema inference and execution.
Use table-function argument metadata when traversing nested table functions, so ordinary scalar arguments such as a `remote` sharding key retain normal alias resolution. Add an integration regression for a scalar SQL UDF named `eval`.
return false;

const auto * value_function = function_args_expr->children[1]->as<ASTFunction>();
return value_function && TableFunctionFactory::instance().isTableFunctionName(value_function->name);

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.

database = <expr> on named-collection remote(...) used to be a constant-expression slot. This name-only TableFunctionFactory::instance().isTableFunctionName(...) check reintroduces the scalar-function ambiguity that the rest of the PR had to unwind for eval: a pre-existing SQL UDF such as CREATE FUNCTION eval AS x -> 'system' is now reinterpreted as a table-function override, so remote(remote_nc, database = eval(1)) stops evaluating the RHS as a database name and can start failing with Table function \eval` is disabledeven though the query never intended to use the experimental table function. Because the same helper also drivesgetTableExpressionArgumentIndexes`, the analyzer/distributed path follows the table-function branch too.

This needs a compatibility story that preserves the old constant-expression behavior for scalar/UDF calls whose names collide with table functions.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed. Handle scalar function eval as well

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 still is not fixed under the old analyzer. The new UserDefinedSQLFunctionFactory guard only affects isDatabaseOverrideWithTableFunctionValue, but TableFunctionRemote::parseArguments still has the name-only branch at src/TableFunctions/TableFunctionRemote.cpp:117-119:

if (function && TableFunctionFactory::instance().isTableFunctionName(function->name)) remote_table_function_ptr = arg_ast;

Context::executeTableFunction still calls TableFunctionFactory::get on the raw AST under enable_analyzer = 0, so SELECT count() FROM remote(remote_eval_scalar, database = eval(1)) SETTINGS enable_analyzer = 0 reinterprets the SQL UDF as the experimental table function before the RHS can be folded.

Treat a named-collection `database` override as a constant expression when its function name is also registered as a SQL UDF. This prevents a scalar UDF named `eval` from being interpreted as the experimental `eval` table function.
{
/// Named collection overrides wrap their table expression in a scalar function such as `equals`.
for (auto & child : function->children)
substituteWithLiteralsInEvalTableFunction(child, literals, context);

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.

Under enable_analyzer = 0 this still misses the named-collection wrapper case. ASTFunction::children only contains the ASTExpressionList, so the recursion stops at equals(database, ...) and never reaches the nested eval(q). A query like WITH 'SELECT x FROM remote_only_eval_table' AS q SELECT * FROM remote(remote_eval, database = eval(q)) SETTINGS allow_experimental_eval_table_function = 1, enable_analyzer = 0 still sends eval(q) without substituting q, so the shard sees an unresolved identifier.

Can we recurse through function->arguments->children here (the same way checkNoNestedEvalTableFunction does) and add an old-analyzer regression for the named-collection override form?

@clickhouse-gh

clickhouse-gh Bot commented Jul 10, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

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

Changed lines: Changed C/C++ lines covered: 527/569 (92.62%) · Uncovered code

Full report · Diff report

@alexey-milovidov

Copy link
Copy Markdown
Member

Let's find ways to simplify this code. What if:

  • we don't support it with the old analyzer;
  • we don't allow using eval nested inside other table functions;
  • we don't substitute WITH-defined names into eval'd queries, so the eval queries have to be self-contained.

Let's submit another PR aimed at maximum simplification of the implementation.

@alexey-milovidov alexey-milovidov added the hold Skip for auto-updating. label Jul 12, 2026
pull Bot pushed a commit to AKJUS/ClickHouse that referenced this pull request Jul 13, 2026
A maximally simplified implementation of the `eval` table function:
the argument is a constant expression evaluated to a query string, and
the generated `SELECT` query is wrapped into `StorageView`, same as the
`view` table function. `eval(SELECT ...)` is syntactic sugar for a scalar
subquery argument `eval((SELECT ...))`. The old analyzer is not supported,
`eval` cannot be used as an argument of another table function, and the
generated query must be self-contained.

Requested in ClickHouse#104396 (comment)
Closes ClickHouse#101293

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
A maximally simplified implementation of the `eval` table function:
the argument is a constant expression evaluated to a query string, and
the generated `SELECT` query is wrapped into `StorageView`, same as the
`view` table function. `eval(SELECT ...)` is syntactic sugar for a scalar
subquery argument `eval((SELECT ...))`. The old analyzer is not supported,
`eval` cannot be used as an argument of another table function, and the
generated query must be self-contained.

Requested in ClickHouse#104396 (comment)
Closes ClickHouse#101293

Co-Authored-By: Claude Fable 5 <[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 hold Skip for auto-updating. pr-experimental Experimental Feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants