Skip to content

[client-v2] Add Client#insertQuery for application-defined INSERT statements - #3460

Open
den-crane wants to merge 1 commit into
ClickHouse:mainfrom
den-crane:feature/insert-query
Open

den-crane wants to merge 1 commit into
ClickHouse:mainfrom
den-crane:feature/insert-query

Conversation

@den-crane

@den-crane den-crane commented Nov 27, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds Client#insertQuery, which inserts data with an INSERT statement that the application writes. Before, the insert methods could only make INSERT INTO <table> [(columns)] FORMAT <format>. That is not enough for statements such as:

INSERT INTO t (ip, count, ports)
SELECT ip, sum(count), groupUniqArrayState(port)
FROM input('ip IPv4, count UInt64, port UInt16') GROUP BY ip

INSERT INTO FUNCTION file('data.csv.gz', 'CSV', 'id UInt32, name String')

Relates to #2071 (closed by #2289, which added only column lists; the input() use case in the last comment of the issue was not covered).
Closes #2726

API (additive)

CompletableFuture<InsertResponse> insertQuery(String sql, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings)
CompletableFuture<InsertResponse> insertQuery(String sql, InputStream data, ClickHouseFormat format, InsertSettings settings)
CompletableFuture<InsertResponse> insertQuery(String sql, Map<String, Object> queryParams, DataStreamWriter writer, ClickHouseFormat format, InsertSettings settings)

A new method name is necessary: insert(String, DataStreamWriter, ClickHouseFormat, InsertSettings) already exists with a table name as the first argument.

Behavior

  • The client sends sql as it is in the query URL parameter, as the other insert methods do. The request body has only the data. The client does not parse, validate, or escape the SQL.
  • format != null: the client appends a new line and FORMAT <format>. The new line keeps the clause out of a -- comment at the end of the SQL.
  • format == null: the SQL must have its own FORMAT clause. The default format of the client is not sent (no X-ClickHouse-Format header), so it cannot conflict with the clause.
  • queryParams: values for {name:Type} placeholders, sent as param_<name> URL parameters with the same value formatting as Client#query.
  • Pre-compressed bodies work with InsertSettings#appCompressedData(true, "gzip") (for example a .parquet.gz file).
  • Metrics and spans of the operation have no target table (tableName is null). The javadoc of SpanRecorder, MetricsRecorder, SpanSupport, and MetricsSupport now says that tableName can be null.

Implementation

The retry/metrics/span/cancellation loop of insert(tableName, columns, writer, format, settings) moved into a private executeInsert(...). The existing method builds the same SQL as before and calls it. The InputStream writer and the query-parameter formatting became private helpers, shared with the existing paths.

Compatibility

Additive only. No existing signature or behavior changes.

Tests (InsertTests, which also runs in the LZ4, ZSTD and HTTP-compression subclasses)

  • testInsertQuery (data provider): INSERT ... SELECT ... FROM input(...) GROUP BY ... with the format appended by the client, a FORMAT clause in the SQL, a trailing -- comment, a {k:UInt64} query parameter, and the InputStream overload. Checks every column of every row.
  • testInsertQueryCompressedParquet: test_sample.parquet.gz (from tests for ORC / Parquet #571, copied to client-v2 test resources) with appCompressedData(true, "gzip") and a transform in SELECT.
  • testInsertQueryIntoTableFunction: INSERT INTO FUNCTION file('<uuid>.csv.gz', ...); checks the gzip magic bytes of the file and the rows read back. Skipped on Cloud.
  • testInsertQueryIntoNullFunction: INSERT INTO FUNCTION null(...); checks the written rows.
  • testInsertQueryServerError: duplicate FORMAT clause gives a ServerException and no rows.
  • testInsertQueryInvalidArguments: null/blank SQL, null writer, null settings give IllegalArgumentException.

Local run against ClickHouse 26.11: all insertQuery tests pass in all four classes. The only failures in those classes, testInsertAndReadBackWithSecureConnection (LZ4/ZSTD), need the SSL setup of the Testcontainers environment and fail the same way without this change.

Checklist

  • Unit and integration tests covering the common scenarios were added
  • A human-readable description of the changes was provided to include in CHANGELOG (history/latest/2071.md)
  • For significant changes, documentation in https://github.com/ClickHouse/clickhouse-docs was updated with further explanations or tutorials

🤖 Generated with Claude Code


Note

Medium Risk
Adds a new write path that accepts raw SQL (SQL-injection risk if misused) and refactors the shared insert executor, though existing insert APIs are intended to behave the same.

Overview
Adds Client#insertQuery so applications can send arbitrary INSERT SQL (e.g. INSERT ... SELECT ... FROM input(...), INSERT INTO FUNCTION file(...)/null(...)) with body data from an InputStream or DataStreamWriter. The client forwards sql unchanged (optional queryParams for {name:Type} placeholders, same formatting as query), appends \nFORMAT <format> when a format is provided, or requires a FORMAT clause in SQL when format is null and clears the default format header so it does not override the statement.

Existing insert(table, columns, ...) behavior is unchanged: it still builds INSERT INTO ... FORMAT ... but now delegates the retry/metrics/span/cancellation path to a private executeInsert. inputStreamWriter and formatQueryParams are shared helpers; insertQuery calls executeInsert with tableName null, so metrics/spans document that tableName may be absent. Integration tests cover input() transforms, params, compressed Parquet, table functions, duplicate FORMAT errors, and validation.

Reviewed by Cursor Bugbot for commit 4d54a8c. Bugbot is set up for automated code reviews on this repo. Configure here.

…T statements

The insert methods could only build `INSERT INTO <table> [(columns)] FORMAT <format>`.
An application could not send a statement such as
`INSERT INTO t SELECT ... FROM input('...')` or `INSERT INTO FUNCTION ...`
with data from a stream.

Add three `insertQuery` overloads (DataStreamWriter, InputStream, and
DataStreamWriter with query parameters). The client sends the statement as
it is in the `query` URL parameter, as the other insert methods do. When a
format is given, the client appends a new line and `FORMAT <format>`; when
it is null, the statement must have its own FORMAT clause and the default
format of the client is not sent. The operation reports no target table to
metrics and spans.

The existing insert methods delegate to the same private `executeInsert`
and keep their behavior. The change is additive.

Relates to ClickHouse#2071

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Enhance insert() API to support SELECT with input() for computed columns v2

1 participant