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 @@ -340,4 +340,16 @@ public static List<Expression> prependFunctionProperties(
operandsWithProperties.addFirst(properties);
return Collections.unmodifiableList(operandsWithProperties);
}

/**
* Converts a UDF argument to {@code int}, failing when it is outside the int range. PPL widens
* integer arithmetic to BIGINT (#5603), so UDF methods take {@code long} and convert with this
* helper. The error matches the one Calcite raises when it casts BIGINT to INTEGER.
*/
public static int toIntArg(long value) {
if (value != (int) value) {
throw new ArithmeticException("Value " + value + " out of range");
}
return (int) value;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

package org.opensearch.sql.expression.function;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.calcite.adapter.enumerable.RexImpTable;
import org.apache.calcite.sql.SqlOperator;

/**
* Determines, from the Java methods Calcite generates calls to, which operand positions of a
* Calcite built-in operator need a Java {@code int}.
*
* <p>PPL widens integer arithmetic to BIGINT (#5603), so an argument such as {@code 1 + 1} reaches
* code generation as a {@code long}. Calcite resolves the runtime method by name and argument types
* and never narrows {@code long} to {@code int}, so the call fails to compile when every overload
* takes an {@code int} at that position (e.g. {@code SqlFunctions.left(String, int)}). Positions
* where some overload accepts a {@code long} (e.g. {@code substring(String, long, long)}) need no
* narrowing.
*
* <p>The runtime methods are read from the implementor that {@link RexImpTable} registers for the
* operator. That implementor is internal to Calcite, so its fields are read reflectively; when they
* cannot be read (or the implementor exposes no method, as for {@code ITEM}) the result is empty
* and callers fall back to the operator's declared signature.
*/
final class CalciteIntParameters {

private record Key(SqlOperator operator, int arity) {}

/** Parameter types to which code generation can pass a {@code long} or {@code Long}. */
private static final Set<Class<?>> ACCEPTS_LONG =
Set.of(long.class, Long.class, float.class, double.class, Object.class, BigDecimal.class);

private static final Map<Key, Optional<boolean[]>> CACHE = new ConcurrentHashMap<>();

private CalciteIntParameters() {}

/**
* Returns, for each operand position of a call to {@code operator} with {@code arity} operands,
* whether a BIGINT operand there must be narrowed to INTEGER: some runtime overload takes an
* {@code int} at that position and none accepts a {@code long}. Returns empty when the runtime
* methods cannot be determined.
*/
static Optional<boolean[]> narrowablePositions(SqlOperator operator, int arity) {
return CACHE.computeIfAbsent(new Key(operator, arity), CalciteIntParameters::compute);
}

private static Optional<boolean[]> compute(Key key) {
List<Method> overloads = new ArrayList<>();
for (Method method : implementationMethods(key.operator())) {
for (Method candidate : method.getDeclaringClass().getMethods()) {
if (candidate.getName().equals(method.getName())
&& candidate.getParameterCount() == key.arity()
&& !candidate.isVarArgs()) {
overloads.add(candidate);
}
}
}
if (overloads.isEmpty()) {
return Optional.empty();
}
boolean[] narrowable = new boolean[key.arity()];
for (int pos = 0; pos < key.arity(); pos++) {
boolean acceptsLong = false;
boolean acceptsInt = false;
for (Method overload : overloads) {
Class<?> parameter = overload.getParameterTypes()[pos];
acceptsLong |= ACCEPTS_LONG.contains(parameter);
acceptsInt |= parameter == int.class || parameter == Integer.class;
}
narrowable[pos] = acceptsInt && !acceptsLong;
}
return Optional.of(narrowable);
}

/** Methods held by the implementor Calcite registers for {@code operator}, if readable. */
private static List<Method> implementationMethods(SqlOperator operator) {
Object implementor;
try {
implementor = RexImpTable.INSTANCE.get(operator);
} catch (RuntimeException e) {
return List.of();
}
List<Method> methods = new ArrayList<>();
if (implementor == null) {
return methods;
}
for (Class<?> type = implementor.getClass();
type != null && type.getName().startsWith("org.apache.calcite.");
type = type.getSuperclass()) {
for (Field field : type.getDeclaredFields()) {
if (Modifier.isStatic(field.getModifiers())) {
continue;
}
Object value;
try {
field.setAccessible(true);
value = field.get(implementor);
} catch (ReflectiveOperationException | RuntimeException e) {
continue;
}
if (value instanceof Method method) {
methods.add(method);
} else if (value instanceof Collection<?> values) {
for (Object element : values) {
if (element instanceof Method method) {
methods.add(method);
}
}
}
}
}
return methods;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -648,7 +648,11 @@ public RexNode resolve(
try {
for (Map.Entry<CalciteFuncSignature, FunctionImp> implement : implementList) {
if (implement.getKey().match(functionName.getName(), argTypes)) {
return implement.getValue().resolve(builder, args);
return narrowIntArgs(
builder,
implement.getKey().typeChecker(),
args,
implement.getValue().resolve(builder, args));
}
}

Expand Down Expand Up @@ -678,6 +682,78 @@ public RexNode resolve(
functionName, allowedSignatures, PlanUtils.getActualSignature(argTypes)));
}

/**
* Narrows BIGINT operands of a resolved Calcite built-in call to INTEGER where its runtime method
* needs a Java {@code int}.
*
* <p>PPL widens integer arithmetic to BIGINT for overflow safety (#5603), so {@code 1 + 1} is
* BIGINT. Type checking still accepts it ({@code SqlTypeFamily.INTEGER} contains BIGINT), but
* some Calcite runtime methods take a Java {@code int} (e.g. {@code SqlFunctions.left(String,
* int)}), and code generation cannot pass a {@code long} there. Values outside the int range fail
* at runtime with an out-of-range error rather than wrapping.
*
* <p>The positions come from the runtime methods themselves (see {@link CalciteIntParameters}),
* so an operand is narrowed only when no overload accepts a {@code long} there; e.g. {@code
* SUBSTRING}, which has {@code long} overloads, is left as is. When the runtime methods cannot be
* read (e.g. {@code ITEM}), the signature alternative that accepted these operands decides
* instead, so {@code ITEM(map, key)} is not narrowed while {@code ITEM(array, index)} is. PPL
* UDFs are skipped: their runtime methods take {@code long} (enforced by {@code
* UDFIntParameterTest}).
*/
private static RexNode narrowIntArgs(
RexBuilder builder, @Nullable PPLTypeChecker typeChecker, RexNode[] args, RexNode node) {
if (!(node instanceof RexCall call) || call.getOperator() instanceof SqlUserDefinedFunction) {
return node;
}
List<RexNode> operands = call.getOperands();
boolean[] narrowable =
CalciteIntParameters.narrowablePositions(call.getOperator(), operands.size())
.orElseGet(() -> signatureIntegerPositions(typeChecker, args, call));
if (narrowable == null) {
return node;
}
List<RexNode> narrowed = null;
for (int pos = 0; pos < operands.size(); pos++) {
RexNode operand = operands.get(pos);
if (!narrowable[pos] || operand.getType().getSqlTypeName() != SqlTypeName.BIGINT) {
continue;
}
if (narrowed == null) {
narrowed = new ArrayList<>(operands);
}
RelDataType intType =
TYPE_FACTORY.createSqlType(SqlTypeName.INTEGER, operand.getType().isNullable());
narrowed.set(pos, builder.makeCast(intType, operand));
}
return narrowed == null ? node : call.clone(call.getType(), narrowed);
}

/**
* Fallback for {@link #narrowIntArgs}: positions that the signature alternative accepting {@code
* args} restricts to the INTEGER family, read from the registered signature or else the
* operator's own checker. Returns {@code null} when the call's operands are not {@code args}
* (positions would not line up) or no signature can be read.
*/
private static @Nullable boolean[] signatureIntegerPositions(
@Nullable PPLTypeChecker typeChecker, RexNode[] args, RexCall call) {
if (!call.getOperands().equals(Arrays.asList(args))) {
return null;
}
List<RelDataType> types = Arrays.stream(args).map(RexNode::getType).toList();
List<SqlTypeFamily> families = typeChecker == null ? null : typeChecker.matchedFamilies(types);
if (families == null) {
families = PPLTypeChecker.matchedFamilies(call.getOperator().getOperandTypeChecker(), types);
}
if (families == null) {
return null;
}
boolean[] positions = new boolean[args.length];
for (int pos = 0; pos < args.length; pos++) {
positions[pos] = families.get(pos) == SqlTypeFamily.INTEGER;
}
return positions;
}

/**
* Widens the operands of a binary comparison against a scalar subquery to a common integer type
* when the two operands are integers of differing width (e.g. INT vs BIGINT, SMALLINT vs INT).
Expand Down Expand Up @@ -769,7 +845,12 @@ private void compulsoryCast(
.typeChecker()
.checkOperandTypes(widenedArgs.stream().map(RexNode::getType).toList());
if (matchSignature) {
return implement.getValue().resolve(builder, widenedArgs.toArray(new RexNode[0]));
RexNode[] coercedArgs = widenedArgs.toArray(new RexNode[0]);
return narrowIntArgs(
builder,
implement.getKey().typeChecker(),
coercedArgs,
implement.getValue().resolve(builder, coercedArgs));
}
}
}
Expand All @@ -784,7 +865,12 @@ private void compulsoryCast(
// will be skipped.
// Maybe can be improved to return the best match? E.g. convert to timestamp when date,
// time, and timestamp are all possible.
return implement.getValue().resolve(builder, castedArgs.toArray(new RexNode[0]));
RexNode[] coercedArgs = castedArgs.toArray(new RexNode[0]);
return narrowIntArgs(
builder,
signature.typeChecker(),
coercedArgs,
implement.getValue().resolve(builder, coercedArgs));
}
}
}
Expand Down
Loading
Loading