org.apache.calcite.linq4j.tree.MethodCallExpression Java Examples

The following examples show how to use org.apache.calcite.linq4j.tree.MethodCallExpression. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: HiveRexExecutorImpl.java    From marble with Apache License 2.0 6 votes vote down vote up
public Expression field(BlockBuilder list, int index, Type storageType) {
  MethodCallExpression recFromCtx = Expressions.call(
      DataContext.ROOT,
      BuiltInMethod.DATA_CONTEXT_GET.method,
      Expressions.constant("inputRecord"));
  Expression recFromCtxCasted =
      RexToLixTranslator.convert(recFromCtx, Object[].class);
  IndexExpression recordAccess = Expressions.arrayIndex(recFromCtxCasted,
      Expressions.constant(index));
  if (storageType == null) {
    final RelDataType fieldType =
        rowType.getFieldList().get(index).getType();
    storageType = ((JavaTypeFactory) typeFactory).getJavaClass(fieldType);
  }
  return RexToLixTranslator.convert(recordAccess, storageType);
}
 
Example #2
Source File: RexExecutorImpl.java    From calcite with Apache License 2.0 6 votes vote down vote up
public Expression field(BlockBuilder list, int index, Type storageType) {
  MethodCallExpression recFromCtx = Expressions.call(
      DataContext.ROOT,
      BuiltInMethod.DATA_CONTEXT_GET.method,
      Expressions.constant("inputRecord"));
  Expression recFromCtxCasted =
      EnumUtils.convert(recFromCtx, Object[].class);
  IndexExpression recordAccess = Expressions.arrayIndex(recFromCtxCasted,
      Expressions.constant(index));
  if (storageType == null) {
    final RelDataType fieldType =
        rowType.getFieldList().get(index).getType();
    storageType = ((JavaTypeFactory) typeFactory).getJavaClass(fieldType);
  }
  return EnumUtils.convert(recordAccess, storageType);
}
 
Example #3
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
private Expression unboxExpression(final Expression argValue) {
  Primitive fromBox = Primitive.ofBox(argValue.getType());
  if (fromBox == null || fromBox == Primitive.VOID) {
    return argValue;
  }
  // Optimization: for "long x";
  // "Long.valueOf(x)" generates "x"
  if (argValue instanceof MethodCallExpression) {
    MethodCallExpression mce = (MethodCallExpression) argValue;
    if (mce.method.getName().equals("valueOf") && mce.expressions.size() == 1) {
      Expression originArg = mce.expressions.get(0);
      if (Primitive.of(originArg.type) == fromBox) {
        return originArg;
      }
    }
  }
  return NullAs.NOT_POSSIBLE.handle(argValue);
}
 
Example #4
Source File: ExpressionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testCompile() throws NoSuchMethodException {
  // Creating a parameter for the expression tree.
  ParameterExpression param = Expressions.parameter(String.class);

  // Creating an expression for the method call and specifying its
  // parameter.
  MethodCallExpression methodCall =
      Expressions.call(
          Integer.class,
          "valueOf",
          Collections.<Expression>singletonList(param));

  // The following statement first creates an expression tree,
  // then compiles it, and then runs it.
  int x =
      Expressions.<Function1<String, Integer>>lambda(
          methodCall,
          new ParameterExpression[] { param })
          .getFunction()
          .apply("1234");
  assertEquals(1234, x);
}
 
Example #5
Source File: HiveUDFImplementor.java    From marble with Apache License 2.0 5 votes vote down vote up
private MemberDeclaration generateUdfOutputOIDeclaration(Expression udfInstanceExpr
    , Expression argsTypeArrayExpr, String fieldName) {
  MethodCallExpression call = Expressions.call(INIT_GENERIC_UDF_METHOD, udfInstanceExpr, argsTypeArrayExpr);
  MemberDeclaration udfMemberDeclaration = Expressions.fieldDecl(
      Modifier.PUBLIC,
      Expressions.parameter(ObjectInspector.class, fieldName),
      call);
  return udfMemberDeclaration;
}
 
Example #6
Source File: EnumUtilsTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testMethodCallExpression() {
  // test for Object.class method parameter type
  final ConstantExpression arg0 = Expressions.constant(1, int.class);
  final ConstantExpression arg1 = Expressions.constant("x", String.class);
  final MethodCallExpression arrayMethodCall = EnumUtils.call(SqlFunctions.class,
      BuiltInMethod.ARRAY.getMethodName(), Arrays.asList(arg0, arg1));
  assertThat(Expressions.toString(arrayMethodCall),
      is("org.apache.calcite.runtime.SqlFunctions.array(1, \"x\")"));

  // test for Object.class argument type
  final ConstantExpression nullLiteral = Expressions.constant(null);
  final MethodCallExpression xmlExtractMethodCall = EnumUtils.call(
      XmlFunctions.class, BuiltInMethod.EXTRACT_VALUE.getMethodName(),
      Arrays.asList(arg1, nullLiteral));
  assertThat(Expressions.toString(xmlExtractMethodCall),
      is("org.apache.calcite.runtime.XmlFunctions.extractValue(\"x\", (String) null)"));

  // test "mod(decimal, long)" match to "mod(decimal, decimal)"
  final ConstantExpression arg2 = Expressions.constant(12.5, BigDecimal.class);
  final ConstantExpression arg3 = Expressions.constant(3, long.class);
  final MethodCallExpression modMethodCall = EnumUtils.call(
      SqlFunctions.class, "mod", Arrays.asList(arg2, arg3));
  assertThat(Expressions.toString(modMethodCall),
      is("org.apache.calcite.runtime.SqlFunctions.mod("
          + "java.math.BigDecimal.valueOf(125L, 1), "
          + "new java.math.BigDecimal(\n  3L))"));

  // test "ST_MakePoint(int, int)" match to "ST_MakePoint(decimal, decimal)"
  final ConstantExpression arg4 = Expressions.constant(1, int.class);
  final ConstantExpression arg5 = Expressions.constant(2, int.class);
  final MethodCallExpression geoMethodCall = EnumUtils.call(
      GeoFunctions.class, "ST_MakePoint", Arrays.asList(arg4, arg5));
  assertThat(Expressions.toString(geoMethodCall),
      is("org.apache.calcite.runtime.GeoFunctions.ST_MakePoint("
          + "new java.math.BigDecimal(\n  1), "
          + "new java.math.BigDecimal(\n  2))"));
}
 
Example #7
Source File: Schemas.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns the expression to access a table within a schema. */
public static Expression tableExpression(SchemaPlus schema, Type elementType,
    String tableName, Class clazz) {
  final MethodCallExpression expression;
  if (Table.class.isAssignableFrom(clazz)) {
    expression = Expressions.call(
        expression(schema),
        BuiltInMethod.SCHEMA_GET_TABLE.method,
        Expressions.constant(tableName));
    if (ScannableTable.class.isAssignableFrom(clazz)) {
      return Expressions.call(
          BuiltInMethod.SCHEMAS_ENUMERABLE_SCANNABLE.method,
          Expressions.convert_(expression, ScannableTable.class),
          DataContext.ROOT);
    }
    if (FilterableTable.class.isAssignableFrom(clazz)) {
      return Expressions.call(
          BuiltInMethod.SCHEMAS_ENUMERABLE_FILTERABLE.method,
          Expressions.convert_(expression, FilterableTable.class),
          DataContext.ROOT);
    }
    if (ProjectableFilterableTable.class.isAssignableFrom(clazz)) {
      return Expressions.call(
          BuiltInMethod.SCHEMAS_ENUMERABLE_PROJECTABLE_FILTERABLE.method,
          Expressions.convert_(expression, ProjectableFilterableTable.class),
          DataContext.ROOT);
    }
  } else {
    expression = Expressions.call(
        BuiltInMethod.SCHEMAS_QUERYABLE.method,
        DataContext.ROOT,
        expression(schema),
        Expressions.constant(elementType),
        Expressions.constant(tableName));
  }
  return EnumUtils.convert(expression, clazz);
}
 
Example #8
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * The powerful version of {@code org.apache.calcite.linq4j.tree.Expressions#call(
 * Type, String, Iterable<? extends Expression>)}. Try best effort to convert the
 * accepted arguments to match parameter type.
 *
 * @param clazz Class against which method is invoked
 * @param methodName Name of method
 * @param arguments argument expressions
 * @param targetExpression target expression
 *
 * @return MethodCallExpression that call the given name method
 * @throws RuntimeException if no suitable method found
 */
public static MethodCallExpression call(Class clazz, String methodName,
     List<? extends Expression> arguments, Expression targetExpression) {
  Class[] argumentTypes = Types.toClassArray(arguments);
  try {
    Method candidate = clazz.getMethod(methodName, argumentTypes);
    return Expressions.call(targetExpression, candidate, arguments);
  } catch (NoSuchMethodException e) {
    for (Method method : clazz.getMethods()) {
      if (method.getName().equals(methodName)) {
        final boolean varArgs = method.isVarArgs();
        final Class[] parameterTypes = method.getParameterTypes();
        if (Types.allAssignable(varArgs, parameterTypes, argumentTypes)) {
          return Expressions.call(targetExpression, method, arguments);
        }
        // fall through
        final List<? extends Expression> typeMatchedArguments =
            matchMethodParameterTypes(varArgs, parameterTypes, arguments);
        if (typeMatchedArguments != null) {
          return Expressions.call(targetExpression, method, typeMatchedArguments);
        }
      }
    }
    throw new RuntimeException("while resolving method '" + methodName
        + Arrays.toString(argumentTypes) + "' in class " + clazz, e);
  }
}
 
Example #9
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected Expression getExpression(RexToLixTranslator translator,
    Expression operand, BuiltInMethod builtInMethod) {
  final MethodCallExpression locale =
      Expressions.call(BuiltInMethod.LOCALE.method, translator.getRoot());
  return Expressions.call(builtInMethod.method.getDeclaringClass(),
      builtInMethod.method.getName(), operand, locale);
}
 
Example #10
Source File: EnumerableTableScan.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Expression fieldExpression(ParameterExpression row_, int i,
    PhysType physType, JavaRowFormat format) {
  final Expression e =
      format.field(row_, i, null, physType.getJavaFieldType(i));
  final RelDataType relFieldType =
      physType.getRowType().getFieldList().get(i).getType();
  switch (relFieldType.getSqlTypeName()) {
  case ARRAY:
  case MULTISET:
    final RelDataType fieldType = relFieldType.getComponentType();
    if (fieldType.isStruct()) {
      // We can't represent a multiset or array as a List<Employee>, because
      // the consumer does not know the element type.
      // The standard element type is List.
      // We need to convert to a List<List>.
      final JavaTypeFactory typeFactory =
              (JavaTypeFactory) getCluster().getTypeFactory();
      final PhysType elementPhysType = PhysTypeImpl.of(
              typeFactory, fieldType, JavaRowFormat.CUSTOM);
      final MethodCallExpression e2 =
              Expressions.call(BuiltInMethod.AS_ENUMERABLE2.method, e);
      final Expression e3 = elementPhysType.convertTo(e2, JavaRowFormat.LIST);
      return Expressions.call(e3, BuiltInMethod.ENUMERABLE_TO_LIST.method);
    } else {
      return e;
    }
  default:
    return e;
  }
}
 
Example #11
Source File: CassandraToEnumerableConverter.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** E.g. {@code constantArrayList("x", "y")} returns
 * "Arrays.asList('x', 'y')". */
private static <T> MethodCallExpression constantArrayList(List<T> values,
    Class clazz) {
  return Expressions.call(
      BuiltInMethod.ARRAYS_AS_LIST.method,
      Expressions.newArrayInit(clazz, constantList(values)));
}
 
Example #12
Source File: OLAPTableScan.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

    context.setReturnTupleInfo(rowType, columnRowType);
    String execFunction = genExecFunc();

    PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), JavaRowFormat.ARRAY);
    MethodCallExpression exprCall = Expressions.call(table.getExpression(OLAPTable.class), execFunction,
            implementor.getRootExpression(), Expressions.constant(context.id));
    return implementor.result(physType, Blocks.toBlock(exprCall));
}
 
Example #13
Source File: OLAPJoinRel.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

    context.setReturnTupleInfo(rowType, columnRowType);

    PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), pref.preferArray());
    RelOptTable factTable = context.firstTableScan.getTable();
    MethodCallExpression exprCall = Expressions.call(factTable.getExpression(OLAPTable.class), "executeOLAPQuery",
            implementor.getRootExpression(), Expressions.constant(context.id));
    return implementor.result(physType, Blocks.toBlock(exprCall));
}
 
Example #14
Source File: OLAPTableScan.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

    context.setReturnTupleInfo(rowType, columnRowType);
    String execFunction = genExecFunc();

    PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), JavaRowFormat.ARRAY);
    MethodCallExpression exprCall = Expressions.call(table.getExpression(OLAPTable.class), execFunction,
            implementor.getRootExpression(), Expressions.constant(context.id));
    return implementor.result(physType, Blocks.toBlock(exprCall));
}
 
Example #15
Source File: OLAPJoinRel.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

    context.setReturnTupleInfo(rowType, columnRowType);

    PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), pref.preferArray());
    RelOptTable factTable = context.firstTableScan.getTable();
    MethodCallExpression exprCall = Expressions.call(factTable.getExpression(OLAPTable.class), "executeOLAPQuery",
            implementor.getRootExpression(), Expressions.constant(context.id));
    return implementor.result(physType, Blocks.toBlock(exprCall));
}
 
Example #16
Source File: LixToRelTranslator.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RelNode translate(Expression expression) {
  if (expression instanceof MethodCallExpression) {
    final MethodCallExpression call = (MethodCallExpression) expression;
    BuiltInMethod method = BuiltInMethod.MAP.get(call.method);
    if (method == null) {
      throw new UnsupportedOperationException(
          "unknown method " + call.method);
    }
    RelNode input;
    switch (method) {
    case SELECT:
      input = translate(call.targetExpression);
      return LogicalProject.create(input,
          ImmutableList.of(),
          toRex(input, (FunctionExpression) call.expressions.get(0)),
          (List<String>) null);

    case WHERE:
      input = translate(call.targetExpression);
      return LogicalFilter.create(input,
          toRex((FunctionExpression) call.expressions.get(0), input));

    case AS_QUERYABLE:
      return LogicalTableScan.create(cluster,
          RelOptTableImpl.create(null,
              typeFactory.createJavaType(
                  Types.toClass(
                      Types.getElementType(call.targetExpression.getType()))),
              ImmutableList.of(),
              call.targetExpression),
          ImmutableList.of());

    case SCHEMA_GET_TABLE:
      return LogicalTableScan.create(cluster,
          RelOptTableImpl.create(null,
              typeFactory.createJavaType((Class)
                  ((ConstantExpression) call.expressions.get(1)).value),
              ImmutableList.of(),
              call.targetExpression),
          ImmutableList.of());

    default:
      throw new UnsupportedOperationException(
          "unknown method " + call.method);
    }
  }
  throw new UnsupportedOperationException(
      "unknown expression type " + expression.getNodeType());
}
 
Example #17
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 4 votes vote down vote up
public RexNode toRex(Expression expression) {
  switch (expression.getNodeType()) {
  case MemberAccess:
    // Case-sensitive name match because name was previously resolved.
    return rexBuilder.makeFieldAccess(
        toRex(
            ((MemberExpression) expression).expression),
        ((MemberExpression) expression).field.getName(),
        true);
  case GreaterThan:
    return binary(expression, SqlStdOperatorTable.GREATER_THAN);
  case LessThan:
    return binary(expression, SqlStdOperatorTable.LESS_THAN);
  case Parameter:
    return parameter((ParameterExpression) expression);
  case Call:
    MethodCallExpression call = (MethodCallExpression) expression;
    SqlOperator operator =
        RexToLixTranslator.JAVA_TO_SQL_METHOD_MAP.get(call.method);
    if (operator != null) {
      return rexBuilder.makeCall(
          type(call),
          operator,
          toRex(
              Expressions.<Expression>list()
                  .appendIfNotNull(call.targetExpression)
                  .appendAll(call.expressions)));
    }
    throw new RuntimeException(
        "Could translate call to method " + call.method);
  case Constant:
    final ConstantExpression constant =
        (ConstantExpression) expression;
    Object value = constant.value;
    if (value instanceof Number) {
      Number number = (Number) value;
      if (value instanceof Double || value instanceof Float) {
        return rexBuilder.makeApproxLiteral(
            BigDecimal.valueOf(number.doubleValue()));
      } else if (value instanceof BigDecimal) {
        return rexBuilder.makeExactLiteral((BigDecimal) value);
      } else {
        return rexBuilder.makeExactLiteral(
            BigDecimal.valueOf(number.longValue()));
      }
    } else if (value instanceof Boolean) {
      return rexBuilder.makeLiteral((Boolean) value);
    } else {
      return rexBuilder.makeLiteral(constant.toString());
    }
  default:
    throw new UnsupportedOperationException(
        "unknown expression type " + expression.getNodeType() + " "
        + expression);
  }
}
 
Example #18
Source File: GeodeToEnumerableConverter.java    From calcite with Apache License 2.0 4 votes vote down vote up
/**
 * E.g. {@code constantArrayList("x", "y")} returns
 * "Arrays.asList('x', 'y')".
 */
private static <T> MethodCallExpression constantArrayList(List<T> values,
    Class clazz) {
  return Expressions.call(BuiltInMethod.ARRAYS_AS_LIST.method,
      Expressions.newArrayInit(clazz, constantList(values)));
}
 
Example #19
Source File: EnumUtils.java    From calcite with Apache License 2.0 4 votes vote down vote up
public static MethodCallExpression call(Class clazz, String methodName,
    List<? extends Expression> arguments) {
  return call(clazz, methodName, arguments, null);
}
 
Example #20
Source File: SolrToEnumerableConverter.java    From lucene-solr with Apache License 2.0 4 votes vote down vote up
/**
 * E.g. {@code constantArrayList("x", "y")} returns
 * "Arrays.asList('x', 'y')".
 */
@SuppressWarnings({"rawtypes"})
private static <T> MethodCallExpression constantArrayList(List<T> values, Class clazz) {
  return Expressions.call(BuiltInMethod.ARRAYS_AS_LIST.method,
      Expressions.newArrayInit(clazz, constantList(values)));
}
 
Example #21
Source File: MongoToEnumerableConverter.java    From calcite with Apache License 2.0 3 votes vote down vote up
/** E.g. {@code constantArrayList("x", "y")} returns
 * "Arrays.asList('x', 'y')".
 *
 * @param values List of values
 * @param clazz Type of values
 * @return expression
 */
private static <T> MethodCallExpression constantArrayList(List<T> values,
    Class clazz) {
  return Expressions.call(
      BuiltInMethod.ARRAYS_AS_LIST.method,
      Expressions.newArrayInit(clazz, constantList(values)));
}
 
Example #22
Source File: ElasticsearchToEnumerableConverter.java    From calcite with Apache License 2.0 2 votes vote down vote up
/** E.g. {@code constantArrayList("x", "y")} returns
 * "Arrays.asList('x', 'y')".
 * @param values list of values
 * @param clazz runtime class representing each element in the list
 * @param <T> type of elements in the list
 * @return method call which creates a list
 */
private static <T> MethodCallExpression constantArrayList(List<T> values, Class clazz) {
  return Expressions.call(BuiltInMethod.ARRAYS_AS_LIST.method,
      Expressions.newArrayInit(clazz, constantList(values)));
}