Skip to content

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

Open
den-crane wants to merge 2 commits into
ClickHouse:mainfrom
den-crane:feature/insert-query
Open

den-crane wants to merge 2 commits 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
Additive API with refactored insert execution path; callers must not embed untrusted values in raw SQL, and null-format behavior depends on correct FORMAT handling in the statement.

Overview
Adds Client#insertQuery so applications can run arbitrary INSERT SQL (e.g. INSERT ... SELECT ... FROM input(...) or INSERT INTO FUNCTION file(...)) with body data from an InputStream or DataStreamWriter. The client sends the statement as-is; when format is set it appends \nFORMAT <format>; when format is null the SQL must already include FORMAT and the client clears the default format header so it cannot conflict. {name:Type} parameters use the same queryParams / formatQueryParams path as Client#query.

Existing table/column insert overloads are unchanged in behavior: SQL building stays in insert(...), while retry/metrics/span/cancellation logic is centralized in private executeInsert, with inputStreamWriter shared for stream-based inserts.

Observability Javadoc now documents tableName as null for custom inserts (no db.collection.name). Integration tests cover input() aggregation, query params, pre-compressed parquet, table functions, validation, and duplicate FORMAT errors.

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

@chernser chernser left a comment

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.

@den-crane

Much appreciate the contribution!
Most looks fine - I will review once more today.

Please fix tests failing on cluster - you should not set the table engine.

[ERROR]   InsertTests.testInsertQuery:946 expected [2] but found [0]
[ERROR]   InsertTests.testInsertQuery:946 expected [2] but found [0]
[ERROR]   InsertTests.testInsertQuery:946 expected [2] but found [0]
[ERROR]   InsertTests.testInsertQuery:946 expected [2] but found [0]
[ERROR]   InsertTests.testInsertQuery:946 expected [2] but found [0]

Thanks!

den-crane and others added 2 commits November 30, 2026 13:08
…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>
The cluster profile sets default_table_engine=ReplicatedMergeTree, and nginx
sends each request to any of the three replicas. The tables with an explicit
MergeTree engine were not replicated, so the read-back on another replica
found no rows. Use the default engine, as the other insert tests do.

The file() table function writes a file that is local to one server. Send all
requests of that test to the same replica with the replica tag header.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@den-crane
den-crane force-pushed the feature/insert-query branch from 4d54a8c to 4132776 Compare November 30, 2026 17:10
@den-crane

Copy link
Copy Markdown
Contributor Author

Thanks! Fixed in 4132776: the tests no longer set the table engine, so the cluster's default ReplicatedMergeTree is used. The file() test also pins its requests to one replica with X-ClickHouse-Replica-Tag, because the file is local to a server. The cluster jobs pass now. The SonarCloud failure is the coverage-comment step (403 for a PR from a fork).

@den-crane
den-crane requested a review from chernser November 30, 2026 17:52
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

2 participants