diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java index 50f9136e2..75b60da15 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/SerializerUtils.java @@ -864,13 +864,12 @@ public static void serializeEnumData(OutputStream stream, ClickHouseColumn colum if (value instanceof String) { enumValue = column.getEnumConstants().value((String) value); } else if (value instanceof Number) { - enumValue = ((Number) value).intValue(); + enumValue = column.getEnumConstants().validate(((Number) value).intValue()); } else if (value instanceof Enum) { - enumValue = ((Enum)value).ordinal(); + enumValue = column.getEnumConstants().value(((Enum) value).name()); } else { throw new IllegalArgumentException("Cannot write value of class " + value.getClass() + " into column with Enum type " + column.getOriginalTypeName()); } - if (column.getDataType() == ClickHouseDataType.Enum8) { BinaryStreamUtils.writeInt8(stream, enumValue); } else if (column.getDataType() == ClickHouseDataType.Enum16) { diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsTest.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsTest.java index 02edbce58..e86cce8ca 100644 --- a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsTest.java +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/internal/SerializerUtilsTest.java @@ -481,6 +481,7 @@ public void testEnumSerializationUnaffectedByNullGuard() throws Exception { Assert.assertEquals(valueOut.toByteArray(), new byte[] {2}); } + @Test(dataProvider = "nestedNullableData") public void testNestedNullableRoundTrip(String typeName, Object value) throws Exception { ClickHouseColumn column = ClickHouseColumn.of("v", typeName); diff --git a/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java b/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java index 5d014e8c6..8d223f0f7 100644 --- a/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/datatypes/DataTypeTests.java @@ -97,7 +97,81 @@ public void setUp() throws IOException { public void tearDown() { client.close(); } + public enum EnumInsertStatus { active, inactive } + @Data + @AllArgsConstructor + @NoArgsConstructor + public static class DTOForEnumInsertTests { + private int rowId; + private Object status; + } + + @DataProvider(name = "enumInsertValues") + public static Object[][] enumInsertValues() { + return new Object[][] { + {"Enum8('active' = 5, 'inactive' = 10)", "inactive", "inactive", 10}, + {"Enum8('active' = 5, 'inactive' = 10)", 5, "active", 5}, + {"Enum8('active' = 5, 'inactive' = 10)", EnumInsertStatus.inactive, "inactive", 10}, + {"Enum16('active' = 500, 'inactive' = 1000)", "inactive", "inactive", 1000}, + {"Enum16('active' = 500, 'inactive' = 1000)", 500, "active", 500}, + {"Enum16('active' = 500, 'inactive' = 1000)", EnumInsertStatus.inactive, "inactive", 1000}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "enumInsertValues") + public void testInsertIntoEnumWritesDeclaredValue(String enumType, Object input, + String expectedName, int expectedValue) throws Exception { + final String table = "test_enum_insert_" + System.nanoTime(); + client.execute("DROP TABLE IF EXISTS " + table).get(); + client.execute(tableDefinition(table, "rowId Int32", "status " + enumType)).get(); + + client.register(DTOForEnumInsertTests.class, client.getTableSchema(table)); + client.insert(table, Collections.singletonList(new DTOForEnumInsertTests(1, input))) + .get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS); + + List rows = client.queryAll( + "SELECT status, CAST(status AS Int32) AS v FROM " + table); + Assert.assertEquals(rows.size(), 1); + Assert.assertEquals(rows.get(0).getString("status"), expectedName); + Assert.assertEquals(rows.get(0).getInteger("v"), expectedValue); + } + + @DataProvider(name = "enumInsertInvalidValues") + public static Object[][] enumInsertInvalidValues() { + return new Object[][] { + {"Enum8('active' = 5, 'inactive' = 10)", 7, "Unknown enum value: 7"}, + {"Enum16('active' = 500, 'inactive' = 1000)", 7, "Unknown enum value: 7"}, + {"Enum8('inactive' = 10)", EnumInsertStatus.active, "Unknown enum name: active"}, + }; + } + + @Test(groups = {"integration"}, dataProvider = "enumInsertInvalidValues") + public void testInsertInvalidEnumValueThrows(String enumType, Object input, String expectedMessage) throws Exception { + final String table = "test_enum_insert_invalid_" + System.nanoTime(); + client.execute("DROP TABLE IF EXISTS " + table).get(); + client.execute(tableDefinition(table, "rowId Int32", "status " + enumType)).get(); + + client.register(DTOForEnumInsertTests.class, client.getTableSchema(table)); + + Exception thrown = null; + try { + client.insert(table, Collections.singletonList(new DTOForEnumInsertTests(1, input))) + .get(EXECUTE_CMD_TIMEOUT, TimeUnit.SECONDS); + } catch (Exception e) { + thrown = e; + } + + Assert.assertNotNull(thrown, "Expected the insert to fail for " + input + " into " + enumType); + boolean found = false; + for (Throwable t = thrown; t != null; t = t.getCause()) { + if (t.getMessage() != null && t.getMessage().contains(expectedMessage)) { + found = true; + break; + } + } + Assert.assertTrue(found, "Expected message '" + expectedMessage + "' but got: " + thrown); + } private void writeReadVerify(String table, String tableDef, Class dtoClass, List data, BiConsumer, T> rowVerifier) throws Exception { writeReadVerify(table, tableDef, dtoClass, data, rowVerifier, null); diff --git a/history/latest/3304.md b/history/latest/3304.md new file mode 100644 index 000000000..edd27157b --- /dev/null +++ b/history/latest/3304.md @@ -0,0 +1 @@ +- **[client-v2]** Enum8/Enum16 inserts now validate the value on the client. A number that is not a declared enum member, or a Java `Enum` constant whose name is not declared in the column, fails with `IllegalArgumentException`. A Java `Enum` is now written as the value declared for its name instead of its `ordinal()`. (https://github.com/ClickHouse/clickhouse-java/issues/3304) diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/JdbcDataTypeTests.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/JdbcDataTypeTests.java index b169f1e59..15d3a9d5d 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/JdbcDataTypeTests.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/JdbcDataTypeTests.java @@ -75,6 +75,59 @@ public static void setUp() throws SQLException { Driver.load(); } + private Properties rowBinaryWriterProperties() { + Properties props = new Properties(); + props.setProperty(DriverProperties.BETA_ROW_BINARY_WRITER.getKey(), "true"); + return props; + } + + @Test(groups = {"integration"}) + public void testInsertNumberIntoEnumColumn() throws SQLException { + String table = "jdbc_enum_number_insert_" + System.nanoTime(); + runQuery("CREATE TABLE " + table + " (id Int32, e8 Enum8('active' = 5, 'inactive' = 10), " + + "e16 Enum16('active' = 500, 'inactive' = 1000)) ENGINE = Memory"); + + try (Connection conn = getJdbcConnection(rowBinaryWriterProperties()); + PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?)")) { + stmt.setInt(1, 1); + stmt.setInt(2, 10); + stmt.setInt(3, 500); + stmt.executeUpdate(); + } + + try (Connection conn = getJdbcConnection(); + Statement stmt = conn.createStatement(); + ResultSet rs = stmt.executeQuery("SELECT e8, CAST(e8 AS Int32), e16, CAST(e16 AS Int32) FROM " + table)) { + Assert.assertTrue(rs.next()); + Assert.assertEquals(rs.getString(1), "inactive"); + Assert.assertEquals(rs.getInt(2), 10); + Assert.assertEquals(rs.getString(3), "active"); + Assert.assertEquals(rs.getInt(4), 500); + } + } + + @Test(groups = {"integration"}) + public void testInsertNonMemberNumberIntoEnumColumnThrows() throws SQLException { + String table = "jdbc_enum_invalid_insert_" + System.nanoTime(); + runQuery("CREATE TABLE " + table + " (id Int32, e8 Enum8('active' = 5, 'inactive' = 10)) ENGINE = Memory"); + + try (Connection conn = getJdbcConnection(rowBinaryWriterProperties()); + PreparedStatement stmt = conn.prepareStatement("INSERT INTO " + table + " VALUES (?, ?)")) { + stmt.setInt(1, 1); + stmt.setInt(2, 7); + SQLException ex = Assert.expectThrows(SQLException.class, stmt::executeUpdate); + + boolean found = false; + for (Throwable t = ex; t != null; t = t.getCause()) { + if (t.getMessage() != null && t.getMessage().contains("Unknown enum value: 7")) { + found = true; + break; + } + } + Assert.assertTrue(found, "Expected 'Unknown enum value: 7' but got: " + ex); + } + } + private int insertData(String sql) throws SQLException { try (Connection conn = getJdbcConnection()) { try (Statement stmt = conn.createStatement()) {