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 @@ -228,6 +228,12 @@ private static Map<Class<?>, 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;
Expand Down Expand Up @@ -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);
Expand All @@ -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
Expand All @@ -316,15 +334,21 @@ 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<Object[]> 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;
StringBuilder typeStr = new StringBuilder();
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;
Expand All @@ -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) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<Object> list = new ArrayList<>();
list.add(list);
Map<String, Object> map = new LinkedHashMap<>();
map.put("self", map);
Object[] arrayInList = new Object[1];
List<Object> listInArray = new ArrayList<>();
arrayInList[0] = listInArray;
listInArray.add(arrayInList);
Map<String, Object> outerMap = new LinkedHashMap<>();
Map<String, Object> 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<Integer> list = Arrays.asList(1, 2);
Object[] arrayOfEmptyArray = {new Object[0]};
Map<String, Integer> map = new LinkedHashMap<>();
map.put("a", 1);
Map<Map<String, Integer>, Map<String, Integer>> 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);
Expand Down
8 changes: 8 additions & 0 deletions history/latest/3177.md
Original file line number Diff line number Diff line change
@@ -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 <class> 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)
Loading