[client-v2, jdbc-v2] A null for a Nullable column with a DEFAULT is stored as the default, not NULL

Abierto
#3,421 0 comentarios 0 reacciones 0 asignados Ver en GitHub

Los mantenedores suelen responder en 1 día

Nadie ha tomado este issue todavía.

Evaluación

Dificultad
4/5
Tiempo estimado
3-5 días
Aptitud para principiantes
25/100
Tipo de issue
Error
Claridad
Bastante claro
Estado de actividad
Activo
Stack tecnológico
java, sql
Área
database

Línea de trabajo

Start with writeValuePreamble in client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java (around lines 207-214), where the hasDefault check runs before isNullable. Then look at RowBinaryFormatWriter.commitRow() and POJOSerDe.java:65, and at writeNullableTests in RowBinaryFormatWriterTest. Done requires a maintainer decision on whether null means NULL, and a repro showing NULL is stored. The decision is still open, so wait for it before writing a patch.

Escrito por el modelo de indexación a partir del texto del issue.

Descripción

bug client data-types jdbc

Description

When a column has the type Nullable(T) and a DEFAULT, a Java null for that column is stored as the default value, not NULL. There is no error. Affected entry points:

  • client-v2 POJO insert (Client.register + Client.insert(table, List)): a null field;
  • client-v2 RowBinaryFormatWriter with RowBinaryWithDefaults: setValue(column, null);
  • jdbc-v2 with beta.row_binary_for_simple_insert=true (WriterStatementImpl): setNull, setString(i, null) and setObject(i, null), with executeUpdate() and with executeBatch().

SQL VALUES (NULL) and jdbc-v2 without the writer (PreparedStatementImpl) store NULL for the same row. A Nullable column without a DEFAULT is not affected. #3328 proposes to make the writer the default in jdbc-v2; then setNull stores the default for each such column.

Steps to reproduce
  1. CREATE TABLE t_null_default (id Int32, s Nullable(String) DEFAULT 'dflt') ENGINE = MergeTree ORDER BY id
  2. With the code example, insert one row with s = null through each path: SQL (id 1), POJO (2), RowBinaryFormatWriter (3), jdbc-v2 setNull with the writer off (4) and on (5).
  3. SELECT id, s, isNull(s) FROM t_null_default ORDER BY id
Error Log or Exception StackTrace
1	null	isNull=1
2	dflt	isNull=0
3	dflt	isNull=0
4	null	isNull=1
5	dflt	isNull=0
Expected Behaviour

All five rows store NULL. The server documentation of input_format_null_as_default says: "If column type is nullable, then NULL values are inserted as is, regardless of this setting." The format keeps the two cases apart: for a Nullable(UInt32) DEFAULT 42 cell, 01 means "use the DEFAULT" and 00 01 means NULL (Defaults vs NULL). When the bytes 00 01 are sent by hand with INSERT INTO t_null_default FORMAT RowBinaryWithDefaults, the server stores NULL.

Root cause

For a null value, RowBinaryFormatSerializer.writeValuePreamble (client-v2/src/main/java/com/clickhouse/client/api/data_formats/RowBinaryFormatSerializer.java:207-214) checks hasDefault before isNullable, so it writes the "use default" byte 01, not 00 01. The POJO serializer (POJOSerDe.java:65) and RowBinaryFormatWriter.commitRow() (RowBinaryFormatWriter.java:97) call it. Client.insert (Client.java:1591-1592) and WriterStatementImpl (WriterStatementImpl.java:84-85) use RowBinaryWithDefaults when a column of the table has a default.

The fix needs a maintainer decision: RowBinaryFormatWriter also keeps a column that is not set as null, and RowBinaryFormatWriterTest.writeNullableTests (:1025-1040) expects setValue("nullable_default", null) to give the default. Either a null gives NULL and only a column that is not set gives the default, or the current behavior stays and is documented. Polyglot AI can open a fix PR if a maintainer assigns this issue to @polyglotAI-bot.

Related: #3402 (open) changes the same function for Variant NULL; not this defect.

Code Example
Reproduction program (Java, 57 lines)
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.data_formats.RowBinaryFormatWriter;
import com.clickhouse.client.api.insert.InsertSettings;
import com.clickhouse.client.api.metadata.TableSchema;
import com.clickhouse.data.ClickHouseFormat;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.Types;
import java.util.Collections;
import java.util.Properties;

public class Minimal {
    public static class Row {
        private int id; private String s;
        public Row() {}
        public Row(int id, String s) { this.id = id; this.s = s; }
        public int getId() { return id; }
        public void setId(int id) { this.id = id; }
        public String getS() { return s; }
        public void setS(String s) { this.s = s; }
    }

    public static void main(String[] args) throws Exception {
        String pw = "<password>";
        try (Client client = new Client.Builder().addEndpoint("http://localhost:8123")
                .setUsername("default").setPassword(pw).build()) {
            client.execute("DROP TABLE IF EXISTS t_null_default").get().close();
            client.execute("CREATE TABLE t_null_default (id Int32, s Nullable(String) DEFAULT 'dflt') "
                    + "ENGINE = MergeTree ORDER BY id").get().close();
            client.execute("INSERT INTO t_null_default VALUES (1, NULL)").get().close();      // 1. SQL
            TableSchema schema = client.getTableSchema("t_null_default");
            client.register(Row.class, schema);
            client.insert("t_null_default", Collections.singletonList(new Row(2, null))).get().close(); // 2. POJO
            client.insert("t_null_default", out -> {                                          // 3. writer
                RowBinaryFormatWriter w = new RowBinaryFormatWriter(out, schema, ClickHouseFormat.RowBinaryWithDefaults);
                w.setValue("id", 3);
                w.setValue("s", null);
                w.commitRow();
            }, ClickHouseFormat.RowBinaryWithDefaults, new InsertSettings()).get().close();

            for (String writer : new String[] {"false", "true"}) {                            // 4, 5. jdbc-v2
                Properties p = new Properties();
                p.setProperty("user", "default");
                p.setProperty("password", pw);
                p.setProperty("beta.row_binary_for_simple_insert", writer);
                try (Connection c = new com.clickhouse.jdbc.Driver().connect("jdbc:clickhouse://localhost:8123/default", p);
                     PreparedStatement ps = c.prepareStatement("INSERT INTO t_null_default VALUES (?, ?)")) {
                    ps.setInt(1, writer.equals("true") ? 5 : 4);
                    ps.setNull(2, Types.VARCHAR);
                    ps.executeUpdate();
                }
            }
            client.queryAll("SELECT id, s, isNull(s) AS n FROM t_null_default ORDER BY id").forEach(r ->
                    System.out.println(r.getInteger("id") + "\t" + r.getString("s") + "\tisNull=" + r.getInteger("n")));
        }
    }
}
Configuration
Client Configuration
// Default client settings. Row 5: jdbc-v2 property beta.row_binary_for_simple_insert=true.
Environment
  • Cloud
  • Client version: main at 051a7ecfd (0.12.0-rc1-SNAPSHOT)
  • Language version: OpenJDK 17.0.21.1
  • OS: Linux (Docker)
ClickHouse Server
  • ClickHouse Server version: 26.10.4.207
  • ClickHouse Server non-default settings, if any: none
  • CREATE TABLE statements for tables involved: step 1
  • Sample data for all these tables: none (the code example inserts the rows)

Classification: impact: Data integrity · area: Data types & formats (Nullable with DEFAULT, RowBinaryWithDefaults)


Found by automated analysis (Polyglot AI) while working on ClickHouse/clickhouse-go#2160. Verified against a live server.

Lenguaje dominante
Java
Estrellas
1.6k
Forks
657
Merge medio
2 d 6 h
PR fusionados (30 d)
36

Preparar el entorno

Primeros pasos

  1. Lee el issue completo y luego la guía de contribución del proyecto.
  2. Comenta en el issue que vas a ocuparte — evita que dos personas hagan lo mismo.
  3. Haz un fork del repositorio y trabaja en una rama.
  4. Abre un pull request que haga referencia al número del issue.

Más de ClickHouse/clickhouse-java

Todos los issues de ClickHouse/clickhouse-java

Issues similares

Más issues de Java

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.