}
@Override
public Expression visitLeave(ArrayConstructorNode node, List<Expression> children) throws SQLException {
boolean isChildTypeUnknown = false;
Expression arrayElemChild = null;
PDataType arrayElemDataType = children.get(0).getDataType();
for (int i = 0; i < children.size(); i++) {
Expression child = children.get(i);
PDataType childType = child.getDataType();
if (childType == null) {
isChildTypeUnknown = true;
} else if (arrayElemDataType == null) {
arrayElemDataType = childType;
isChildTypeUnknown = true;
arrayElemChild = child;
} else if (arrayElemDataType == childType || childType.isCoercibleTo(arrayElemDataType)) {
continue;
} else if (arrayElemDataType.isCoercibleTo(childType)) {
arrayElemChild = child;
arrayElemDataType = childType;
} else {
throw new SQLExceptionInfo.Builder(SQLExceptionCode.CANNOT_CONVERT_TYPE)
.setMessage(
"Case expressions must have common type: " + arrayElemDataType
+ " cannot be coerced to " + childType).build().buildException();
}
}
// If we found an "unknown" child type and the return type is a number
// make the return type be the most general number type of DECIMAL.
if (isChildTypeUnknown && arrayElemDataType != null && arrayElemDataType.isCoercibleTo(PDataType.DECIMAL)) {
arrayElemDataType = PDataType.DECIMAL;
}
final PDataType theArrayElemDataType = arrayElemDataType;
for (int i = 0; i < node.getChildren().size(); i++) {
ParseNode childNode = node.getChildren().get(i);
if (childNode instanceof BindParseNode) {
context.getBindManager().addParamMetaData((BindParseNode)childNode,
arrayElemDataType == arrayElemChild.getDataType() ? arrayElemChild :
new DelegateDatum(arrayElemChild) {
@Override
public PDataType getDataType() {
return theArrayElemDataType;
}
});
}
}
ImmutableBytesWritable ptr = context.getTempPtr();
Object[] elements = new Object[children.size()];
ArrayConstructorExpression arrayExpression = new ArrayConstructorExpression(children, arrayElemDataType);
if (ExpressionUtil.isConstant(arrayExpression)) {
for (int i = 0; i < children.size(); i++) {
Expression child = children.get(i);
child.evaluate(null, ptr);
Object value = arrayElemDataType.toObject(ptr, child.getDataType(), child.getSortOrder());
elements[i] = LiteralExpression.newConstant(value, child.getDataType(), child.isDeterministic()).getValue();
}
Object value = PArrayDataType.instantiatePhoenixArray(arrayElemDataType, elements);
return LiteralExpression.newConstant(value,
PDataType.fromTypeId(arrayElemDataType.getSqlType() + PDataType.ARRAY_TYPE_BASE), true);
}