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..5715614eb 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 @@ -228,6 +228,12 @@ private static Map, ClickHouseColumn> getPredefinedTypeColumnsMap() { } public static ClickHouseColumn valueToColumnForDynamicType(Object value) { + return valueToColumnForDynamicType(value, null); + } + + // enclosingMap is null when no map holds the value. Otherwise it is a pair of the map that holds + // the value and the enclosingMap of that map. + private static ClickHouseColumn valueToColumnForDynamicType(Object value, Object[] enclosingMap) { ClickHouseColumn column; if (value instanceof ZonedDateTime) { ZonedDateTime dt = (ZonedDateTime) value; @@ -275,10 +281,16 @@ public static ClickHouseColumn valueToColumnForDynamicType(Object value) { column = ClickHouseColumn.of("v", decType.name() + "(" + scale + ")"); } else if (value instanceof Map) { Map map = (Map) value; + for (Object[] holder = enclosingMap; holder != null; holder = (Object[]) holder[1]) { + if (holder[0] == map) { + throw containsItself(map); + } + } + Object[] entryHolder = {map, enclosingMap}; // TODO: handle empty map? Map.Entry entry = map.entrySet().iterator().next(); - ClickHouseColumn keyInfo = valueToColumnForDynamicType(entry.getKey()); - ClickHouseColumn valueInfo = valueToColumnForDynamicType(entry.getValue()); + ClickHouseColumn keyInfo = valueToColumnForDynamicType(entry.getKey(), entryHolder); + ClickHouseColumn valueInfo = valueToColumnForDynamicType(entry.getValue(), entryHolder); column = ClickHouseColumn.of("v", "Map(" + keyInfo.getOriginalTypeName() + ", " + valueInfo.getOriginalTypeName() + ")"); } else if (value instanceof Enum) { column = enumValue2Column((Enum)value); @@ -299,6 +311,12 @@ public static ClickHouseColumn valueToColumnForDynamicType(Object value) { return column; } + // No column type fits a value that contains itself, because the type would never end. + private static ClientException containsItself(Object container) { + return new ClientException("Cannot serialize " + container.getClass() + + " into a Dynamic column because it contains itself"); + } + // Returns null if cannot convert // The problem here is that >2-dimensional array would require traversing all value // to detect correct depth. Consider this example @@ -316,8 +334,9 @@ private static ClickHouseColumn listValue2Column(Object value) { } if (value instanceof List || (value.getClass().isArray())) { + // An entry is the array or list, its depth and the entry of the array or list that holds it Stack arrays = new Stack<>(); - arrays.push(new Object[]{value, 1}); + arrays.push(new Object[]{value, 1, null}); int maxDepth = 0; boolean hasNulls = false; ClickHouseColumn arrayBaseColumn = null; @@ -325,6 +344,11 @@ private static ClickHouseColumn listValue2Column(Object value) { int insertPos = 0; while (!arrays.isEmpty()) { Object[] arr = arrays.pop(); + for (Object[] holder = (Object[]) arr[2]; holder != null; holder = (Object[]) holder[2]) { + if (holder[0] == arr[0]) { + throw containsItself(arr[0]); + } + } int depth = (Integer) arr[1]; if (depth > maxDepth) { maxDepth = depth; @@ -340,7 +364,7 @@ private static ClickHouseColumn listValue2Column(Object value) { if (!hasNulls && item == null) { hasNulls = true; } else if (item != null && (item instanceof List || item.getClass().isArray())) { - arrays.push(new Object[]{item, depth + 1}); + arrays.push(new Object[]{item, depth + 1, arr}); } else if (arrayBaseColumn == null && item != null) { arrayBaseColumn = PREDEFINED_TYPE_COLUMNS.get(item.getClass()); if (arrayBaseColumn == null) { 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..d0ba9bcbc 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 @@ -18,11 +18,13 @@ import java.time.LocalDate; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.TimeZone; import java.util.UUID; +import java.util.function.Supplier; @Test(groups = {"unit"}) public class SerializerUtilsTest { @@ -443,6 +445,66 @@ public void testValueToColumnForDynamicTypeRejectsOversizedDecimal(BigDecimal va () -> SerializerUtils.valueToColumnForDynamicType(value)); } + @DataProvider(name = "dynamicValuesThatContainThemselves") + public Object[][] dynamicValuesThatContainThemselves() { + Object[] array = new Object[1]; + array[0] = array; + List list = new ArrayList<>(); + list.add(list); + Map map = new LinkedHashMap<>(); + map.put("self", map); + Object[] arrayInList = new Object[1]; + List listInArray = new ArrayList<>(); + arrayInList[0] = listInArray; + listInArray.add(arrayInList); + Map outerMap = new LinkedHashMap<>(); + Map innerMap = new LinkedHashMap<>(); + outerMap.put("inner", innerMap); + innerMap.put("outer", outerMap); + // Test reports print the parameters, and two maps that hold each other cannot be printed, + // so each value is passed as a supplier. + return new Object[][]{ + {(Supplier) () -> array, Object[].class}, + {(Supplier) () -> list, ArrayList.class}, + {(Supplier) () -> map, LinkedHashMap.class}, + {(Supplier) () -> arrayInList, Object[].class}, + {(Supplier) () -> outerMap, LinkedHashMap.class}, + {(Supplier) () -> Collections.singletonList(array), Object[].class}, + {(Supplier) () -> Collections.singletonMap("map", map), LinkedHashMap.class}, + }; + } + + @Test(dataProvider = "dynamicValuesThatContainThemselves", timeOut = 10000) + public void testValueToColumnForDynamicTypeRejectsValueThatContainsItself(Supplier value, Class repeatedClass) { + ClientException ex = Assert.expectThrows(ClientException.class, + () -> SerializerUtils.valueToColumnForDynamicType(value.get())); + Assert.assertEquals(ex.getMessage(), + "Cannot serialize " + repeatedClass + " into a Dynamic column because it contains itself"); + } + + @DataProvider(name = "dynamicValuesWithSharedContainers") + public Object[][] dynamicValuesWithSharedContainers() { + Object[] array = {1}; + List list = Arrays.asList(1, 2); + Object[] arrayOfEmptyArray = {new Object[0]}; + Map map = new LinkedHashMap<>(); + map.put("a", 1); + Map, Map> mapOfMaps = new LinkedHashMap<>(); + mapOfMaps.put(map, map); + return new Object[][]{ + {new Object[]{array, array}, "Array(Array(Int32))"}, + {Arrays.asList(list, list), "Array(Array(Int32))"}, + // The shared array is read twice before a value is found + {new Object[]{new Object[]{new Object[]{1}}, arrayOfEmptyArray, arrayOfEmptyArray}, "Array(Array(Array(Int32)))"}, + {mapOfMaps, "Map(Map(String, Int32), Map(String, Int32))"}, + }; + } + + @Test(dataProvider = "dynamicValuesWithSharedContainers") + public void testValueToColumnForDynamicTypeAcceptsSharedContainers(Object value, String expectedType) { + Assert.assertEquals(SerializerUtils.valueToColumnForDynamicType(value).getOriginalTypeName(), expectedType); + } + @Test(dataProvider = "nonNullableEnumTypes") public void testNullIntoNonNullableEnumThrowsIllegalArgument(String typeName) { ClickHouseColumn column = ClickHouseColumn.of("bs_flag", typeName); diff --git a/history/latest/3177.md b/history/latest/3177.md new file mode 100644 index 000000000..84ea9476c --- /dev/null +++ b/history/latest/3177.md @@ -0,0 +1,8 @@ +- **[client-v2]** Fixed writing a value that contains itself into a `Dynamic` column. The client walks the value to + find its type. For an array or `List` that holds itself this walk never ended, so the insert never returned. For a + `Map` that holds itself it threw `StackOverflowError`, and later requests of the same client failed with + `Connection pool shut down`. A cycle through more than one container, for example an array that holds a list that + holds the array, failed in the same way. Such a value now fails at once with `ClientException` and the message + `Cannot serialize into a Dynamic column because it contains itself`. A value that holds the same array, + list or map more than once without containing itself keeps its type, for example `Array(Array(Int32))`. + (https://github.com/ClickHouse/clickhouse-java/issues/3177)