Skip to content

Insert function is not working #1401

Open

Description

@shabir1

I am not able to insert the CSV data into the existing table in click house. using clickhouse-java

I run the below code but it throws the errro:

static long insert(ClickHouseNode server, String table) throws ClickHouseException {
        try (ClickHouseClient client = ClickHouseClient.newInstance(server.getProtocol())) {
            ClickHouseRequest.Mutation request = client.connect(server).write().table(table)
                    .format(ClickHouseFormat.RowBinary);
            ClickHouseConfig config = request.getConfig();
            CompletableFuture<ClickHouseResponse> future;
            // back-pressuring is not supported, you can adjust the first two arguments
            try (ClickHousePipedOutputStream stream = ClickHouseDataStreamFactory.getInstance()
                    .createPipedOutputStream(config, (Runnable) null)) {
                // in async mode, which is default, execution happens in a worker thread
                future = request.data(stream.getInputStream()).execute();

                // writing happens in main thread
                for (int i = 0; i < 10_000; i++) {
                    BinaryStreamUtils.writeString(stream, String.valueOf(i % 16));
                    BinaryStreamUtils.writeNonNull(stream);
                    BinaryStreamUtils.writeString(stream, UUID.randomUUID().toString());
                }
            }

            // response should be always closed
            try (ClickHouseResponse response = future.get()) {
                ClickHouseResponseSummary summary = response.getSummary();
                return summary.getWrittenRows();
            }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
            throw ClickHouseException.forCancellation(e, server);
        } catch (ExecutionException | IOException e) {
            throw ClickHouseException.of(e, server);
        }
    }

Error

java.util.concurrent.ExecutionException: com.clickhouse.client.ClickHouseException: Code: 33. DB::Exception: Cannot read all data. Bytes read: 2. Bytes expected: 4.: (at row 14272)
: While executing BinaryRowInputFormat. (CANNOT_READ_ALL_DATA) (version 23.6.2.18 (official build))
, server ClickHouseNode [uri=http://localhost:8123/ShabirBhat_project]@-2130346309
	at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
	at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1908)
	at com.datoin.ch.CHclientTest.insert(CHclientTest.java:77)
	at com.datoin.ch.CHclientTest.main(CHclientTest.java:40)
Caused by: com.clickhouse.client.ClickHouseException: Code: 33. DB::Exception: Cannot read all data. Bytes read: 2. Bytes expected: 4.: (at row 14272)
: While executing BinaryRowInputFormat. (CANNOT_READ_ALL_DATA) (version 23.6.2.18 (official build))
, server ClickHouseNode [uri=http://localhost:8123/ShabirBhat_project]@-2130346309
	at com.clickhouse.client.ClickHouseException.of(ClickHouseException.java:168)
	at com.clickhouse.client.AbstractClient.lambda$execute$0(AbstractClient.java:275)
	at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1604)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
	at java.lang.Thread.run(Thread.java:750)
Caused by: java.io.IOException: Code: 33. DB::Exception: Cannot read all data. Bytes read: 2. Bytes expected: 4.: (at row 14272)
: While executing BinaryRowInputFormat. (CANNOT_READ_ALL_DATA) (version 23.6.2.18 (official build))

	at com.clickhouse.client.http.HttpUrlConnectionImpl.checkResponse(HttpUrlConnectionImpl.java:184)
	at com.clickhouse.client.http.HttpUrlConnectionImpl.post(HttpUrlConnectionImpl.java:227)
	at com.clickhouse.client.http.ClickHouseHttpClient.send(ClickHouseHttpClient.java:124)
	at com.clickhouse.client.AbstractClient.sendAsync(AbstractClient.java:161)
	at com.clickhouse.client.AbstractClient.lambda$execute$0(AbstractClient.java:273)
	... 4 more

Process finished with exit code 0

I tried to replace the below code with my csv data

 // writing happens in main thread
                for (int i = 0; i < 10_000; i++) {
                    BinaryStreamUtils.writeString(stream, String.valueOf(i % 16));
                    BinaryStreamUtils.writeNonNull(stream);
                    BinaryStreamUtils.writeString(stream, UUID.randomUUID().toString());
                }


Replace with :
BufferedReader reader = new BufferedReader(new FileReader(csvFilePath));
                String line;
                while ((line = reader.readLine()) != null) {
                    System.out.println(line);
                    BinaryStreamUtils.writeString(stream, line);
                }

Activity

  1. zhicwu commented on Jul 13, 2023

    @zhicwu
    Contributor

    Hi @shabir1, apologize for the confusing methods. BinaryStreamUtils.writeString only works for writing a String in RowBinary data format. It looks like this is duplicated with #1402? Let me know if you want to close this and carry on discussion there.

  2. mzitnik commented on Aug 2, 2023

    @mzitnik
    Contributor

    @shabir1 did you managed?

  3. shabir1 commented on Aug 3, 2023

    @shabir1
    Author

    @mzitnik I used the below method to upload the local file on clickhouse.

    static long insert(String tableName, String csvFilePath) throws Exception {
            ClickHouseNode server = getServer();
            try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(csvFilePath))) {
                ClickHousePassThruStream stream = ClickHousePassThruStream.of(
                        bufferedInputStream,
                        ClickHouseCompression.NONE,
                        0,
                        ClickHouseFormat.CSVWithNames
                );
                CompletableFuture<ClickHouseResponseSummary> load = ClickHouseClient.load(server, tableName, stream);
                ClickHouseResponseSummary clickHouseResponse = load.get();
                return clickHouseResponse.getWrittenRows();
            } catch (Exception e) {
                System.out.println("Failed to  load");
                e.printStackTrace();
                throw new Exception();
            }
        }
    

    But on huge files, it failed with memory issues, Most failures occurred on the file that contained more than 300 columns.

    ERROR [2023-07-27 06:20:36,451] com.datoin.library.dataset.sql.utility.commons.abstracts.sql.AbstractDBEngine: Failed to load dataset
    java.util.concurrent.ExecutionException: com.clickhouse.client.ClickHouseException: Code: 241. DB::Exception: Memory limit (total) exceeded:
    would use 3.36 GiB (attempt to allocate chunk of 4360384 bytes), maximum: 3.24 GiB. OvercommitTracker decision: Query was selected to stop by
     OvercommitTracker. (MEMORY_LIMIT_EXCEEDED) (version 23.6.2.18 (official build))
    , server ClickHouseNode [uri=http://localhost:8123/cayleytest95814, options={connect_timeout=5000000,socket_timeout=5000000}]@75218225
            at java.util.concurrent.CompletableFuture.reportGet(CompletableFuture.java:357)
            at java.util.concurrent.CompletableFuture.get(CompletableFuture.java:1895)
    
  4. mzitnik commented on Aug 3, 2023

    @mzitnik
    Contributor

    @shabir1 from here it looks like a ClickHouse server limit issue did you tried to set memory

  5. shabir1 commented on Aug 7, 2023

    @shabir1
    Author

    @mzitnik How to set memory in the above method?
    and if I set max_memory_usage_for_user = 10, Is it 10 Bytes/MB/GB ?

  6. mzitnik commented on Aug 7, 2023

    @mzitnik
    Contributor

    @shabir1 It is bytes

  7. shabir1 commented on Aug 14, 2023

    @shabir1
    Author

    @mzitnik How to set memory in the below method?
    like max_memory_usage_for_user, max_memory_usage, etc

       static long insert(String tableName, String csvFilePath) throws Exception {
            ClickHouseNode server = ClickHouseNode.builder()
                    .host(System.getProperty("chHost", "localhost"))
                    .port(ClickHouseProtocol.HTTP, Integer.getInteger("chPort", 8123))
                    .database("ShabirBhat_project")
                    .addOption("connect_timeout", String.valueOf(1350 * 1000))
                    .addOption("socket_timeout", String.valueOf(1350 * 1000))
                    .credentials(ClickHouseCredentials.fromUserAndPassword(
                            System.getProperty("chUser", "default"), System.getProperty("chPassword", "")))
                    .build();
            try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(csvFilePath))) {
                ClickHousePassThruStream stream = ClickHousePassThruStream.of(
                        bufferedInputStream,
                        ClickHouseCompression.NONE,
                        0,
                        ClickHouseFormat.CSVWithNames
                );
                CompletableFuture<ClickHouseResponseSummary> load = ClickHouseClient.load(server, tableName, stream);
                ClickHouseResponseSummary clickHouseResponse = load.get();
                return clickHouseResponse.getWrittenRows();
            } catch (Exception e) {
                System.out.println("Failed to  load");
                e.printStackTrace();
                throw new Exception();
            }
        }
    
    
  8. shabir1 commented on Aug 22, 2023

    @shabir1
    Author

    @mshustov @mzitnik
    If the file size is 5GB but the number of columns is less (less than 10 columns).then the above method works fine.
    But if the file size is just 200MB but the number of columns is huge (greater than 800 columns) then the above method failed with memory issues.

  9. added
    documentation
    on Aug 29, 2023
  10. added this to the v0.5.1 milestone on Aug 29, 2023
  11. github-actions commented on Jan 8, 2025

    @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!

  12. github-actions commented on Nov 15, 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!

  13. polyglotAI-bot commented on Nov 28, 2026

    @polyglotAI-bot
    Collaborator

    Recommendation: Close — no-op: works as intended
    BinaryStreamUtils.writeString writes one RowBinary String value, so CSV lines in a RowBinary request do not match the table. The reporter's later code, which sends the file with a CSV format, is the correct use.

    • Category: Incorrect usage
    • Classification: impact: none · area: Data types & formats (RowBinary, CSV)
    • Status on main: Not a bug — CSV lines in a RowBinary request fail with code 33; the same lines with the format CSV insert 2 rows.
    • Breaking change: No
    • Duplicates / related: No others

    Analysis: writeString writes a var-int length and the UTF-8 bytes (clickhouse-data/src/main/java/com/clickhouse/data/format/BinaryStreamUtils.java:1660): the server reads the table's columns from these bytes and fails (CANNOT_READ_ALL_DATA). The later MEMORY_LIMIT_EXCEEDED (code 241) for a file with 800 columns is an error of the server's memory limit; ClickHousePassThruStream sends the file bytes unchanged.

    Reproduction: complete program and output

    Changed from the issue's steps: a table (id UInt32, name String) and two CSV lines; client.connect(server) is client.read(server) on main (removed in 0.5.0); compress=0 for #3107; one contrast case with the reporter's later ClickHousePassThruStream code.

    import com.clickhouse.client.ClickHouseClient;
    import com.clickhouse.client.ClickHouseCredentials;
    import com.clickhouse.client.ClickHouseNode;
    import com.clickhouse.client.ClickHouseProtocol;
    import com.clickhouse.client.ClickHouseRequest;
    import com.clickhouse.client.ClickHouseResponse;
    import com.clickhouse.data.ClickHouseCompression;
    import com.clickhouse.data.ClickHouseDataStreamFactory;
    import com.clickhouse.data.ClickHouseFormat;
    import com.clickhouse.data.ClickHousePassThruStream;
    import com.clickhouse.data.ClickHousePipedOutputStream;
    import com.clickhouse.data.ClickHouseRecord;
    import com.clickhouse.data.format.BinaryStreamUtils;
    import java.io.ByteArrayInputStream;
    import java.net.URI;
    import java.util.concurrent.CompletableFuture;
    
    public class Repro {
        static final String URL = System.getenv().getOrDefault("CLICKHOUSE_URL", "http://localhost:8123");
        static final String PASSWORD = System.getenv().getOrDefault("CLICKHOUSE_PASSWORD", "");
        static final String[] CSV = {"1,alice", "2,bob"};
    
        public static void main(String[] args) throws Exception {
            URI u = URI.create(URL);
            ClickHouseNode server = ClickHouseNode.builder()
                    .host(u.getHost()).port(ClickHouseProtocol.HTTP, u.getPort()).database("default")
                    .addOption("compress", "0") // clickhouse-java#3107
                    .credentials(ClickHouseCredentials.fromUserAndPassword("default", PASSWORD))
                    .build();
            try (ClickHouseClient client = ClickHouseClient.newInstance(server.getProtocol())) {
                run(client, server, "DROP TABLE IF EXISTS t1401");
                run(client, server, "CREATE TABLE t1401 (id UInt32, name String) ENGINE = Memory");
    
                // the issue's code: each CSV line written with BinaryStreamUtils.writeString into a RowBinary request
                try {
                    ClickHouseRequest.Mutation request = client.read(server).write().table("t1401")
                            .format(ClickHouseFormat.RowBinary);
                    CompletableFuture<ClickHouseResponse> future;
                    try (ClickHousePipedOutputStream stream = ClickHouseDataStreamFactory.getInstance()
                            .createPipedOutputStream(request.getConfig(), (Runnable) null)) {
                        future = request.data(stream.getInputStream()).execute();
                        for (String line : CSV) {
                            BinaryStreamUtils.writeString(stream, line);
                        }
                    }
                    try (ClickHouseResponse response = future.get()) {
                        System.out.println("RowBinary + writeString(csv line): written rows " + response.getSummary().getWrittenRows());
                    }
                } catch (Exception e) {
                    System.out.println("RowBinary + writeString(csv line): " + e.getCause().getMessage().split("\n")[0]);
                }
                System.out.println("table: " + select(client, server));
    
                // the reporter's later code: the CSV bytes passed through with a CSV format
                run(client, server, "TRUNCATE TABLE t1401");
                ClickHousePassThruStream csv = ClickHousePassThruStream.of(
                        new ByteArrayInputStream(String.join("\n", CSV).getBytes()), ClickHouseCompression.NONE, 0, ClickHouseFormat.CSV);
                long rows = ClickHouseClient.load(server, "t1401", csv).get().getWrittenRows();
                System.out.println("load with ClickHousePassThruStream (CSV): written rows " + rows + ", table: " + select(client, server));
            }
        }
    
        static void run(ClickHouseClient client, ClickHouseNode server, String sql) throws Exception {
            client.read(server).query(sql).executeAndWait().close();
        }
    
        static String select(ClickHouseClient client, ClickHouseNode server) throws Exception {
            StringBuilder sb = new StringBuilder();
            try (ClickHouseResponse r = client.read(server).format(ClickHouseFormat.RowBinaryWithNamesAndTypes)
                    .query("SELECT id, name FROM t1401 ORDER BY id").executeAndWait()) {
                for (ClickHouseRecord rec : r.records()) {
                    sb.append("(").append(rec.getValue(0).asString()).append(", ").append(rec.getValue(1).asString()).append(") ");
                }
            }
            return sb.length() == 0 ? "empty" : sb.toString().trim();
        }
    }

    Output on main (8480ca001), ClickHouse 26.11.4.11:

    RowBinary + writeString(csv line): Code: 33. DB::Exception: Cannot read all data. Bytes read: 9. Bytes expected: 108: (at row 1)
    table: empty
    load with ClickHousePassThruStream (CSV): written rows 2, table: (1, alice) (2, bob)
    

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

  14. added
    client
    data-types
    legacy
    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

    action:verifyclientdata-typesdocumentationduplicatelegacyquestion

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions