Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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());

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.

here is integer changed to string. Would it work?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does work. ClickHouseEnum.value(String) looks up the declared integer for that name (for example ‘inactive’ → 10), so the Java enum is converted by name and the integer is what gets written. Before this change it wrote ordinal(), which is wrong whenever the declared values differ from the position. The new integration tests use values like 5/10 and 500/1000 to check this.

} 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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<GenericRecord> 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 <T> void writeReadVerify(String table, String tableDef, Class<T> dtoClass, List<T> data,
BiConsumer<List<T>, T> rowVerifier) throws Exception {
writeReadVerify(table, tableDef, dtoClass, data, rowVerifier, null);
Expand Down
1 change: 1 addition & 0 deletions history/latest/3304.md
Original file line number Diff line number Diff line change
@@ -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)
Original file line number Diff line number Diff line change
Expand Up @@ -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()) {
Expand Down
Loading