Skip to content

Allow using external tables with any queries in the interactive mode - #97091

Open
AVMusorin wants to merge 17 commits into
ClickHouse:masterfrom
AVMusorin:allow-external-tables-with-set
Open

AVMusorin wants to merge 17 commits into
ClickHouse:masterfrom
AVMusorin:allow-external-tables-with-set

Conversation

@AVMusorin

@AVMusorin AVMusorin commented Feb 16, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Improvement

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

Allow using external tables with any queries in the interactive mode

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)
chc --external --file=/tmp/test_data.csv --name=users --structure='id UInt32, name String' --format=CSV

:) set max_block_size=1

SET max_block_size = 1

Query id: df6e51c4-09bc-43e3-bfc9-f18fe6e538a5

Ok.

0 rows in set. Elapsed: 0.003 sec.

:) select count() from users

SELECT count()
FROM users

Query id: bbff5205-71f6-441b-b265-6607aa11e3d4

   ┌─count()─┐
1. │       2 │
   └─────────┘

1 row in set. Elapsed: 0.002 sec.

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

@Ergus Ergus self-assigned this Feb 19, 2026
@clickhouse-gh

clickhouse-gh Bot commented Feb 19, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ebaceca]

Summary: ✅


AI Review

Summary

This PR removes the client-side SELECT gate for interactive --external tables, tweaks the docs, and adds an integration test. The core contract is still broken: the client now uploads external tables before every interactive query, so unqualified statements can bind to the ephemeral uploaded table instead of the real table with the same name.

Findings
  • ❌ [src/Client/ClientBase.cpp:753; src/Interpreters/executeQuery.cpp:2671; src/Interpreters/Context.cpp:7990-8015; src/Interpreters/InterpreterInsertQuery.cpp:193-205; src/Interpreters/InterpreterDropQuery.cpp:156-160,383-408] Interactive --external tables now shadow real tables for write/drop statements. INSERT INTO users resolves the uploaded temporary users first, so inserted rows disappear with the query context instead of reaching default.users; DROP TABLE users / TRUNCATE TABLE users only remove or mutate the temporary table. Suggested fix: restrict interactive support to statement kinds that legitimately inspect external tables, or send/attach external tables only when the analyzed query actually references them.
  • ❌ [src/Client/ClientBase.cpp:753; src/Interpreters/InterpreterAlterQuery.cpp:421-427; src/Interpreters/InterpreterOptimizeQuery.cpp:49-50; src/Interpreters/InterpreterCheckQuery.cpp:428-433] The same shadowing leak reaches admin/mutation statements that were not covered by the existing threads. ALTER TABLE users, OPTIMIZE TABLE users, and CHECK TABLE users all resolve the uploaded temporary users before default.users, so interactive --external can divert maintenance or schema changes away from the permanent table. Suggested fix: same as above.
  • ❌ [tests/integration/test_external_tables_interactive_mode/test.py:80-92] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/97091#discussion_r3441084669] The new regression test now pins the unresolved SET upload path instead of proving it is fixed: it asserts that a missing external file still surfaces on SET. That makes the old bug part of the expected contract. Suggested fix: either short-circuit SET before sendExternalTables, or drop SET from the supported interactive statements and test for rejection instead.
  • 💡 [docs/reference/engines/table-engines/special/external-data.mdx:1-17] [dismissed by author -- https://github.com/ClickHouse/ClickHouse/pull/97091#discussion_r3441437593] The docs still describe external data as something sent "together with a SELECT query" and only show SELECT examples. The one-line mode update does not document the new interactive behavior or its limitations. Suggested fix: update the frontmatter/body wording and add at least one interactive example beyond SELECT.
Tests
  • ⚠️ There is still no focused interactive regression proving that unqualified write/admin statements are protected from external-table shadowing. The smallest useful coverage is a real default.users table plus --external --name=users, then INSERT, DROP / TRUNCATE, and one ALTER / OPTIMIZE / CHECK statement that must either hit the permanent table or be rejected explicitly.
  • ⚠️ There is still no test proving that SET is short-circuited. If SET is meant to stay supported, the missing-file case should succeed; if not, the test should assert the query is rejected before any file read.
Final Verdict

Changes requested.

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.90% 86.80% -0.10%
Functions 92.00% 92.00% +0.00%
Branches 79.30% 79.20% -0.10%

Changed lines: Changed C/C++ lines covered: 4/5 (80.00%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Feb 19, 2026
@Ergus Ergus added the can be tested Allows running workflows for external contributors label Feb 19, 2026
@Ergus

Ergus commented Feb 19, 2026

Copy link
Copy Markdown
Member

A bit concerned about potential security implications of this.

@AVMusorin

Copy link
Copy Markdown
Contributor Author

A bit concerned about potential security implications of this.

I can limit it to SELECT, SET and EXPLAIN. Otherwise it requires extra steps to debug queries that uses external tables with explain

@Ergus

Ergus commented Feb 19, 2026

Copy link
Copy Markdown
Member

Please merge with current master to trigger the CI again

@AVMusorin
AVMusorin force-pushed the allow-external-tables-with-set branch from 65e4494 to 350947c Compare February 19, 2026 17:43
@Ergus

Ergus commented Feb 19, 2026

Copy link
Copy Markdown
Member

Hi @AVMusorin please, once a PR starts reviews we recommend to avoid force pushes unless totally necessary to simplify reviews of subsequent changes ;)

Comment thread src/Client/ClientBase.cpp Outdated

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.

Looking a bit more into this change, this seems to suppress the exception but does not short-circuit this last call on every single non-SELECT query in interactive mode. Suppose a set. So the complete payload is re-uploaded anyways.

I think we must early return to avoid this somehow.

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.

I agree with the concern, but I don't think we should try to enumerate every query kind that may need external tables. Looks like the safe approach is to keep the general behavior correct and only short-circuit a small set of queries that are guaranteed not to resolve external tables, such as SET.

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.

@Ergus WDYT?

@Ergus

Ergus commented Apr 15, 2026

Copy link
Copy Markdown
Member

Hi @AVMusorin Any progress on this? DO you need any help or support from our side?

@@ -0,0 +1,66 @@
#!/usr/bin/expect -f

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.

Is it possible to make this test as pure sql+reference pair instead of .expect?

Or in the worst case an integration test?

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.

Hi @AVMusorin

Do you need any help with this?

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.

Is it possible to make this test as pure sql+reference pair instead of .expect?

No, because I want to test it in interactive mode

Or in the worst case an integration test?

Looks like yes, I found some useful helpers in the codebase

Comment thread src/Client/ClientBase.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 19, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

🟢 AI verdict: improvement — 3 query(s) improved out of 34 analysed

This sync PR changes only the command-line client's interactive-mode external-table handling (src/Client/ClientBase.cpp) plus a doc line and a new integration test — the server's query-execution hot path is untouched, so none of these per-query deltas can plausibly be caused by the PR. The flagged clickbench improvements (Q13/Q15/Q16/Q18/Q30/Q31) and the Q28 +7.4% regression are off-path and have been downgraded to not-sure as run-to-run variance. Three very large deltas (clickbench Q23 ×2.4 faster, tpch Q7 ×8.4 faster, Q8 ×2.2 faster) are locked by the large-delta trust override and left as improvements, but given the client-only diff they almost certainly reflect a baseline/environment difference rather than a real code effect.

clickbench

🟢 1 improved · ⚠️ 7 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 23 improvement 164 69 ×2.4 faster <0.0001 Locked by the large-delta trust override (×2.4 faster), but this client-only diff can't touch Q23's server path; the ×50 measurement spread points to baseline variance.
⚠️ 13 not_sure 422 339 -19.7% <0.0001 This PR only changes command-line client interactive-mode external-table handling; the server path Q13 executes is untouched, so this −19.7% is run-to-run variance.
⚠️ 15 not_sure 192 160 -16.7% <0.0001 The client-only interactive-mode fix cannot affect Q15's server execution; treat this −16.7% as noise, not a PR effect.
⚠️ 16 not_sure 734 632 -13.9% <0.0001 Server query execution is untouched by this CLI change, so this −13.9% is unrelated to the PR.
⚠️ 18 not_sure 1244 1109 -10.9% <0.0001 The diff only touches client external-table plumbing; Q18's −10.9% reflects run-to-run variance, not the PR.
⚠️ 28 not_sure 1051 1129 +7.4% <0.0001 The +7.4% regression can't come from a command-line client interactive-mode change; the server path is untouched, so this is noise.
⚠️ 30 not_sure 279 227 -18.6% <0.0001 Client-side interactive-mode fix does not reach Q30's server execution; this −18.6% is run-to-run variance.
⚠️ 31 not_sure 408 315 -22.8% <0.0001 Server execution is unchanged by this CLI-only diff, so Q31's −22.8% is unrelated to the PR.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

🟢 2 improved

Flagged queries (2 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
🟢 7 improvement 560 67 ×8.4 faster <0.0001 Locked by the large-delta override (×8.4 faster), yet the client-only interactive-mode change can't affect server execution; this most likely reflects a baseline difference, not the PR.
🟢 8 improvement 166 77 ×2.2 faster <0.0001 Locked by the large-delta override (×2.2 faster), but this diff only touches command-line client plumbing; the server path Q8 runs is untouched, so read this as baseline variance.

Change = percent below ×2; the ratio of medians (×N faster/slower) beyond, where percent understates the scale. q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 4caa9494-5f2c-4741-9d23-f4b35c5615a7
  • MIRAI run: 009b7e0f-d063-42eb-8bc0-5aa77371d856
  • PR check IDs:
    • clickbench_1988166_1787086180
    • clickbench_1988177_1787086177
    • clickbench_1988184_1787086177
    • tpch_adapted_1_official_1988196_1787086177
    • tpch_adapted_1_official_1988221_1787086177
    • tpch_adapted_1_official_1988235_1787086177

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

Thanks for waiting ;)
The change LGTM. Please merge the master branch to trigger the CI and try to get a green CI.

@AVMusorin

Copy link
Copy Markdown
Contributor Author

@Ergus everything seems nice except private sync

@Ergus

Ergus commented Jul 15, 2026

Copy link
Copy Markdown
Member

Hi @AVMusorin

Very thanks for the patience ;)

Yes the issue seems unrelated in private, but produced many tests failures there. We are restricting the CI conditions to merge so let's be good guys ;).

Please merge again with master, hopefully the error is fixed now. When done, please, remember to ping me here so I can check again. In case public CI fails and the error seems unrelated, just merge again (I know it is not a perfect system, but let's reduce the risk for potential errors).

Comment thread src/Client/ClientBase.cpp Outdated
const auto * select = parsed_query->as<ASTSelectWithUnionQuery>();
if (!select && !external_tables.empty())
throw Exception(ErrorCodes::BAD_ARGUMENTS, "External tables could be sent only with select query");
if (!select && !external_tables.empty() && !is_interactive)

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.

Allowing every interactive non-SELECT through this branch also means the external table now exists for unqualified DDL. With clickhouse-client --external --name=users ..., a later DETACH TABLE users or DROP TABLE users no longer targets the real default.users: Context::resolveStorageID prefers the just-uploaded external users first, and InterpreterDropQuery then routes the statement down the temporary-table path instead of the ordinary table path. In current master that means DETACH TABLE users starts throwing the temporary-table syntax error, while DROP / TRUNCATE never reach the real table. Please keep the interactive exemption to statement kinds that legitimately inspect external tables (DESCRIBE / EXPLAIN / similar), or only attach external tables when the current AST actually references them.

Comment thread src/Client/ClientBase.cpp
const auto * select = parsed_query->as<ASTSelectWithUnionQuery>();
bool has_external_data = !external_tables.empty() || !external_scalars.empty();
if (!select && has_external_data)
if (!select && has_external_data && !is_interactive)

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.

Allowing every interactive non-SELECT through this branch also enables mutating INSERTs against query-scoped external tables. executeQuery loads the uploaded external table before InterpreterInsertQuery::getTable resolves the destination, and that resolver still goes through Context::resolveStorageID, which prefers an external table in the current query context first. Concretely, start clickhouse-client --external --name=users ..., then run INSERT INTO users VALUES (...): the target resolves to the temporary external users, the insert succeeds there, and the rows disappear with the query context instead of reaching default.users. Please either keep the interactive exemption away from write statements, or add a collision check for unqualified write targets before allowing this path.

@clickhouse-gh

clickhouse-gh Bot commented Jul 22, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 86.20% 86.20% +0.00%
Functions 92.00% 92.00% +0.00%
Branches 78.30% 78.30% +0.00%

Changed lines: Changed C/C++ lines covered: 4/5 (80.00%) · Uncovered code

Full report · Diff report

`master` moved the documentation from the Docusaurus tree under
`docs/en/**/*.md` to the Mintlify tree at `docs/**/*.mdx`, deleting every
file this branch edits. The edits are replayed at the new paths:

- `docs/en/engines/table-engines/special/external-data.md` -> `docs/reference/engines/table-engines/special/external-data.mdx`
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Dear @Ergus, you haven't been active on this PR for 30 days. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

Comment thread src/Client/ClientBase.cpp
const auto * select = parsed_query->as<ASTSelectWithUnionQuery>();
bool has_external_data = !external_tables.empty() || !external_scalars.empty();
if (!select && has_external_data)
if (!select && has_external_data && !is_interactive)

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 leaves the interactive exemption too broad: once executeQuery loads the uploaded tables before interpretation, any unqualified statement that resolves its target with ResolveAll will prefer the temporary external table. INSERT/DROP already have threads, but the same applies to ALTER TABLE, OPTIMIZE TABLE, and CHECK TABLE (InterpreterAlterQuery::executeToTable, InterpreterOptimizeQuery::execute, InterpreterCheckQuery::executeImpl). For example, clickhouse-client --external --name=users ... followed by ALTER TABLE users COMMENT COLUMN id 'x' or OPTIMIZE TABLE users never reaches default.users; it hits the ephemeral uploaded users instead. Please keep this path to statement kinds that intentionally inspect external tables, or only attach external tables when the analyzed AST actually references them.

@clickhouse-gh

clickhouse-gh Bot commented Aug 18, 2026

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

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

✅ No significant changes.

Binary sizes
Binary Master PR Δ
programs/clickhouse-stripped 702.07 MiB 699.05 MiB -3.03 MiB (-0.43%)

Only the stripped binary is compared: the official master build keeps debug symbols while PR builds strip them, so the other binaries differ by construction.

Compile time of recompiled translation units

7 translation units recompiled, 17 s compile time in total, 7 of them have a recent master baseline.

Job report

@abashkeev abashkeev added the comp-cli clickhouse-client (interactive CLI) and client library. label Sep 3, 2026
@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026

This branch has not been deployed

No deployments
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-cli clickhouse-client (interactive CLI) and client library. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-improvement Pull request with some product improvements

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants