NIFI-7637: Ensure all array elements are compatible in DataTypeUtils.isArrayTypeCompatible() (#4612)

This commit is contained in:
Matthew Burgess 2020-10-27 11:39:28 -04:00 committed by GitHub
parent 77b4abc21e
commit 4fee076561
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 23 additions and 4 deletions

View File

@ -720,10 +720,21 @@ public class DataTypeUtils {
}
public static boolean isArrayTypeCompatible(final Object value, final DataType elementDataType) {
return value != null
// Either an object array or a String to be converted to byte[]
&& (value instanceof Object[]
|| (value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType)));
if (value == null) {
return false;
}
// Either an object array (check the element type) or a String to be converted to byte[]
if (value instanceof Object[]) {
for (Object o : ((Object[]) value)) {
// Check each element to ensure its type is the same or can be coerced (if need be)
if (!isCompatibleDataType(o, elementDataType)) {
return false;
}
}
return true;
} else {
return value instanceof String && RecordFieldType.BYTE.getDataType().equals(elementDataType);
}
}
@SuppressWarnings("unchecked")

View File

@ -424,6 +424,14 @@ public class TestDataTypeUtils {
assertFalse(DataTypeUtils.isCompatibleDataType(new Long[]{1L, 2L}, dataType));
}
@Test
public void testIsCompatibleDataTypeArrayDifferentElementTypes() {
Object[] array = new Object[]{"2", 1};
assertTrue(DataTypeUtils.isCompatibleDataType(array, RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.INT.getDataType())));
array = new Object[]{Collections.singletonMap("hello", "world"), 1};
assertFalse(DataTypeUtils.isCompatibleDataType(array, RecordFieldType.ARRAY.getArrayDataType(RecordFieldType.INT.getDataType())));
}
@Test
public void testConvertDataTypeBigint() {
final Function<Object, BigInteger> toBigInteger = v -> (BigInteger) DataTypeUtils.convertType(v, RecordFieldType.BIGINT.getDataType(), "field");