Skip to content
Merged
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 @@ -177,8 +177,18 @@ private static ClickHouseColumn update(ClickHouseColumn column) {
case Enum:
case Enum8:
case Enum16:
column.template = ClickHouseEnumValue
.ofNull(column.enumConstants = new ClickHouseEnum(column.parameters));
column.enumConstants = new ClickHouseEnum(column.parameters);
if (column.dataType == ClickHouseDataType.Enum && column.enumConstants.size() > 0) {
// Same as the server: a bare Enum is Enum8 when all its values fit into Int8, else Enum16.
column.dataType = isInt8(column.enumConstants.getValues()) ? ClickHouseDataType.Enum8
: ClickHouseDataType.Enum16;
column.valueDataType = column.dataType;
if (!column.nullable) {
column.fixedByteLength = true;
column.estimatedByteLength += column.dataType.getByteLength();
}
}
column.template = ClickHouseEnumValue.ofNull(column.enumConstants);
break;
case Int8:
column.template = ClickHouseByteValue.ofNull();
Expand Down Expand Up @@ -365,6 +375,15 @@ private static ClickHouseColumn update(ClickHouseColumn column) {
return column;
}

private static boolean isInt8(int[] values) {
for (int value : values) {
if (value < Byte.MIN_VALUE || value > Byte.MAX_VALUE) {
return false;
}
}
return true;
}

private static ClickHouseColumn createGeometryVariantColumn() {
// The six geometry variants that exist since CH 25.11. Variant nested columns are ordered by
// type name, which reproduces the discriminators the server assigns to them.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ public enum ClickHouseDataType implements SQLType {
DateTime(LocalDateTime.class, true, false, false, 0, 29, 0, 0, 9, false, 0x11, "TIMESTAMP"),
DateTime32(LocalDateTime.class, true, false, false, 4, 19, 0, 0, 0, false, 0x12),
DateTime64(LocalDateTime.class, true, false, false, 8, 29, 3, 0, 9, false, 0x14), // we always write timezone as argument
Enum(String.class, true, true, false, 0, 0, 0, 0, 0, false),
Enum8(String.class, true, true, false, 1, 0, 0, 0, 0, false, 0x17, "ENUM"),
Enum(String.class, true, true, false, 0, 0, 0, 0, 0, false, "ENUM"),
Enum8(String.class, true, true, false, 1, 0, 0, 0, 0, false, 0x17),
Enum16(String.class, true, true, false, 2, 0, 0, 0, 0, false, 0x18),
FixedString(String.class, true, true, false, 0, 0, 0, 0, 0, false, 0x16, "BINARY"),
Int8(Byte.class, false, true, true, 1, 3, 0, 0, 0, false, 0x07,"BYTE", "INT1", "INT1 SIGNED", "TINYINT",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@
public class ClickHouseColumnTest {
@DataProvider(name = "enumTypesProvider")
private Object[][] getEnumTypes() {
return new Object[][] { { "Enum" }, { "Enum8" }, { "Enum16" } };
return new Object[][] { { "Enum", ClickHouseDataType.Enum8 }, { "Enum8", ClickHouseDataType.Enum8 },
{ "Enum16", ClickHouseDataType.Enum16 } };
}

@DataProvider(name = "objectTypesProvider")
Expand Down Expand Up @@ -246,25 +247,69 @@ public void testArray() {
}

@Test(dataProvider = "enumTypesProvider", groups = { "unit" })
public void testEnum(String typeName) {
public void testEnum(String typeName, ClickHouseDataType expectedType) {
Assert.assertThrows(IllegalArgumentException.class,
() -> ClickHouseColumn.of("e", typeName + "('Query''Start' = a)"));
Assert.assertThrows(IllegalArgumentException.class, () -> ClickHouseColumn.of("e", typeName + "(aa,1)"));
ClickHouseColumn column = ClickHouseColumn.of("e", typeName + "('Query''Start' = 1, 'Query\\'Finish' = 10)");
Assert.assertTrue(column.isEnum());
Assert.assertEquals(column.getDataType(), ClickHouseDataType.of(typeName));
Assert.assertEquals(column.getDataType(), expectedType);
Assert.assertThrows(IllegalArgumentException.class, () -> column.getEnumConstants().name(2));
Assert.assertThrows(IllegalArgumentException.class, () -> column.getEnumConstants().value(""));
Assert.assertEquals(column.getEnumConstants().name(1), "Query'Start");
Assert.assertEquals(column.getEnumConstants().name(10), "Query'Finish");
Assert.assertEquals(column.getEnumConstants().value("Query'Start"), 1);
Assert.assertEquals(column.getEnumConstants().value("Query'Finish"), 10);
if (column.getDataType() != ClickHouseDataType.Enum) { // virtual type
Assert.assertTrue(column.isFixedLength(), "Should have fixed length in byte");
}
Assert.assertTrue(column.isFixedLength(), "Should have fixed length in byte");
Assert.assertEquals(column.getEstimatedLength(), column.getDataType().getByteLength());
}

@DataProvider(name = "enumWidthProvider")
private Object[][] getEnumWidths() {
return new Object[][] {
{ "Enum('a' = -128, 'b' = 127)", ClickHouseDataType.Enum8 },
{ "Enum('a' = 1, 'b' = 128)", ClickHouseDataType.Enum16 },
{ "Enum('a' = -129)", ClickHouseDataType.Enum16 },
{ "enum('a' = 1000)", ClickHouseDataType.Enum16 },
{ "ENUM('a' = 1)", ClickHouseDataType.Enum8 },
{ "Enum8('a' = 1)", ClickHouseDataType.Enum8 },
{ "Enum16('a' = 1)", ClickHouseDataType.Enum16 },
};
}

@Test(dataProvider = "enumWidthProvider", groups = { "unit" })
public void testEnumWidth(String typeName, ClickHouseDataType expectedType) {
ClickHouseColumn column = ClickHouseColumn.of("e", typeName);
Assert.assertEquals(column.getDataType(), expectedType);
Assert.assertEquals(column.getValueDataType(), expectedType);
Assert.assertEquals(column.getOriginalTypeName(), typeName);
Assert.assertTrue(column.isFixedLength());
Assert.assertEquals(column.getEstimatedLength(), expectedType.getByteLength());

ClickHouseColumn nullable = ClickHouseColumn.of("e", "Nullable(" + typeName + ")");
Assert.assertEquals(nullable.getDataType(), expectedType);
Assert.assertTrue(nullable.isNullable());

Assert.assertEquals(ClickHouseColumn.of("e", "Array(" + typeName + ")").getArrayBaseColumn().getDataType(),
expectedType);
Assert.assertEquals(ClickHouseColumn.of("e", "Map(String, " + typeName + ")").getValueInfo().getDataType(),
expectedType);
ClickHouseColumn tuple = ClickHouseColumn.of("e", "Tuple(" + typeName + ", UInt8)");
Assert.assertEquals(tuple.getNestedColumns().get(0).getDataType(), expectedType);
Assert.assertEquals(tuple.getNestedColumns().get(1).getDataType(), ClickHouseDataType.UInt8);
ClickHouseColumn variant = ClickHouseColumn.of("e", "Variant(" + typeName + ", Bool)");
Assert.assertEquals(variant.getNestedColumns().get(0).getDataType(), ClickHouseDataType.Bool);
Assert.assertEquals(variant.getNestedColumns().get(1).getDataType(), expectedType);
}

@Test(groups = { "unit" })
public void testBareEnumWidthFromDataType() {
Assert.assertEquals(ClickHouseColumn.of("e", ClickHouseDataType.Enum, false, false, "'a'=1").getDataType(),
ClickHouseDataType.Enum8);
Assert.assertEquals(ClickHouseColumn.of("e", ClickHouseDataType.Enum, false, false, "'a'=1000").getDataType(),
ClickHouseDataType.Enum16);
}

@Test(dataProvider = "objectTypesProvider", groups = { "unit" })
public void testObjectType(String typeName) {
ClickHouseColumn.of("o", "Tuple(TINYINT SIGNED null)");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,15 @@ public void testMapping() {
}
}

@Test(groups = { "unit" })
public void testEnumTypeNames() {
Assert.assertEquals(ClickHouseDataType.of("Enum"), ClickHouseDataType.Enum);
Assert.assertEquals(ClickHouseDataType.of("enum"), ClickHouseDataType.Enum);
Assert.assertEquals(ClickHouseDataType.of("ENUM"), ClickHouseDataType.Enum);
Assert.assertEquals(ClickHouseDataType.of("Enum8"), ClickHouseDataType.Enum8);
Assert.assertEquals(ClickHouseDataType.of("Enum16"), ClickHouseDataType.Enum16);
}

@Test(groups = { "unit" })
public void testMatch() {
List<String> matched = ClickHouseDataType.match("INT1");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,12 @@ private <T> T readValue(ClickHouseColumn column, Class<?> typeHint, boolean stri
case Enum8: {
byte enum8Val = (byte) readUnsignedByte();
String name = actualColumn.getEnumConstants().nameNullable(enum8Val);
return (T) new EnumValue(name == null ? "<unknown>" : name, enum8Val);
return (T) new EnumValue(name == null ? "<unknown>" : name, enum8Val, ClickHouseDataType.Enum8);
}
case Enum16: {
short enum16Val = (short) readUnsignedShortLE();
String name = actualColumn.getEnumConstants().nameNullable(enum16Val);
return (T) new EnumValue(name == null ? "<unknown>" : name, enum16Val);
return (T) new EnumValue(name == null ? "<unknown>" : name, enum16Val, ClickHouseDataType.Enum16);
}
case Date:
return (T) readDateAsLocalDate();
Expand Down Expand Up @@ -970,9 +970,24 @@ public static class EnumValue extends Number {

public final int value;

/**
* Type of the value: {@link ClickHouseDataType#Enum8} (1 byte) or {@link ClickHouseDataType#Enum16} (2 bytes).
*/
public final ClickHouseDataType dataType;

/**
* Creates a value of the smallest Enum type that holds it: {@code Enum8} when the value is in -128..127,
* {@code Enum16} otherwise.
*/
public EnumValue(String name, int value) {
this(name, value, value >= Byte.MIN_VALUE && value <= Byte.MAX_VALUE ?
ClickHouseDataType.Enum8 : ClickHouseDataType.Enum16);
}

public EnumValue(String name, int value, ClickHouseDataType dataType) {
this.name = name;
this.value = value;
this.dataType = dataType;
}

@Override
Expand All @@ -999,6 +1014,10 @@ public String getName() {
return name;
}

public ClickHouseDataType getDataType() {
return dataType;
}

@Override
public String toString() {
return name;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@
import com.clickhouse.client.api.query.GenericRecord;
import com.clickhouse.client.api.query.QueryResponse;
import com.clickhouse.client.api.query.QuerySettings;
import com.clickhouse.client.api.sql.SQLUtils;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.ClickHouseFormat;
import lombok.Data;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import java.math.BigInteger;
Expand Down Expand Up @@ -353,6 +356,40 @@ void testGetObjectArrayMultipleRows() {
}
}

@DataProvider(name = "enumTypesInSchema")
private Object[][] enumTypesInSchema() {
return new Object[][]{
{"Enum('a' = 1000)", "a", 1000, ClickHouseDataType.Enum16},
{"enum('a' = 1, 'b' = 1000)", "a", 1, ClickHouseDataType.Enum16},
{"ENUM('a' = -129)", "a", -129, ClickHouseDataType.Enum16},
{"Enum('a' = 1, 'b' = 128)", "b", 128, ClickHouseDataType.Enum16},
{"Enum('a' = -128, 'b' = 127)", "a", -128, ClickHouseDataType.Enum8},
{"Enum8('a' = 1)", "a", 1, ClickHouseDataType.Enum8},
{"Enum16('a' = 1000)", "a", 1000, ClickHouseDataType.Enum16},
{"Nullable(Enum('a' = 1000))", "a", 1000, ClickHouseDataType.Enum16},
};
}

@Test(groups = {"integration"}, dataProvider = "enumTypesInSchema")
void testReadEnumWithSchemaFromTypeName(String type, String name, int value, ClickHouseDataType expectedType) throws Exception {
TableSchema schema = new TableSchema(Arrays.asList(ClickHouseColumn.of("e", type), ClickHouseColumn.of("u", "UInt8")));
String sql = "SELECT CAST(" + SQLUtils.enquoteLiteral(name) + ", " + SQLUtils.enquoteLiteral(type)
+ ") AS e, toUInt8(7) AS u FROM numbers(2)";
QuerySettings settings = new QuerySettings().setFormat(ClickHouseFormat.RowBinary);
try (Client client = newClient().build(); QueryResponse response = client.query(sql, settings).get()) {
ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response, schema);
for (int row = 0; row < 2; row++) {
Assert.assertNotNull(reader.next());
BinaryStreamReader.EnumValue enumValue = reader.readValue("e");
Assert.assertEquals(enumValue.getName(), name);
Assert.assertEquals(enumValue.intValue(), value);
Assert.assertEquals(enumValue.getDataType(), expectedType);
Assert.assertEquals(reader.getShort("u"), 7);
}
Assert.assertNull(reader.next());
}
}

@Test(groups = {"integration"})
void testRowBinaryEmptyResult() throws Exception {
try (Client client = newClient().build()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import com.clickhouse.client.api.query.QueryResponse;
import com.clickhouse.client.api.query.QuerySettings;
import com.clickhouse.client.api.sql.SQLUtils;
import com.clickhouse.data.ClickHouseColumn;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.ClickHouseFormat;
import com.clickhouse.data.ClickHouseVersion;
Expand Down Expand Up @@ -1179,6 +1180,51 @@ public void testVariantWithEnums() throws Exception {
});
}

@DataProvider(name = "variantWithEnumSchemas")
public Object[][] variantWithEnumSchemas() {
return new Object[][]{
{"Variant(Bool, Enum('a' = 1, 'b' = 1000))", true},
{"Variant(Bool, Enum('a' = 1, 'b' = 1000))", false},
{"Variant(Bool, ENUM('a' = 1, 'b' = 1000))", true},
};
}

@Test(groups = {"integration"}, dataProvider = "variantWithEnumSchemas")
public void testVariantWithEnum16(String variantType, boolean schemaFromTypeName) throws Exception {
if (isVersionMatch("(,24.8]")) {
return;
}

String enumType = "Enum16('a' = 1, 'b' = 1000)";
String sql = "SELECT arrayJoin([CAST(CAST('b', " + SQLUtils.enquoteLiteral(enumType) + "), " + SQLUtils.enquoteLiteral(variantType) + "), "
+ "CAST(CAST('a', " + SQLUtils.enquoteLiteral(enumType) + "), " + SQLUtils.enquoteLiteral(variantType) + "), "
+ "CAST(true, " + SQLUtils.enquoteLiteral(variantType) + ")]) AS v, 42::Int32 AS num";
QuerySettings settings = new QuerySettings().serverSetting("allow_experimental_variant_type", "1");
TableSchema schema = null;
if (schemaFromTypeName) {
settings.setFormat(ClickHouseFormat.RowBinary);
schema = new TableSchema(Arrays.asList(ClickHouseColumn.of("v", variantType), ClickHouseColumn.of("num", "Int32")));
}

try (QueryResponse response = client.query(sql, settings).get()) {
ClickHouseBinaryFormatReader reader = schema == null ? client.newBinaryFormatReader(response)
: client.newBinaryFormatReader(response, schema);
Object[][] expected = {{"b", 1000}, {"a", 1}};
for (Object[] e : expected) {
Assert.assertNotNull(reader.next());
BinaryStreamReader.EnumValue enumValue = reader.readValue("v");
Assert.assertEquals(enumValue.getName(), e[0]);
Assert.assertEquals(enumValue.intValue(), e[1]);
Assert.assertEquals(enumValue.getDataType(), ClickHouseDataType.Enum16);
Assert.assertEquals(reader.getInteger("num"), 42);
}
Assert.assertNotNull(reader.next());
Assert.assertEquals(reader.readValue("v"), Boolean.TRUE);
Assert.assertEquals(reader.getInteger("num"), 42);
Assert.assertNull(reader.next());
}
}

@Test(groups = {"integration"}, enabled = false)
public void testVariantWithTuple() throws Exception {
// TODO: same as array
Expand Down Expand Up @@ -1588,6 +1634,32 @@ public void testDynamicWithParametrizedElementType(String elementType, String va
Assert.assertEquals(records.get(0).getInteger("num"), 42);
}

@DataProvider(name = "dynamicEnumValues")
public Object[][] dynamicEnumValues() {
return new Object[][]{
{"Enum('a' = 1, 'b' = 1000)", "b", 1000, ClickHouseDataType.Enum16},
{"Enum('a' = 1, 'b' = 1000)", "a", 1, ClickHouseDataType.Enum16},
{"Enum('a' = -129)", "a", -129, ClickHouseDataType.Enum16},
{"Enum('a' = -128, 'b' = 127)", "b", 127, ClickHouseDataType.Enum8},
{"Enum16('a' = 1)", "a", 1, ClickHouseDataType.Enum16},
};
}

@Test(groups = {"integration"}, dataProvider = "dynamicEnumValues")
public void testDynamicWithEnum(String enumType, String name, int value, ClickHouseDataType expectedType) throws Exception {
if (isVersionMatch("(,24.8]")) {
return;
}

List<GenericRecord> records = client.queryAll("SELECT CAST(" + SQLUtils.enquoteLiteral(name) + ", "
+ SQLUtils.enquoteLiteral(enumType) + ")::Dynamic AS v, 42::Int32 AS num");
BinaryStreamReader.EnumValue enumValue = (BinaryStreamReader.EnumValue) records.get(0).getObject("v");
Assert.assertEquals(enumValue.getName(), name);
Assert.assertEquals(enumValue.intValue(), value);
Assert.assertEquals(enumValue.getDataType(), expectedType);
Assert.assertEquals(records.get(0).getInteger("num"), 42);
}

@Test(groups = {"integration"})
public void testDynamicWithEnum8WithMoreThan127Constants() throws Exception {
if (isVersionMatch("(,24.8]")) {
Expand Down
Loading
Loading