Skip to content

Do not leave an orphan table when CREATE ... AS SELECT is denied - #108048

Merged
alexey-milovidov merged 30 commits into
masterfrom
fix-create-as-select-subquery-access
Jul 19, 2026
Merged

alexey-milovidov merged 30 commits into
masterfrom
fix-create-as-select-subquery-access

Conversation

@alexey-milovidov

@alexey-milovidov alexey-milovidov commented Jun 21, 2026 •

Copy link
Copy Markdown
Member

A CREATE TABLE ... AS SELECT that is denied because the user lacks SELECT on a table referenced by a subquery used to leave an empty orphan table behind. The table was created before the populating INSERT SELECT ran, and the access check fired only during that INSERT SELECT — after the table already existed. A retry then reported TABLE_ALREADY_EXISTS instead of the access error.

This is fixed for Atomic databases by reusing the same create-temporary-then-publish machinery that CREATE OR REPLACE already uses (doCreateOrReplaceTable): a plain CREATE TABLE ... AS SELECT now creates the table under a temporary name, runs the populating INSERT SELECT into it, and only then atomically publishes it under the final name with a RENAME. If the SELECT is denied — or the populate fails for any other reason — the temporary table is dropped, so a denied query leaves no orphan behind. The access check is now performed by the real INSERT SELECT (executed exactly once), so it is column-aware and also covers tables referenced from IN/scalar subqueries, not only FROM-position ones, with no access-check code of its own. As a side effect the table becomes visible only once it has been fully populated.

For non-Atomic databases (e.g. Ordinary, getUUID() == Nil) the previous behavior is kept: the table is created first and an orphan is left if the INSERT SELECT fails.

Materialized/window views with POPULATE are out of scope of this change — they can own an inner table and carry source-view dependencies, which the plain-table rename does not cover — so they keep the previous behavior.

This replaces the earlier up-front access pre-check, which required a second, full query-plan build of the SELECT (executing scalar subqueries a second time) and spread access-check logic across getTablePropertiesAndNormalizeCreateQuery, doCreateTable and a helper.

Closes: #26746

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Fixed CREATE TABLE ... AS SELECT on Atomic databases leaving an empty table behind when the query fails — for example when the user has no access to a table referenced from a subquery. Previously a retry reported that the table already exists instead of the original error. The table is now created via a temporary table and becomes visible only after it has been fully populated.

`CREATE TABLE ... AS SELECT` creates the table first and then populates it
with an `INSERT SELECT`. When the user lacks `SELECT` on a table referenced
from a `WHERE ... IN (SELECT ...)` (or another non-`FROM` subquery), the
access check fired only during that `INSERT SELECT`, after the table had
already been created, leaving an empty orphan table behind. A retry then
reported `TABLE_ALREADY_EXISTS` instead of the access error.

The up-front access pre-check (`checkSubqueryTableAccess`) only covers
subqueries that appear as `FROM`-position (join-tree) table expressions, so
tables referenced from `IN`/scalar subqueries of the outer query were missed.
It also used a whole-table `SELECT` check that wrongly denied valid
column-level grants.

For queries that populate the table immediately
(`isCreateQueryWithImmediateInsertSelect`), build the full query plan of the
`SELECT` before the table is created, using the same `SelectQueryOptions` as
the subsequent `INSERT SELECT`. This runs the planner's complete, column-aware
access checks before any side effect, so a denied query leaves no table behind
and column-level grants are honored.

Closes: #26746

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 21, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [c6e7196]

Summary: ✅


AI Review

Summary

This PR reroutes plain CREATE TABLE ... AS SELECT on Atomic databases through the existing temporary-create / populate / publish machinery so a denied or otherwise failing populate no longer leaves an orphan table behind. On the current head, the previously risky corners I would have expected here are covered: IF NOT EXISTS no-op ordering, detached-name and dictionary-name parity with doCreateTable, temp-table cleanup under drop-size guards, table-scoped INSERT grants, query_log temp-name scrubbing, and the now-documented destination-visibility change during populate. I did not find any remaining actionable correctness, safety, or compatibility issues in the current diff.

Missing context / blind spots
  • ⚠️ I did not replay the concurrent DDL interleavings locally; confidence there comes from code-path tracing plus the focused regression coverage already added in the PR. A failpoint-style test would be the next step if we wanted to harden those races further.
Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Jun 21, 2026
alexey-milovidov and others added 6 commits June 21, 2026 23:17
…lumn-level grant)

The new test `04404_create_table_as_select_subquery_access` failed in `Fast test`
because the test user was not granted `TABLE ENGINE ON Memory`, which is required
in that CI profile. The success path (the `CREATE TABLE ... AS SELECT` run after
`SELECT` on `t2` is granted) was therefore denied with `it's necessary to have
the grant TABLE ENGINE ON Memory`, so `dst` was never created and the final
`DROP TABLE dst` failed with `UNKNOWN_TABLE`. The denied paths were unaffected
because the new subquery access pre-check throws `ACCESS_DENIED` on `t2` before
the engine grant is checked.

Also address the review feedback on the test:
- Force `enable_analyzer = 1` on the `CREATE` statements: the fix only applies in
  the analyzer code path, so the old-analyzer profile would not exercise it.
- Give `t2` an extra unused column and grant only `SELECT(y)` on the success path,
  so the test proves the up-front check is column-aware (the old whole-table
  pre-check would have rejected this valid column-level grant).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108048&sha=2feec2f15732a0073965dc2d0efb76b002963bea&name_0=PR&name_1=Fast%20test
PR: #108048

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The up-front access pre-check that prevents `CREATE TABLE ... AS SELECT`
from leaving an orphan table behind only ran in the column-inference
branch (`else if (create.select)`), so a query with an explicit column
list - e.g. `CREATE TABLE dst (y Int) ENGINE = Memory AS SELECT y FROM t0
WHERE y IN (SELECT y FROM t2)` - went through the `create.columns_list`
branch instead, never built the full query plan, and still created the
table before the denied subquery access was discovered in the populating
`INSERT SELECT`.

Move the full-plan pre-check to the top of
`getTablePropertiesAndNormalizeCreateQuery`, before any branch, so it runs
for every `isCreateQueryWithImmediateInsertSelect` form (inferred or
explicit columns, and materialized/window views with `POPULATE`). The
check now uses `getContext()` - the same context the subsequent
`INSERT SELECT` uses in `fillTableIfNeeded` - so it mirrors that query
plan exactly; the lighter `checkSubqueryTableAccess` is kept for plain
view definitions that have no immediate insert.

Extend the regression test to cover the explicit-column form, which would
still leave an orphan table behind without this change.

Addresses the review on the PR:
#108048

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…cess' into fix-create-as-select-subquery-access
alexey-milovidov and others added 2 commits June 30, 2026 02:41
…rtion table

Moving the `CREATE ... AS SELECT` access pre-check to cover explicit column
lists (commit dedd2dc) regressed `03753_infer_schema_from_insert_table`:
a query like `CREATE TABLE t (a Int32) AS SELECT * FROM file('x.bin', RowBinary)`
failed with `RowBinary file format doesn't support schema inference`
(BAD_ARGUMENTS).

The pre-check built the `SELECT` query plan in isolation, before the table
existed and without an insertion table in the context. The subsequent real
`INSERT SELECT` (see `fillTableIfNeeded`) sets the just-created table as the
insertion table, which lets table functions in the `SELECT` infer their
structure from the target table's columns
(`use_structure_from_insertion_table_in_table_functions`). Without that, a
`RowBinary` source - which cannot infer its own schema - has no structure to
fall back on, so the pre-check threw an error the real insert would never hit.
That contradicted the pre-check's own contract of mirroring the insert exactly.

Make the pre-check faithfully mirror the `INSERT SELECT`: provide the same
insertion table columns description (the structure we just computed, which is
what the table will have) on a copy of the context, with the same
`SelectQueryOptions(QueryProcessingStage::Complete, subquery_depth = 1)` as
`InterpreterInsertQuery`. The check now lives after the column structure is
known (so it can supply it) but still before the table is created, and continues
to cover every `isCreateQueryWithImmediateInsertSelect()` form.

CI report (Fast test):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108048&sha=db51f546c1f7e32da51b2d59c61324d67c208e3f&name_0=PR&name_1=Fast%20test
PR: #108048

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ias application

The orphan-table access pre-check builds the full query plan of the `SELECT`
before the table is created. It must run after the view's column alias list has
been applied to the `SELECT`; otherwise a `POPULATE` materialized view whose
`ORDER BY` references a column alias - e.g.
`CREATE MATERIALIZED VIEW mv (x) ENGINE = Memory POPULATE AS SELECT y FROM src ORDER BY x` -
would be planned against the un-aliased `SELECT` and throw `UNKNOWN_IDENTIFIER`
before the view could be created.

This test passes on master (which has no such pre-check) and guards against
re-introducing the pre-check above the alias rewrite.

PR: #108048

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The orphan-table access pre-check (a full query plan of the populating
`SELECT`, built before the table is created) ran unconditionally for every
`isCreateQueryWithImmediateInsertSelect` form. For `CREATE TABLE IF NOT EXISTS
... AS SELECT` whose target already exists this is wrong: `doCreateTable`
returns false and `execute` skips `fillTableIfNeeded`, so the populating
`INSERT SELECT` never runs and the `SELECT` is a no-op against the untouched
existing table. Running the pre-check there turned the no-op into an
access-checked `SELECT`, so a user lacking `SELECT` on a table referenced from
a subquery got a spurious `ACCESS_DENIED` even though the existing table would
be left untouched.

Add `createIfNotExistsResolvesToExistingTable`, mirroring the two
`if_not_exists` early-returns of `doCreateTable` (temporary tables via
`tryResolveStorageID(..., ResolveExternal)`, regular tables via
`database->isTableExist`), and skip the pre-check when it holds.

The pre-check still runs for `IF NOT EXISTS` when the table does not yet exist
(the orphan-table fix still applies there).

Extends `04418_create_table_as_select_subquery_access` with both cases: a
no-op `CREATE TABLE IF NOT EXISTS dst ... AS SELECT` on an existing table must
succeed and leave it unchanged even though a referenced table is denied, while
the same statement for a missing table must still be denied and leave no orphan.

Addresses the review on #108048

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

Copy link
Copy Markdown
Member Author

Addressed the sole blocking review item (the clickhouse-gh thread on InterpreterCreateQuery.cpp and the AI Review ⚠️ Request changes verdict, both pointing at the same issue).

Fix (commit 0bcedbf2803): the orphan-table access pre-check no longer runs when CREATE TABLE IF NOT EXISTS ... AS SELECT resolves to an already-existing table. In that case doCreateTable returns false and execute skips fillTableIfNeeded, so the populating INSERT SELECT never runs and the SELECT is a no-op against the untouched table — running the pre-check there produced a spurious ACCESS_DENIED on a source table. The new helper createIfNotExistsResolvesToExistingTable mirrors doCreateTable's two if_not_exists early-returns exactly (temporary via tryResolveStorageID(..., ResolveExternal), regular via database->isTableExist). The pre-check still runs for IF NOT EXISTS when the table does not yet exist.

Test: extended 04418_create_table_as_select_subquery_access with both cases the AI Review asked for — a no-op CREATE TABLE IF NOT EXISTS dst ... AS SELECT on an existing table succeeds and leaves it unchanged even though a subquery source is denied, and the same statement for a missing table is still ACCESS_DENIED and leaves no orphan. Built and ran 04418 (+ 04421) locally against a freshly-linked server — both pass, output matches the references exactly.

CI reds — all unrelated flakes, none caused by this PR:

  • Stress test (amd_tsan) / Stress test (arm_tsan) — Hung check failed, possible deadlock found, CI-auto-linked to Hung check failed, possible deadlock found #107941.
  • Stress test (arm_ubsan) — UndefinedBehaviorSanitizer (STID: 0250-4a9f), a signed-integer overflow in DateLUTImpl.h:1148 (values.date + time) reached from a fuzzed date function during query analysis. This PR does not touch DateLUTImpl; CIDB shows the same STID hitting 7 unrelated PRs in the last two days (100391, 104657, 108345, 108765, 108835, 108084 + this one) — a master-wide AST-fuzzer flake.

This was generated by Claude Code.

alexey-milovidov and others added 2 commits June 30, 2026 23:58
…rent DDL

Addresses review feedback on the orphan-table fix: the `IF NOT EXISTS` skip
of the access pre-check was decided outside the table DDL guard, so a
concurrent DROP between that decision and `doCreateTable` could let the table
be created and `fillTableIfNeeded` run the denied SELECT, reopening the
orphan-table bug.

Extract the pre-check into `checkAccessForImmediateInsertSelectPopulate` and,
when `IF NOT EXISTS` resolves to an existing table in
`getTablePropertiesAndNormalizeCreateQuery`, only defer it (set
`deferred_as_select_access_check`) instead of skipping outright. `doCreateTable`
re-runs the pre-check under the DDL guard, before the table is created, when it
finds the table no longer exists -- so a denied source SELECT leaves no orphan
table even under concurrent DDL, while the genuine no-op still succeeds without
a spurious access error.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses review feedback: the no-op `CREATE TABLE IF NOT EXISTS ... AS SELECT`
case was only piped to `grep -F ACCESS_DENIED`, so any other failure (for
example `TABLE_ALREADY_EXISTS` or an analysis error) produced the same empty
output and the test passed silently. Capture the exit status and assert it is 0
(printing `succeeded`), keeping a separate assertion that `ACCESS_DENIED` is
absent, so the test actually proves the no-op success contract.

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

Copy link
Copy Markdown
Member Author

Addressed both items in the AI Review ⚠️ Request changes verdict (and the two clickhouse-gh threads), head now 5366fc746b1.

1. Race-free IF NOT EXISTS skip (commit 7a81a8ae432). The pre-check is extracted into checkAccessForImmediateInsertSelectPopulate. When IF NOT EXISTS resolves to an already-existing table, getTablePropertiesAndNormalizeCreateQuery no longer skips the check outright — it only defers it (sets deferred_as_select_access_check). doCreateTable re-runs the pre-check under the same DDL guard that protects the create/no-op decision, before the table is created, when it finds the table is in fact being created (i.e. the target was concurrently dropped after the unguarded existence check). So:

  • genuine no-op (IF NOT EXISTS, table still exists under the guard) → doCreateTable returns false before the re-check, no spurious ACCESS_DENIED;
  • concurrent DROP → the re-check fires under the guard, before creation, so a denied source SELECT leaves no orphan table;
  • the check runs exactly once in the create path (no redundant plan build).

2. Strengthened no-op test (commit 5366fc746b1). The no-op CREATE TABLE IF NOT EXISTS ... AS SELECT case now captures the client exit status and asserts it is 0 (prints succeeded), with a separate assertion that ACCESS_DENIED is absent. Previously it was only piped to grep -F ACCESS_DENIED, so any other failure (e.g. TABLE_ALREADY_EXISTS or an analysis error) produced the same empty output and passed silently.

Built locally and ran 04418_create_table_as_select_subquery_access + 04421_create_populate_view_alias_precheck against a freshly-linked server — both pass.

The two prior CI reds were both Hung check failed, possible deadlock found on Stress test (amd_tsan)/(arm_tsan) (CI-auto-linked to #107941, AST-fuzzer deadlock-detector flake), unrelated to this change.

This was generated by Claude Code.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

The sole CI red on head 5366fc746b1 is a known, unrelated flake, and the AI Review is now ✅ Approve.

Flake: Integration tests (amd_tsan, 4/6) → test_replicated_table_attach/test.py::test_startup_with_small_bg_pool_partitioned failed with QueryTimeoutExceedException: Client timed out! on INSERT INTO replicated_table_partitioned. This is tracked by the open flaky-test issue #101103 and is a low-frequency intermittent timeout (one failure each on 4 separate days over the last 30 — PRs #105962, #107442, #107566, and this one). It exercises replicated-table startup with a small background merge pool and has nothing to do with this change, which touches only InterpreterCreateQuery.cpp (CREATE ... AS SELECT access pre-check). Reran the failed job.

Other state: all review threads resolved; CH Inc sync is still PENDING (not failed). No code changes were needed.

This was generated by Claude Code.

@alexey-milovidov

Copy link
Copy Markdown
Member Author

Follow-up on head 5366fc746b1: the two items still open in my previous comment have both cleared, so the PR is now fully green and ready to merge.

Current CI: 156 checks SUCCESS, 18 SKIPPED, 0 failures; all four meta gates (CH Inc sync, Mergeable Check, PR, Style check) are SUCCESS. Merge state is MERGEABLE/CLEAN, AI Review is ✅ Approve, and there are no unresolved review threads. The branch is behind master by ~1200 commits but the merge-base is only ~1.5 days old and there are no conflicts, so no re-merge is needed.

This was generated by Claude Code.

StorageID(create.getDatabase(), create.getTable(), create.uuid),
/*column_names=*/std::nullopt,
std::make_shared<ColumnsDescription>(properties.columns));
InterpreterSelectQueryAnalyzer(create.select->clone(), check_context,

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Don't we worry about side effects or complex operations during the query plan building? Like scalar subqueries execution?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Addressed by the redesign: there is no longer a separate plan build for an access pre-check. The SELECT is planned and executed exactly once, by the real INSERT SELECT into the temporary table, so scalar subqueries run only once (as before this PR). The code this thread points at has been removed.

@alexey-milovidov alexey-milovidov left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Spreading the access check across the codebase and the duplicate plan build sounds scary.

Can we instead implement it as:

For Atomic-based databases it will create a temporary table, then insert, then make it persistent.

For non-Atomic-based databases we will not worry and keep the previous behavior of orphan table.

alexey-milovidov and others added 2 commits July 11, 2026 00:09
Rework the fix for issue #26746 (`CREATE TABLE ... AS SELECT` denied for
lack of access to a subquery-referenced table leaving an empty orphan
table) to avoid the up-front access pre-check, which required a second,
full query-plan build of the `SELECT` (executing scalar subqueries a
second time) and spread access-check logic across
`getTablePropertiesAndNormalizeCreateQuery`, `doCreateTable` and a helper.

A plain `CREATE TABLE ... AS SELECT` (no REPLACE) on an Atomic database
now reuses the same create-temporary-then-publish machinery as
`CREATE OR REPLACE` (`doCreateOrReplaceTable`): the table is created under
a temporary name, the populating `INSERT SELECT` runs into it, and it is
then atomically published under the final name with a `RENAME`. If the
`SELECT` is denied -- or the populate fails for any other reason -- the
temporary table is dropped, so no orphan is left behind, and the access
check is done by the real `INSERT SELECT` (column-aware, and covering
tables referenced from `IN`/scalar subqueries). For non-Atomic databases
the previous behavior is kept (the table is created first, orphan left on
failure). Materialized/window views with `POPULATE` are left out of the
temporary-table path for now and keep the previous behavior.

`doCreateOrReplaceTable` is generalized to also handle the plain-create
case: publish via a plain `RENAME` (fails if the target exists), handle
`IF NOT EXISTS` as a no-op both up front and on a concurrent-create race,
and skip the post-publish old-table drop.

The temporary table is an implementation detail, so renaming and dropping
it run with a full-access context derived from the global context (as inner
tables of a materialized view are dropped in
`InterpreterDropQuery::executeDropQuery`): a plain `CREATE TABLE ... AS
SELECT` only requires `CREATE` + `INSERT` (+ `SELECT` on the sources,
still checked by the populating `INSERT SELECT`, which runs as the user),
so the user is not required to hold `RENAME`/`DROP` on the temporary table.

Removed `checkAccessForImmediateInsertSelectPopulate`,
`createIfNotExistsResolvesToExistingTable`, the
`deferred_as_select_access_check` member, and the
`checkSubqueryTableAccess` special-casing.

Co-Authored-By: Claude Fable 5 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member Author

Reworked the fix along the lines you suggested — thanks, this is much cleaner.

Instead of the up-front access pre-check (which, as you noted, needed a second full query-plan build of the SELECT — executing scalar subqueries a second time — and spread access-check logic across getTablePropertiesAndNormalizeCreateQuery, doCreateTable and a helper), a plain CREATE TABLE ... AS SELECT on an Atomic database now goes through the same create-temporary-then-publish path that CREATE OR REPLACE already uses (doCreateOrReplaceTable):

  1. create the table under a temporary name;
  2. run the populating INSERT SELECT into it;
  3. atomically publish it under the final name with a RENAME (a plain rename that fails if the target already exists; IF NOT EXISTS is handled as a no-op both up front and on a concurrent-create race).

If the SELECT is denied — or the populate fails for any other reason — the temporary table is dropped, so no orphan is left behind. The access check is now done only by the real INSERT SELECT, executed exactly once, so it is column-aware and also covers tables referenced from IN/scalar subqueries, with no access-check code of its own. This directly answers the inline question about side effects during plan building: there is no longer a separate plan build, so scalar subqueries are executed once, by the insert, exactly as before this PR.

For non-Atomic databases the previous behavior is kept (the table is created first, orphan left on failure), as you proposed.

doCreateOrReplaceTable is generalized to also serve the plain-create case (publish via a plain RENAME instead of EXCHANGE; skip the post-publish old-table drop). Removed all the previous pre-check machinery: checkAccessForImmediateInsertSelectPopulate, createIfNotExistsResolvesToExistingTable, the deferred_as_select_access_check member, and the checkSubqueryTableAccess special-casing.

One scope note: materialized/window views with POPULATE are intentionally left out of the temporary-table path for now — they can own an inner table and carry source-view dependencies, which the plain-table rename does not cover — so they keep the previous behavior. Happy to extend the same approach to them in a follow-up if you'd like.

Also merged master (the branch was ~2 weeks behind).

This was generated by Claude Code.

…eate-only validation

The no-op over an existing table must succeed even when the new (unused)
definition would fail the cyclic table dependency check, and the plain
create must fail fast with `TABLE_ALREADY_EXISTS` from the same fast
path. When the table does not exist, a cyclic definition is still
rejected with `INFINITE_LOOP` and leaves no orphan table behind.

Co-Authored-By: Claude Fable 5 <[email protected]>
alexey-milovidov and others added 3 commits July 14, 2026 08:24
…TE ... AS SELECT

The plain `CREATE TABLE ... AS SELECT` temporary-table publish path in
`doCreateOrReplaceTable` had three shortcomings versus the ordinary
`doCreateTable` path it now stands in for:

* The up-front existence fast path only probed `isTableExist`, so a final
  name reserved by a detached / detached-permanently table (metadata file
  present, `isTableExist` false) was not caught before the populate. An
  `IF NOT EXISTS` create was then no longer a no-op -- it could run the
  `SELECT`, raise a source `ACCESS_DENIED`, or trigger scalar-subquery side
  effects -- and a plain create could surface a source-query failure instead
  of the existing detached-name error, before the final `RENAME` eventually
  discovered the collision. Mirror `doCreateTable`'s
  `checkMetadataFilenameAvailability` branch here, before any populate work.

* The fast path collapsed a name already used by a dictionary into
  `TABLE_ALREADY_EXISTS`. `doCreateTable` reports `DICTIONARY_ALREADY_EXISTS`
  for that case (see `02973_dictionary_table_exception_fix`); restore that
  error contract for the AS-select form.

* `removeQueryAccessInfoTable` (which strips the internal `_tmp_replace_*`
  name from `system.query_log` `tables`) ran only on the successful publish.
  The `IF NOT EXISTS` lost-race no-op and the generic exception path both
  returned/rethrew without scrubbing, and `executeQuery` copies the access
  info into the log for failed queries too, so a denied or failing
  `CREATE ... AS SELECT` leaked the meaningless internal name. Scrub it from a
  single helper on every exit after the populate may have touched the temp
  table.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…CreateTable

Covers the two existence-parity fixes: `CREATE TABLE ... AS SELECT` over an
existing dictionary name reports `DICTIONARY_ALREADY_EXISTS`, and a name
reserved by a detached-permanently table is handled before the populate --
`IF NOT EXISTS` is a no-op (the `SELECT`, guarded with `throwIf`, is never run)
and a plain create fails with the detached-name `TABLE_ALREADY_EXISTS` instead
of a source-query failure. The detached table is left intact and re-attachable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A `CREATE TABLE ... AS SELECT throwIf(1)` fails during the populating
`INSERT SELECT`, after the internal `_tmp_replace_*` target has been recorded
in the query's access info. The failed query must leave no orphan table and
must not leak the temporary name into `system.query_log` `tables`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
….. AS SELECT

Routing a plain `CREATE TABLE ... AS SELECT` on an Atomic database through
the temporary-table publish path means the final table name is only
registered by the publishing `RENAME`, so the populating `SELECT` runs while
the destination does not yet exist. A `SELECT` that references the
destination itself -- directly (`CREATE TABLE dst ... AS SELECT * FROM dst`,
which now fails with `UNKNOWN_TABLE`) or indirectly (e.g. via `system.tables`,
which no longer counts the not-yet-published table) -- therefore no longer
observes it as an already-created empty table, unlike the previous
create-then-populate order.

This narrow visibility change is an intentional consequence of the fix (the
table becomes visible only once fully populated) and was flagged in review.
Make it explicit with a code comment next to the routing decision and pin it
with a focused regression test
(`04547_create_as_select_destination_not_visible_during_populate`), which
also checks that a normal, non-self-referential `CREATE ... AS SELECT` is
unaffected.

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

clickhouse-gh Bot commented Jul 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.90% 85.80% -0.10%
Functions 92.70% 92.70% +0.00%
Branches 78.00% 78.00% +0.00%

Changed lines: Changed C/C++ lines covered: 127/140 (90.71%) · Uncovered code

Full report · Diff report

@clickhouse-gh

clickhouse-gh Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 38 queries analysed

The change is confined to the CREATE TABLE ... AS SELECT DDL publish path (create-temporary-then-rename, plus its access-check plumbing); it does not touch the query-execution hot path that a read-only ClickBench SELECT like Q15 runs. The -11.5% median shift on Q15 came with essentially unchanged CPU (2593.6 vs 2606.6 ms), which is the signature of page-cache/IO variance rather than a real effect, and the deterministic envelope check correctly kept it as no_change. No genuine performance impact is attributable to this PR.

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: e78249c9-5f43-45ed-aedb-1778bc734532
  • MIRAI run: c9d33767-c7e9-4862-b4da-5a36572f9831
  • PR check IDs:
    • clickbench_147080_1784336359
    • clickbench_147093_1784336359
    • clickbench_147099_1784336359
    • tpch_adapted_1_official_147105_1784336359
    • tpch_adapted_1_official_147116_1784336359
    • tpch_adapted_1_official_147128_1784336359

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jul 19, 2026
Merged via the queue into master with commit 696bbe0 Jul 19, 2026
513 of 518 checks passed
@alexey-milovidov
alexey-milovidov deleted the fix-create-as-select-subquery-access branch July 19, 2026 02:12
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jul 19, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lumn-level grant)

The new test `04404_create_table_as_select_subquery_access` failed in `Fast test`
because the test user was not granted `TABLE ENGINE ON Memory`, which is required
in that CI profile. The success path (the `CREATE TABLE ... AS SELECT` run after
`SELECT` on `t2` is granted) was therefore denied with `it's necessary to have
the grant TABLE ENGINE ON Memory`, so `dst` was never created and the final
`DROP TABLE dst` failed with `UNKNOWN_TABLE`. The denied paths were unaffected
because the new subquery access pre-check throws `ACCESS_DENIED` on `t2` before
the engine grant is checked.

Also address the review feedback on the test:
- Force `enable_analyzer = 1` on the `CREATE` statements: the fix only applies in
  the analyzer code path, so the old-analyzer profile would not exercise it.
- Give `t2` an extra unused column and grant only `SELECT(y)` on the success path,
  so the test proves the up-front check is column-aware (the old whole-table
  pre-check would have rejected this valid column-level grant).

CI report: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108048&sha=2feec2f15732a0073965dc2d0efb76b002963bea&name_0=PR&name_1=Fast%20test
PR: ClickHouse#108048

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
The up-front access pre-check that prevents `CREATE TABLE ... AS SELECT`
from leaving an orphan table behind only ran in the column-inference
branch (`else if (create.select)`), so a query with an explicit column
list - e.g. `CREATE TABLE dst (y Int) ENGINE = Memory AS SELECT y FROM t0
WHERE y IN (SELECT y FROM t2)` - went through the `create.columns_list`
branch instead, never built the full query plan, and still created the
table before the denied subquery access was discovered in the populating
`INSERT SELECT`.

Move the full-plan pre-check to the top of
`getTablePropertiesAndNormalizeCreateQuery`, before any branch, so it runs
for every `isCreateQueryWithImmediateInsertSelect` form (inferred or
explicit columns, and materialized/window views with `POPULATE`). The
check now uses `getContext()` - the same context the subsequent
`INSERT SELECT` uses in `fillTableIfNeeded` - so it mirrors that query
plan exactly; the lighter `checkSubqueryTableAccess` is kept for plain
view definitions that have no immediate insert.

Extend the regression test to cover the explicit-column form, which would
still leave an orphan table behind without this change.

Addresses the review on the PR:
ClickHouse#108048

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
…rtion table

Moving the `CREATE ... AS SELECT` access pre-check to cover explicit column
lists (commit dedd2dc) regressed `03753_infer_schema_from_insert_table`:
a query like `CREATE TABLE t (a Int32) AS SELECT * FROM file('x.bin', RowBinary)`
failed with `RowBinary file format doesn't support schema inference`
(BAD_ARGUMENTS).

The pre-check built the `SELECT` query plan in isolation, before the table
existed and without an insertion table in the context. The subsequent real
`INSERT SELECT` (see `fillTableIfNeeded`) sets the just-created table as the
insertion table, which lets table functions in the `SELECT` infer their
structure from the target table's columns
(`use_structure_from_insertion_table_in_table_functions`). Without that, a
`RowBinary` source - which cannot infer its own schema - has no structure to
fall back on, so the pre-check threw an error the real insert would never hit.
That contradicted the pre-check's own contract of mirroring the insert exactly.

Make the pre-check faithfully mirror the `INSERT SELECT`: provide the same
insertion table columns description (the structure we just computed, which is
what the table will have) on a copy of the context, with the same
`SelectQueryOptions(QueryProcessingStage::Complete, subquery_depth = 1)` as
`InterpreterInsertQuery`. The check now lives after the column structure is
known (so it can supply it) but still before the table is created, and continues
to cover every `isCreateQueryWithImmediateInsertSelect()` form.

CI report (Fast test):
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108048&sha=db51f546c1f7e32da51b2d59c61324d67c208e3f&name_0=PR&name_1=Fast%20test
PR: ClickHouse#108048

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
…ias application

The orphan-table access pre-check builds the full query plan of the `SELECT`
before the table is created. It must run after the view's column alias list has
been applied to the `SELECT`; otherwise a `POPULATE` materialized view whose
`ORDER BY` references a column alias - e.g.
`CREATE MATERIALIZED VIEW mv (x) ENGINE = Memory POPULATE AS SELECT y FROM src ORDER BY x` -
would be planned against the un-aliased `SELECT` and throw `UNKNOWN_IDENTIFIER`
before the view could be created.

This test passes on master (which has no such pre-check) and guards against
re-introducing the pre-check above the alias rewrite.

PR: ClickHouse#108048

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
The orphan-table access pre-check (a full query plan of the populating
`SELECT`, built before the table is created) ran unconditionally for every
`isCreateQueryWithImmediateInsertSelect` form. For `CREATE TABLE IF NOT EXISTS
... AS SELECT` whose target already exists this is wrong: `doCreateTable`
returns false and `execute` skips `fillTableIfNeeded`, so the populating
`INSERT SELECT` never runs and the `SELECT` is a no-op against the untouched
existing table. Running the pre-check there turned the no-op into an
access-checked `SELECT`, so a user lacking `SELECT` on a table referenced from
a subquery got a spurious `ACCESS_DENIED` even though the existing table would
be left untouched.

Add `createIfNotExistsResolvesToExistingTable`, mirroring the two
`if_not_exists` early-returns of `doCreateTable` (temporary tables via
`tryResolveStorageID(..., ResolveExternal)`, regular tables via
`database->isTableExist`), and skip the pre-check when it holds.

The pre-check still runs for `IF NOT EXISTS` when the table does not yet exist
(the orphan-table fix still applies there).

Extends `04418_create_table_as_select_subquery_access` with both cases: a
no-op `CREATE TABLE IF NOT EXISTS dst ... AS SELECT` on an existing table must
succeed and leave it unchanged even though a referenced table is denied, while
the same statement for a missing table must still be denied and leave no orphan.

Addresses the review on ClickHouse#108048

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
…TE ... AS SELECT

Routing a plain `CREATE TABLE ... AS SELECT` through the create-temporary-then-publish
machinery makes the populating `INSERT SELECT` run against an internal temporary table
(`_tmp_replace_<hash>_<random>`). That table's random name was recorded in the query's
access info and surfaced in `system.query_log` `tables`, e.g.:

  ['test_log_queries._tmp_replace_3f3feef71424dc2d_gclurwdee33113d4',
   'test_log_queries.logtable', 'test_log_queries.logtable3']

The temporary table is an implementation detail whose random name is meaningless to the
user and makes the log non-deterministic (this broke `01600_log_queries_with_extensive_info`).

Drop the temporary table from the query access info after the atomic publish. The final
table name is added to the log independently from the query's target (see
`IInterpreter::extendQueryLogElem`), so it is unaffected. A new
`Context::removeQueryAccessInfoTable` performs the removal (table entry plus any columns
recorded under it).

Fast test report:
https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=108048&sha=102c6e5c1563af144be51fba49b5c7599042c41d&name_0=PR&name_1=Fast%20test
PR: ClickHouse#108048

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
…teOrReplaceTable`

For the plain `CREATE TABLE ... AS SELECT` path, the `IF NOT EXISTS`
existing-table short-circuit ran after `checkTableNameLength` and
`checkTableCanBeAddedWithNoCyclicDependencies`, so a no-op create over an
existing table could fail validations that only matter when a table is
actually created (e.g. throw `INFINITE_LOOP` when the new, unused
definition would form a dependency cycle, or reject a legacy overlong
name). Move the existence check ahead of both validations for the
plain-create case, mirroring the check order of `doCreateTable`. The
REPLACE / `CREATE OR REPLACE` paths keep their previous check order.

Addresses the AI review blocker on
ClickHouse#108048

Co-Authored-By: Claude Fable 5 <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…lect-subquery-access

Do not leave an orphan table when CREATE ... AS SELECT is denied
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-bugfix Pull request with bugfix, not backported by default 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.

RBAC create table with sub-queries does not return not enough privileges error after revoke

2 participants