Skip to content

Batch Insert r2dbc #1802

Open
Open

Description

@javiercj93

Looks like bulk inserts are inserting 1 by 1 and not in batches.

I have created the following table:

CREATE TABLE IF NOT EXISTS  test
(
    `a` Int16,
    `b` Int16,
    `created` DateTime
)
ENGINE = MergeTree()
PARTITION BY (toYYYYMM(created))
ORDER BY (created)
TTL created + INTERVAL 13 MONTH;

If I try to do the following:

    public Mono<Void> saveAll(){
        return Mono.from(connectionFactory.create())
                .flatMapMany(conn -> execute(conn)).then();
    }

    private Publisher<? extends Result> execute(Connection conn) {
        return conn.createStatement("insert into test values (:a, :b, :created)")
                .bind("a",1)
                .bind("b", 2)
                .bind("created", LocalDateTime.now())
                .add()
                .bind("a",5)
                .bind("b", 6)
                .bind("created", LocalDateTime.now())
                .execute();
    }

When checking the logs, I can see that 2 connections are established and inserts are run independently so it is not acting as a batch insert.

2024-09-02T10:43:28.253Z DEBUG 49005 --- [ckHouseWorker-1] com.clickhouse.client.AbstractClient     : Connection established: com.clickhouse.client.http.HttpUrlConnectionImpl@1f010075
2024-09-02T10:43:28.253Z DEBUG 49005 --- [ckHouseWorker-1] c.c.client.http.ClickHouseHttpClient     : Query: insert into `default`.test values (1, 2, 1725273808)
2024-09-02T10:43:28.254Z DEBUG 49005 --- [ckHouseWorker-2] com.clickhouse.client.AbstractClient     : Connection established: com.clickhouse.client.http.HttpUrlConnectionImpl@35e8f1b6
2024-09-02T10:43:28.254Z DEBUG 49005 --- [ckHouseWorker-2] c.c.client.http.ClickHouseHttpClient     : Query: insert into `default`.test values (5, 6, 1725273808)

Am I doing something wrong or is this the intended behaviour?

I have also tried using this approach but same behaviour

return conn.createBatch()
    .add("insert into test values (1, 2, '2024-01-17 00:00:00')")
    .add("insert into test values (5, 6, '2024-01-17 00:00:00')")
    .execute();

I am using clickhouse-r2dbc version 0.6.4.

Activity

  1. chernser commented on Sep 3, 2024

    @chernser
    Contributor

    Good day, @javiercj93!
    Thank you for reporting! We will look into it.

  2. eyal-mishor commented on Oct 14, 2024

    @eyal-mishor

    I am using clickhouse-r2dbc version 0.7.0 and see the issue too.

    Looks to me as a critical issue since you can't really use r2dbc for batch inserts (the rows are inserted into different DB parts instead of a single part)

  3. added this to the Priority Backlog milestone on Nov 4, 2024
  4. chernser commented on Nov 4, 2024

    @chernser
    Contributor

    @eyal-mishor I agree - will try to look as soon as possible.

  5. removed this from the Priority Backlog milestone on Jan 10, 2025
  6. self-assigned this
    on Feb 8, 2025
  7. crowcrow commented on Feb 19, 2025

    @crowcrow

    Observed this behavior in clickhouse-jdbc v0.7.x, while 0.6.x seems to work as expected

  8. github-actions commented on Feb 20, 2026

    @github-actions

    This issue has been automatically marked as stale because it has not had activity in the last year. It will be closed in 30 days if no further activity occurs. Please feel free to leave a comment if you believe the issue is still relevant. Thank you for your contributions!

  9. removed their assignment
    on Mar 18, 2026
  10. polyglotAI-bot commented on Nov 28, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Keep open — fix needed
    r2dbc sends one INSERT request for each binding of Statement.add() and for each statement of a Batch, so each row becomes its own insert and part. A fix is needed in r2dbc; no PR exists.

    Analysis: ClickHouseStatement.java:142-153 on main sets the values of each binding on the request and calls request.execute once for each binding; ClickHouseBatch.java:33-37 calls it once for each SQL statement. The reporter's code is correct. The comment about JDBC 0.7.x does not apply to jdbc-v2 on main: its executeBatch sends one INSERT.

    Reproduction: complete program and output

    Changed from the issue's steps: counts the INSERT queries in system.query_log in place of the debug log; added a one-statement case and a jdbc-v2 contrast.

    import io.r2dbc.spi.Connection;
    import io.r2dbc.spi.ConnectionFactories;
    import io.r2dbc.spi.ConnectionFactory;
    import io.r2dbc.spi.Result;
    import org.reactivestreams.Publisher;
    import reactor.core.publisher.Flux;
    
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Timestamp;
    import java.time.LocalDateTime;
    import java.util.Properties;
    import java.util.function.Function;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        // compress=0: avoids clickhouse-java#3107 (v1 compressed reads fail on server 26.9+)
        static final ConnectionFactory CF = ConnectionFactories.get("r2dbc:clickhouse:"
                + URL.replaceFirst("^https?:", "").replaceFirst("//", "//default:" + PASSWORD + "@")
                + "/default?compress=0");
    
        public static void main(String[] args) throws Exception {
            run(conn -> conn.createStatement("DROP TABLE IF EXISTS test").execute());
            run(conn -> conn.createStatement("CREATE TABLE IF NOT EXISTS test (`a` Int16, `b` Int16, `created` DateTime)"
                    + " ENGINE = MergeTree() PARTITION BY (toYYYYMM(created)) ORDER BY (created) TTL created + INTERVAL 13 MONTH").execute());
    
            long before = inserts();
            run(conn -> conn.createStatement("insert into test values (:a, :b, :created)")
                    .bind("a", 1).bind("b", 2).bind("created", LocalDateTime.now())
                    .add()
                    .bind("a", 5).bind("b", 6).bind("created", LocalDateTime.now())
                    .execute());
            System.out.println("r2dbc Statement, 2 bindings: INSERT queries = " + (inserts() - before));
    
            before = inserts();
            run(conn -> conn.createBatch()
                    .add("insert into test values (1, 2, '2024-01-17 00:00:00')")
                    .add("insert into test values (5, 6, '2024-01-17 00:00:00')")
                    .execute());
            System.out.println("r2dbc Batch, 2 statements: INSERT queries = " + (inserts() - before));
    
            before = inserts();
            run(conn -> conn.createStatement("insert into test values (1, 2, now()), (5, 6, now())").execute());
            System.out.println("r2dbc Statement, 1 INSERT with 2 rows: INSERT queries = " + (inserts() - before));
    
            Properties props = new Properties();
            props.setProperty("user", "default");
            props.setProperty("password", PASSWORD);
            before = inserts();
            try (java.sql.Connection conn = DriverManager.getConnection("jdbc:clickhouse:" + URL.replaceFirst("^https?:", "") + "/default", props);
                 PreparedStatement ps = conn.prepareStatement("insert into test values (?, ?, ?)")) {
                for (int[] row : new int[][]{{1, 2}, {5, 6}}) {
                    ps.setInt(1, row[0]);
                    ps.setInt(2, row[1]);
                    ps.setTimestamp(3, Timestamp.valueOf(LocalDateTime.now()));
                    ps.addBatch();
                }
                ps.executeBatch();
            }
            System.out.println("jdbc-v2 PreparedStatement, executeBatch of 2 rows: INSERT queries = " + (inserts() - before));
        }
    
        static void run(Function<Connection, Publisher<? extends Result>> statement) {
            Flux.usingWhen(CF.create(), conn -> Flux.from(statement.apply(conn)).flatMap(Result::getRowsUpdated),
                    Connection::close).blockLast();
        }
    
        static long inserts() {
            run(conn -> conn.createStatement("SYSTEM FLUSH LOGS").execute());
            return Flux.usingWhen(CF.create(), conn -> Flux.from(conn.createStatement(
                    "SELECT toInt64(count()) FROM system.query_log WHERE type = 'QueryFinish' AND query_kind = 'Insert'"
                            + " AND has(tables, 'default.test') AND event_date >= yesterday()").execute())
                    .flatMap(r -> r.map((row, md) -> row.get(0, Long.class))), Connection::close).blockLast();
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11:

    r2dbc Statement, 2 bindings: INSERT queries = 2
    r2dbc Batch, 2 statements: INSERT queries = 2
    r2dbc Statement, 1 INSERT with 2 rows: INSERT queries = 1
    jdbc-v2 PreparedStatement, executeBatch of 2 rows: INSERT queries = 1
    

    Automated triage by Polyglot AI. A maintainer makes the final decision.

  11. added
    queries
    and removed on Nov 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    performancequeriesr2dbc

    Type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions