Repository navigation
Do not leave an orphan table when CREATE ... AS SELECT is denied - #108048
Conversation
`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]>
|
Workflow [PR], commit [c6e7196] Summary: ✅
AI ReviewSummaryThis PR reroutes plain Missing context / blind spots
Final VerdictStatus: ✅ Approve |
…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]>
…t-subquery-access
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
…t-subquery-access
…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]>
|
Addressed the sole blocking review item (the Fix (commit Test: extended CI reds — all unrelated flakes, none caused by this PR:
This was generated by Claude Code. |
…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]>
|
Addressed both items in the AI Review 1. Race-free
2. Strengthened no-op test (commit Built locally and ran The two prior CI reds were both This was generated by Claude Code. |
|
The sole CI red on head Flake: Other state: all review threads resolved; This was generated by Claude Code. |
|
Follow-up on head
Current CI: 156 checks 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, |
There was a problem hiding this comment.
Don't we worry about side effects or complex operations during the query plan building? Like scalar subqueries execution?
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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.
…t-subquery-access
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]>
|
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
If the For non-Atomic databases the previous behavior is kept (the table is created first, orphan left on failure), as you proposed.
One scope note: materialized/window views with Also merged 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]>
…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]>
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 127/140 (90.71%) · Uncovered code |
|
📊 Cloud Performance Report ✅ AI verdict: 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
|
…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]>
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]>
…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]>
…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]>
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]>
…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]>
…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]>
…lect-subquery-access Do not leave an orphan table when CREATE ... AS SELECT is denied
A
CREATE TABLE ... AS SELECTthat is denied because the user lacksSELECTon a table referenced by a subquery used to leave an empty orphan table behind. The table was created before the populatingINSERT SELECTran, and the access check fired only during thatINSERT SELECT— after the table already existed. A retry then reportedTABLE_ALREADY_EXISTSinstead of the access error.This is fixed for Atomic databases by reusing the same create-temporary-then-publish machinery that
CREATE OR REPLACEalready uses (doCreateOrReplaceTable): a plainCREATE TABLE ... AS SELECTnow creates the table under a temporary name, runs the populatingINSERT SELECTinto it, and only then atomically publishes it under the final name with aRENAME. If theSELECTis 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 realINSERT SELECT(executed exactly once), so it is column-aware and also covers tables referenced fromIN/scalar subqueries, not onlyFROM-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 theINSERT SELECTfails.Materialized/window views with
POPULATEare 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 acrossgetTablePropertiesAndNormalizeCreateQuery,doCreateTableand a helper.Closes: #26746
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Fixed
CREATE TABLE ... AS SELECTon 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.