Skip to content

Allow creating table as table function with another engine - #101177

Open
Jaiden285 wants to merge 1 commit into
ClickHouse:masterfrom
Jaiden285:jaiden258/create-table-as-with-engine
Open

Jaiden285 wants to merge 1 commit into
ClickHouse:masterfrom
Jaiden285:jaiden258/create-table-as-with-engine

Conversation

@Jaiden285

Copy link
Copy Markdown

Changelog category (leave one):

  • New Feature

Changelog entry:

Users can create a table with structure inferred from a table function, but with a different engine. The table function's engine is ignored.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Fixes #50571.

This PR allows users to specify engine for CREATE TABLE AS table_function() queries.
The table function is used to infer table structure, i.e. the list of columns with names and types, and the new table is created with the specified engine. The table function's engine is ignored.

Example:

CREATE TABLE test ENGINE = MergeTree ORDER BY coalesce(name, '') AS file('test.csv')

where test.csv is the following:

name,age
'John',29

creates the table equivalent to the following query:

CREATE TABLE test (`name` Nullable(String), `age` Nullable(Int64)) ENGINE = MergeTree ORDER BY coalesce(name, '')

@CLAassistant

Copy link
Copy Markdown

CLA assistant check
Thank you for your submission! We really appreciate it. Like many open source projects, we ask that you sign our Contributor License Agreement before we can accept your contribution.
You have signed the CLA already but the status is still pending? Let us recheck it.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 30, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 30, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [a6b8f9d]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel) failure
00973_create_table_as_table_function FAIL cidb
Stress test (amd_asan_ubsan) failure
Possible deadlock on shutdown (see gdb.log) FAIL cidb

AI Review

Summary

This PR enables CREATE TABLE ... AS table_function() [ENGINE = ...] so users can infer columns from a table function while choosing a different target engine. The feature direction is good, but there are correctness issues around restore_replace_external_table_functions_to_null that can still trigger external table-function access, so this should not merge as-is.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:1288-1300, 993-998] With restore_replace_external_table_functions_to_null = 1, setEngine can return early with create.as_table_function still present (notably when table-function properties are allow_readonly). getTablePropertiesAndNormalizeCreateQuery then calls getActualTableStructureWithAccess for as_table_function, which can still initiate external access and violates the setting’s contract.
    • Suggested fix: when this setting is enabled, ensure as_table_function is cleared or blocked before any structure inference path that could access external sources.
  • [src/Interpreters/InterpreterCreateQuery.cpp:1293-1299] The new explicit-engine path only nullifies the engine for source_access_type storages, but does not prevent table-function-based structure inference from running afterward. This creates partial mitigation and leaves an external-access path active.
    • Suggested fix: handle both engine replacement and table-function inference together under the restore setting (either fully disable table-function inference, or fail fast with a clear exception).

💡 Nits

  • [src/Interpreters/InterpreterCreateQuery.cpp:763] Typo in comment text: "so the after the structure is inferred" → "so after the structure is inferred".
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ restore_replace_external_table_functions_to_null behavior is inconsistent and can violate expected restore safety semantics.
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Restore-time safety behavior is not reliably enforced for this path.
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Make restore_replace_external_table_functions_to_null enforcement complete for CREATE ... AS table_function ... [ENGINE=...], including the structure-inference path.
    2. Add/adjust tests covering this setting with explicit engine overrides and table functions that would otherwise perform external access.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 30, 2026
@@ -2023,19 +2023,32 @@ bool InterpreterCreateQuery::doCreateTable(ASTCreateQuery & create,
/// NOTE: CREATE query may be rewritten by Storage creator or table function
if (create.as_table_function)
{
auto table_function_ast = create.as_table_function->ptr();
auto table_function = TableFunctionFactory::instance().get(table_function_ast, getContext());
if (create.storage)

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.

CREATE TABLE ... ENGINE ... AS table_function(...) now leaves create.storage set while create.as_table_function is still present at this stage. With restore_replace_external_table_functions_to_null = 1, setEngine currently treats this as impossible and throws LOGICAL_ERROR ("Storage should not be created yet, it's a bug.").

This turns a valid query into an internal exception under a supported setting.

Please handle the create.storage && create.as_table_function case explicitly (for example, avoid throwing and clear as_table_function/skip replacement when an explicit engine is already provided).

@Jaiden285
Jaiden285 force-pushed the jaiden258/create-table-as-with-engine branch from 660f75b to dd83f18 Compare March 31, 2026 06:02
{
if (getContext()->getSettingsRef()[Setting::restore_replace_external_table_functions_to_null])
{
if (create.storage) {

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.

With restore_replace_external_table_functions_to_null = 1, this new create.storage fast-path returns before replacing/removing as_table_function.

For a query like CREATE TABLE t ENGINE = MergeTree AS remote(...), execution then reaches getTablePropertiesAndNormalizeCreateQuery, where create.as_table_function is still set and getActualTableStructureWithAccess is called. That can still initiate external access, which conflicts with the setting contract (“replace external table functions to Null to not initiate external connections”).

Could we either (1) nullify/skip as_table_function under this setting (and require explicit columns when needed), or (2) throw a clear exception when AS table_function is used together with this setting and no local structure is available?

@@ -1243,6 +1243,19 @@ void InterpreterCreateQuery::setEngine(ASTCreateQuery & create) const
{
if (getContext()->getSettingsRef()[Setting::restore_replace_external_table_functions_to_null])

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 purpose of this setting is to avoid initiating connections to external services (S3, MySQL, remote ClickHouse, etc) when executing A CREATE TABLE or RESTORE query (useful for testing). Will it avoid external connections for a query with a remote table function and some engine?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

After looking a bit more at this setting, it seems that (and AI pointed that out as well) that we will not be able to infer the table structure without a remote call.

The existing behaviour for the table functions is the following:

set restore_replace_external_table_functions_to_null=1
create table bar as file('test.csv')
Received exception from server (version 26.4.1):
Code: 80. DB::Exception: Received from localhost:9000. DB::Exception: Incorrect CREATE query: required list of column descriptions or AS section or SELECT.. (INCORRECT_QUERY)

Since the code under if resets the as_table_function pointer, and Null engine has supports_schema_inference == false. Which is a bit misleading, since the query has the AS section, but I guess it's fine for testing purposes.

So with this setting active, I'd suggest

  1. Check that if storage is set, then it has an engine specified, before checking the setting. If the engine is not specified, the query is invalid, so I think we should report this error in the first place.
  2. If the table function is allow_readonly and engine is specified, override it with Null engine if source_access_type is set.
  3. Remove the else branch with exception, since it's a valid state now

This way we preserve the existing behaviour for table functions without specified engine and for allow_readonly functions with specified engine we override engine with NullEngine as for non-table function queries. We still want to fail if table function is not allow_readonly if the engine is specified, since we're not able to infer the table structure, unless it's explicitly specified (more on that below).

Does it make sense?

I've also found some issues with column list parsing in case engine is set, I'm fixing it now along with the style inconsistencies.

I've also found some interesting behaviour with create as table function query if the column list specified - inserting values into the new table fails with error NOT_FOUND_COLUMN_IN_BLOCK unless the specified columns are identical to the columns inferred from the table function. Which makes sense, but wouldn't it be better to fail to create a table with incompatible columns?

Example:
Given that test.csv has the following structure: (name Nullable(String), age Nullable(Int64))

create table bar (a Int64) as file('test.csv')
select * from bar
Received exception from server (version 26.4.1):
Code: 10. DB::Exception: Received from localhost:9000. DB::Exception: Column `a` not found in table default.bar (2f1e0874-d862-40f4-94fe-e09922afb0dd). (NOT_FOUND_COLUMN_IN_BLOCK)

create table baz (name Nullable(String)) as file('test.csv')
insert into baz values('aaa')
Code: 10. DB::Exception: Received from localhost:9000. DB::Exception: Column `a` not found in table default.bar (2f1e0874-d862-40f4-94fe-e09922afb0dd). (NOT_FOUND_COLUMN_IN_BLOCK)

create table foo (name Nullable(String), age Nullable(Int64), foo Int64) as file('test.csv')
Received exception from server (version 26.4.1):
Code: 122. DB::Exception: Received from localhost:9000. DB::Exception: Source storage and table function have different structure: While executing WaitForAsyncInsert. (INCOMPATIBLE_COLUMNS)

Though, select * query works if the specified set of columns is a subset of the table function's columns.

So my current plan is to compare the existing ColumnsDescription with the inferred ColumnsDescription from the table function and throw an INCOMPATIBLE_COLUMNS error if they are different, thus failing the creation of the table. Does it make sense?

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.

Yes, we cannot infer the table structure without a remote call, so if no structure is specified and the table function requires a remote call - we should throw an exception. Actually, this combination (restore_replace_external_table_functions_to_null=1 + another engine with as table_function()) doesn't make much sense: "another engine with as table_function()" is useful for schema inference, but restore_replace_external_table_functions_to_null=1 disallows schema inference for some table functions

It's not necessary to reset the engine to Null (and even better to keep the original engine) for allow_readonly table functions, we just need to avoid remote calls. It's also okay to disallow this combination completely

I've also found some interesting behaviour with create as table function query if the column list specified - inserting values into the new table fails with error NOT_FOUND_COLUMN_IN_BLOCK unless the specified columns are identical to the columns inferred from the table function. Which makes sense, but wouldn't it be better to fail to create a table with incompatible columns?

Yes, it would be better, but usually users don't specify the structure when creating tables like this. The possibility to specify the structure is mostly for internal usage: ClickHouse simply stores CREATE TABLE statements in .sql files and executes them as ATTACH TABLE on server loading. It wasn't possible to load a table without a list of columns, and if ClickHouse fails to get the structure from a remote source - it would fail to start, so we saved the previously inferred structure to the metadata file. If the remote structure changes later (but remains compatible, e.g. new columns, data type changes) - ClickHouse will try to convert it when executing SELECT/INSERT, that's why

select * query works if the specified set of columns is a subset of the table function's columns.

So my current plan is to compare the existing ColumnsDescription with the inferred ColumnsDescription from the table function and throw an INCOMPATIBLE_COLUMNS error if they are different, thus failing the creation of the table. Does it make sense?

Yes, it makes sense, but we need to make sure that this check is performed for CREATE only, not for ATTACH

@Jaiden285
Jaiden285 force-pushed the jaiden258/create-table-as-with-engine branch from dd83f18 to a6b8f9d Compare April 15, 2026 20:08
if (create.as_table_function && create.storage && create.storage->engine)
{
/// 1. In CREATE ... AS table_function() ENGINE = ... queries table_function should be used
/// only for table structure inference, so the after the structure is inferred the

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.

Typo in the comment: "so the after the structure is inferred" has an extra the.

Suggested wording: "so after the structure is inferred".

@clickhouse-gh

clickhouse-gh Bot commented Apr 15, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.00% 84.00% +0.00%
Functions 90.90% 90.90% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 89.66% (52/58) | lost baseline coverage: 2 line(s) · Uncovered code

Full report · Diff report

@Jaiden285

Copy link
Copy Markdown
Author

[2026-04-15 22:51:57] - [src/Interpreters/InterpreterCreateQuery.cpp:1288-1300, 993-998] With restore_replace_external_table_functions_to_null = 1, setEngine can return early with create.as_table_function still present (notably when table-function properties are allow_readonly). getTablePropertiesAndNormalizeCreateQuery then calls getActualTableStructureWithAccess for as_table_function, which can still initiate external access and violates the setting’s contract.

However, the early return happens if allow_readonly table function property is true. My understanding was that if it's the case, then table function does not initiate any external accesses, so inferring table structure is safe. The existing code early-returns without any modifications as well. What am I missing here?

The issue with potential deadlock on shutdown in [PR / Stress test (amd_asan_ubsan)](https://github.com/ClickHouse/ClickHouse/actions/runs/24475834899/job/71537021319?pr=101177) seems not to be related to this particular PR, since I see similar failures for many other PRs in cidb.

Will look into the failing test in Stateless tests (amd_llvm_coverage, old analyzer, s3 storage, DatabaseReplicated, WasmEdge, parallel), add more tests for parser to cover the new lines and fix the typo.

@tavplubix

Copy link
Copy Markdown
Member

What am I missing here?

Nothing, AI is wrong

Yes, the Stress tests failure is unrelated, but the 00973_create_table_as_table_function failure is

@abashkeev abashkeev added the comp-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). label Sep 4, 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-ddl DDL command coordination and execution (ON CLUSTER, DDL queue). external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

CREATE TABLE AS table_function() but with another ENGINE

6 participants