Repository navigation
Add minimal INSERT ... RETURNING (SELECT ...) - #126476
Conversation
The `RETURNING` clause specifies a `SELECT` query, which runs on top of the inserted blocks: inside it, the destination table refers to the stream of the data written into the table (after the defaults are filled). The INSERT pipeline is forked right before the sink of the destination table, and the copy of the data is the source of the `RETURNING` query, the same way as a materialized view reads the inserted blocks. Deduplication and other transformations inside the table engine are not taken into account. It is supported for `INSERT SELECT` and for `INSERT` with the data inlined into the query or in the HTTP request body. `clickhouse-client` sends the data inline with the query when there is `RETURNING`. This is a simpler replacement for #105714 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [3891de3] Summary: ✅
AI ReviewSummaryAdds Final VerdictStatus: ✅ Approve. |
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes425 object files changed (+166.33 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units1956 translation units recompiled, 11641 s compile time in total, 1955 of them have a recent master baseline. Translation units without a recent master baseline:
|
…ately When `clickhouse-client` sends the data of an INSERT separately from the query (from stdin, `FROM INFILE`, or `VALUES` parsed by the client), the server reads it inside the pipeline with the `input` callbacks, and sends the result of the `RETURNING` query while the client is still sending the data. The client reads the result between sending the blocks, and before `EndOfStream`. To avoid a deadlock when both sides block on writing to a full socket, the server sends the result without `callback_mutex` (which is held by the thread reading the data) until all the data is received. This is gated by the new protocol revision 54495 (`DBMS_MIN_REVISION_WITH_INSERT_RETURNING`); older clients get `NOT_IMPLEMENTED` instead of unexpected packets. The input initializer now takes the columns description and the header instead of a storage, so the insert can send the full table columns (for defaults) with the insert sample block, as for an ordinary INSERT. The `RETURNING` query is run with `implicit_table_at_top_level` set to the destination, so it can be written without `FROM`, which is also the way to read the data inserted into a table function (`INSERT INTO FUNCTION`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Preview deployment for your docs. Learn more about Mintlify Previews.
|
In the flaky check, `05401_insert_returning` (debug) and `05402_insert_returning_client` (ASan) took more than 180 seconds. The queries did not hang: the inserts with hundreds of tiny blocks created hundreds of parts each, and the insert of 3 million rows from stdin was starved of CPU on the loaded machine (`OSCPUWaitMicroseconds` was 93 seconds of 182). Insert ten times less data, and write the large insert into the `null` table function. It still sends many blocks while receiving a result much larger than the socket buffers. https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126476&sha=86ab9be4ed2881ec7682cda20b1c0565cfa38b22&name_0=PR&name_1=Stateless%20tests%20%28amd_debug%2C%20flaky%20check%29 https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=126476&sha=86ab9be4ed2881ec7682cda20b1c0565cfa38b22&name_0=PR&name_1=Stateless%20tests%20%28amd_asan_ubsan%2C%20flaky%20check%29 #126476 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…other tables in `INSERT ... RETURNING` - `EXPLAIN PIPELINE` of `INSERT ... RETURNING` could run the insert while building the `RETURNING` query, e.g. to evaluate a scalar subquery. Now the `RETURNING` query reads an empty block for `EXPLAIN`, and the insert is added as a separate pipeline, which is not executed. - A scalar subquery or `EXISTS` reading the inserted data ran the whole insert during the analysis, and the query then failed after the data was written. Reading the inserted data during the analysis now throws `NOT_IMPLEMENTED` before anything is executed. - Subcolumns (`JSON` paths, tuple elements, `size0`, `null`) of the inserted data threw `NOT_FOUND_COLUMN_IN_BLOCK`, because the pipe has only the physical columns. They are extracted with `getSubcolumn` now. - For a destination which reads from other tables (`Alias`, `Distributed`, `Buffer`), the `RETURNING` query skipped the access checks and the row policies of those tables. Such destinations are rejected with `NOT_IMPLEMENTED`. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Since ClickHouse#124907 the test runner randomizes `max_bytes_before_external_set` and `max_bytes_ratio_before_external_set`. When the threshold is below what the set collects before the test's 0.1 s limit, the set goes to disk, and the disk set builder throws `QUERY_WAS_CANCELLED` in the `break` mode by design (`05401_external_set_cancellation`). The test checks the quiet stop of the in-memory set, so clamp both thresholds to 0 for it with `Random settings limits`; every other setting stays random. Failed in "Stateless tests (arm_binary, AsyncInsert, s3 storage, parallel)" on PR ClickHouse#126476 with `--max_bytes_before_external_set 8556090` (127/128 reruns with the same settings failed). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…RNING` - Reject materialized-view destinations too: the `RETURNING` query reads the inserted stream instead of the view, so the read authorization of its target would not apply. - Do this check after the `INSERT` access check of the destination, so the engine is not reported to a user without access to the table. - Do not require `SELECT` on the synthetic `_table_function.*` name for the data inserted into a table function; the access to the table function is checked when it is executed, and the tables read by the `RETURNING` query are still checked. - Keep the combined pipeline single-threaded when the insert pushes to dependent materialized views sequentially (`parallel_view_processing = 0`). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…khouse-local` The `input` initializer of `LocalConnection` always read the data from stdin, and the client skipped its own reader of the file, so the file was silently ignored. Read the file in the initializer with `StorageFile`, the same way as `ClientBase::sendData` does (globs, compression, the format from the file name). Co-Authored-By: Claude Opus 5.5 <[email protected]>
…el-replicas Resolve the conflict in the input() blocks reader callback of TCPHandler.cpp: keep master's received_all_data_for_input writes (INSERT ... RETURNING, ClickHouse#126476) and this PR's killQueryIfStoppedByClient call after callback_mutex is released. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@alexey-milovidov should this be experimental and be disabled with a setting at the moment? |
Closes: #21697 Closes #5912
Related: #105714
A minimal implementation of
INSERT ... RETURNING, a much simpler replacement for #105714.The
RETURNING (SELECT ...)clause goes right after the list of columns (before the data, because everything afterVALUES/FORMATis data). It runs theSELECTon top of the inserted blocks: inside it, the destination table refers to the stream of data being written into the table, after the omitted columns are filled with defaults. So it returns, for example, generated values such asDEFAULT generateUUIDv4()exactly as they were written. WithoutFROM, theSELECTreads the inserted data too (viaimplicit_table_at_top_level), which is also the way to refer to the data inserted into a table function. Deduplication and other transformations inside the table engine are not taken into account.Implementation:
InsertDependenciesBuilderoptionally puts aForkProcessorinto the chain of every insert stream, right before the sink of the destination table. The copies are merged by aResizeProcessor.Pipe. TheRETURNINGquery reads it through aStorageValuesset as the view source, the same way a materialized view reads the inserted blocks. The data is streamed and not accumulated in memory. If theRETURNINGquery doesn't read the table (e.g.SELECT 1 FROM system.one), the insert still runs as a completed pipeline. If it reads the table twice, it throwsNOT_IMPLEMENTED.VALUESparsed byclickhouse-client, stdin,FROM INFILE,input) is read inside the pipeline with the existinginputcallbacks, and the result is streamed to the client while it is still sending the data.clickhouse-clientreads the result packets between sending the blocks and beforeEndOfStream. To avoid a deadlock when both sides block on writing to full socket buffers,TCPHandlersends the result withoutcallback_mutex(held by the thread reading the data) until all the data is received, and doesn't acceptPingin this phase.DBMS_MIN_REVISION_WITH_INSERT_RETURNING): older clients getNOT_IMPLEMENTEDinstead of unexpected packets. The spec of the native protocol is updated.clickhouse-localworks as well.async_insertsetting is ignored for such queries, and parallel distributedINSERT SELECTis not used.RETURNINGquery can't read the inserted data during the analysis (in a scalar subquery orEXISTS), because that would run the insert before the query is built: this throwsNOT_IMPLEMENTED. ForEXPLAIN PIPELINE, theRETURNINGquery reads an empty block, and the insert is not executed.Alias,Distributed,Bufferwith a destination) are rejected withNOT_IMPLEMENTED, because the access checks and row policies of the underlying tables would not apply to the substituted data stream.RETURNINGis not added to the list of reserved keywords.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Add
INSERT INTO t ... RETURNING (SELECT ...), which runs aSELECTon top of the inserted data and streams its result while the data is being inserted, e.g. to get the values of columns generated on insertion. Inside theSELECT, the destination table (or the absence ofFROM) refers to the inserted data.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/126476]
Version info
26.11.1.707-master(included in26.11and later)