Java Code Examples for org.apache.calcite.linq4j.tree.Expressions#call()

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions#call() . 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: 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 2
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 3
Source File: RexImpTable.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public Expression implement(RexToLixTranslator translator,
    Expression inputEnumerable,
    RexCall call, PhysType inputPhysType, PhysType outputPhysType) {
  // The table operand is removed from the RexCall because it
  // represents the input, see StandardConvertletTable#convertWindowFunction.
  Expression intervalExpression = translator.translate(call.getOperands().get(1));
  RexCall descriptor = (RexCall) call.getOperands().get(0);
  List<Expression> translatedOperands = new ArrayList<>();
  final ParameterExpression parameter =
      Expressions.parameter(Primitive.box(inputPhysType.getJavaRowType()),
          "_input");
  Expression wmColExpr =
      inputPhysType.fieldReference(parameter,
          ((RexInputRef) descriptor.getOperands().get(0)).getIndex(),
          outputPhysType.getJavaFieldType(
              inputPhysType.getRowType().getFieldCount()));
  translatedOperands.add(wmColExpr);
  translatedOperands.add(intervalExpression);

  return Expressions.call(BuiltInMethod.TUMBLING.method, inputEnumerable,
      EnumUtils.tumblingWindowSelector(inputPhysType, outputPhysType,
          translatedOperands.get(0), translatedOperands.get(1)));
}
 
Example 4
Source File: HiveUDAFImplementor.java    From marble with Apache License 2.0 6 votes vote down vote up
@Override public Expression implementNotNullResult(AggContext info,
    AggResultContext context) {
  Expression acc0 = context.accumulator().get(0);
  Expression resultExpr = Expressions.call(METHOD_EXECUTE_TERMINATE, acc0);
  Method castMethod;
  try {
    SqlTypeName resultType = info.returnRelType().getSqlTypeName();
    String castMethodName =
        TypeConvertUtil.CALCITE_SQL_TYPE_2_CAST_METHOD
            .get(resultType);
    castMethod = TypeConvertUtil.class.getMethod(castMethodName,
        Object.class);
  } catch (NoSuchMethodException e) {
    throw new RuntimeException(e);
  }
  Expression castExpr = Expressions.call(castMethod, resultExpr);
  return castExpr;
}
 
Example 5
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Expression callBackupMethodAnyType(RexToLixTranslator translator,
    RexCall call, List<Expression> expressions) {
  final String backupMethodNameForAnyType =
      backupMethodName + METHOD_POSTFIX_FOR_ANY_TYPE;

  // one or both of parameter(s) is(are) ANY type
  final Expression expression0 = maybeBox(expressions.get(0));
  final Expression expression1 = maybeBox(expressions.get(1));
  return Expressions.call(SqlFunctions.class, backupMethodNameForAnyType,
      expression0, expression1);
}
 
Example 6
Source File: KylinEnumerableUnion.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
private Expression createUnionExpression(Expression left, Expression right, boolean arrayInput) {
    if (all) {
        return Expressions.call(left, BuiltInMethod.CONCAT.method, right);
    }

    return arrayInput
            ? Expressions.call(left, unionArray, right, Expressions.call(arrayComparer))
            : Expressions.call(left, BuiltInMethod.UNION.method, right);
}
 
Example 7
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 8
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 9
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override Expression implementSafe(final RexToLixTranslator translator,
    final RexCall call, final List<Expression> argValueList) {
  final SqlOperator op = call.getOperator();
  final Expression root = translator.getRoot();
  if (op == CURRENT_USER
      || op == SESSION_USER
      || op == USER) {
    return Expressions.call(BuiltInMethod.USER.method, root);
  } else if (op == SYSTEM_USER) {
    return Expressions.call(BuiltInMethod.SYSTEM_USER.method, root);
  } else if (op == CURRENT_PATH
      || op == CURRENT_ROLE
      || op == CURRENT_CATALOG) {
    // By default, the CURRENT_ROLE and CURRENT_CATALOG functions return the
    // empty string because a role or a catalog has to be set explicitly.
    return Expressions.constant("");
  } else if (op == CURRENT_TIMESTAMP) {
    return Expressions.call(BuiltInMethod.CURRENT_TIMESTAMP.method, root);
  } else if (op == CURRENT_TIME) {
    return Expressions.call(BuiltInMethod.CURRENT_TIME.method, root);
  } else if (op == CURRENT_DATE) {
    return Expressions.call(BuiltInMethod.CURRENT_DATE.method, root);
  } else if (op == LOCALTIMESTAMP) {
    return Expressions.call(BuiltInMethod.LOCAL_TIMESTAMP.method, root);
  } else if (op == LOCALTIME) {
    return Expressions.call(BuiltInMethod.LOCAL_TIME.method, root);
  } else {
    throw new AssertionError("unknown function " + op);
  }
}
 
Example 10
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Expression fromInternal(Expression operand,
    Type fromType, Type targetType) {
  if (operand == ConstantUntypedNull.INSTANCE) {
    return operand;
  }
  if (!(operand.getType() instanceof Class)) {
    return operand;
  }
  if (Types.isAssignableFrom(targetType, fromType)) {
    return operand;
  }
  if (targetType == java.sql.Date.class) {
    // E.g. from "int" or "Integer" to "java.sql.Date",
    // generate "SqlFunctions.internalToDate".
    if (isA(fromType, Primitive.INT)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_DATE.method, operand);
    }
  } else if (targetType == java.sql.Time.class) {
    // E.g. from "int" or "Integer" to "java.sql.Time",
    // generate "SqlFunctions.internalToTime".
    if (isA(fromType, Primitive.INT)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_TIME.method, operand);
    }
  } else if (targetType == java.sql.Timestamp.class) {
    // E.g. from "long" or "Long" to "java.sql.Timestamp",
    // generate "SqlFunctions.internalToTimestamp".
    if (isA(fromType, Primitive.LONG)) {
      return Expressions.call(BuiltInMethod.INTERNAL_TO_TIMESTAMP.method, operand);
    }
  }
  if (Primitive.is(operand.type)
      && Primitive.isBox(targetType)) {
    // E.g. operand is "int", target is "Long", generate "(long) operand".
    return Expressions.convert_(operand,
        Primitive.ofBox(targetType).primitiveClass);
  }
  return operand;
}
 
Example 11
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 12
Source File: KylinEnumerableUnion.java    From kylin with Apache License 2.0 5 votes vote down vote up
private Expression createUnionExpression(Expression left, Expression right, boolean arrayInput) {
    if (all) {
        return Expressions.call(left, BuiltInMethod.CONCAT.method, right);
    }

    return arrayInput
            ? Expressions.call(left, unionArray, right, Expressions.call(arrayComparer))
            : Expressions.call(left, BuiltInMethod.UNION.method, right);
}
 
Example 13
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 14
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Override public void implementNotNullAdd(AggContext info,
    AggAddContext add) {
  Expression acc = add.accumulator().get(0);
  Expression arg = add.arguments().get(0);
  SqlAggFunction aggregation = info.aggregation();

  final BuiltInMethod builtInMethod;
  switch (aggregation.kind) {
  case BIT_AND:
    builtInMethod = BuiltInMethod.BIT_AND;
    break;
  case BIT_OR:
    builtInMethod = BuiltInMethod.BIT_OR;
    break;
  case BIT_XOR:
    builtInMethod = BuiltInMethod.BIT_XOR;
    break;
  default:
    throw new IllegalArgumentException("Unknown " + aggregation.getName()
        + ". Only support bit_and, bit_or and bit_xor for bit aggregation function");
  }
  final Method method = builtInMethod.method;
  Expression next = Expressions.call(
      method.getDeclaringClass(),
      method.getName(),
      acc,
      Expressions.unbox(arg));
  accAdvance(add, acc, next);
}
 
Example 15
Source File: SnapshotFunctions.java    From mat-calcite-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public Expression implement(RexToLixTranslator rexToLixTranslator, RexCall rexCall, List<Expression> operands) {
    int snapshotId = SnapshotHolder.put(snapshot);

    return Expressions.call(
            Expressions.new_(getConstructor(SnapshotFunctions.class, Integer.TYPE), Expressions.constant(snapshotId, Integer.TYPE)),
            functionMethod, operands);
}
 
Example 16
Source File: EnumerableUncollect.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final BlockBuilder builder = new BlockBuilder();
  final EnumerableRel child = (EnumerableRel) getInput();
  final Result result = implementor.visitChild(this, 0, child, pref);
  final PhysType physType =
      PhysTypeImpl.of(
          implementor.getTypeFactory(),
          getRowType(),
          JavaRowFormat.LIST);

  // final Enumerable<List<Employee>> child = <<child adapter>>;
  // return child.selectMany(FLAT_PRODUCT);
  final Expression child_ =
      builder.append(
          "child", result.block);

  final List<Integer> fieldCounts = new ArrayList<>();
  final List<FlatProductInputType> inputTypes = new ArrayList<>();

  Expression lambdaForStructWithSingleItem = null;
  for (RelDataTypeField field : child.getRowType().getFieldList()) {
    final RelDataType type = field.getType();
    if (type instanceof MapSqlType) {
      fieldCounts.add(2);
      inputTypes.add(FlatProductInputType.MAP);
    } else {
      final RelDataType elementType = type.getComponentType();
      if (elementType.isStruct()) {
        if (elementType.getFieldCount() == 1 && child.getRowType().getFieldList().size() == 1
            && !withOrdinality) {
          // Solves CALCITE-4063: if we are processing a single field, which is a struct with a
          // single item inside, and no ordinality; the result must be a scalar, hence use a
          // special lambda that does not return lists, but the (single) items within those lists
          lambdaForStructWithSingleItem = Expressions.call(BuiltInMethod.FLAT_LIST.method);
        } else {
          fieldCounts.add(elementType.getFieldCount());
          inputTypes.add(FlatProductInputType.LIST);
        }
      } else {
        fieldCounts.add(-1);
        inputTypes.add(FlatProductInputType.SCALAR);
      }
    }
  }

  final Expression lambda = lambdaForStructWithSingleItem != null
      ? lambdaForStructWithSingleItem
      : Expressions.call(BuiltInMethod.FLAT_PRODUCT.method,
          Expressions.constant(Ints.toArray(fieldCounts)),
          Expressions.constant(withOrdinality),
          Expressions.constant(
              inputTypes.toArray(new FlatProductInputType[0])));
  builder.add(
      Expressions.return_(null,
          Expressions.call(child_,
              BuiltInMethod.SELECT_MANY.method,
              lambda)));
  return implementor.result(physType, builder.toBlock());
}
 
Example 17
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override public Expression implementResult(AggContext info,
    AggResultContext result) {
  return Expressions.call(BuiltInMethod.JSONIZE.method,
      result.accumulator().get(0));
}
 
Example 18
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override Expression implementSafe(
    final RexToLixTranslator translator,
    final RexCall call,
    final List<Expression> argValueList) {
  // neither nullable:
  //   return x OP y
  // x nullable
  //   null_returns_null
  //     return x == null ? null : x OP y
  //   ignore_null
  //     return x == null ? null : y
  // x, y both nullable
  //   null_returns_null
  //     return x == null || y == null ? null : x OP y
  //   ignore_null
  //     return x == null ? y : y == null ? x : x OP y
  if (backupMethodName != null) {
    // If one or both operands have ANY type, use the late-binding backup
    // method.
    if (anyAnyOperands(call)) {
      return callBackupMethodAnyType(translator, call, argValueList);
    }

    final Type type0 = argValueList.get(0).getType();
    final Type type1 = argValueList.get(1).getType();
    final SqlBinaryOperator op = (SqlBinaryOperator) call.getOperator();
    final RelDataType relDataType0 = call.getOperands().get(0).getType();
    final Expression fieldComparator = generateCollatorExpression(relDataType0.getCollation());
    if (fieldComparator != null) {
      argValueList.add(fieldComparator);
    }
    final Primitive primitive = Primitive.ofBoxOr(type0);
    if (primitive == null
        || type1 == BigDecimal.class
        || COMPARISON_OPERATORS.contains(op)
        && !COMP_OP_TYPES.contains(primitive)) {
      return Expressions.call(SqlFunctions.class, backupMethodName,
          argValueList);
    }
    // When checking equals or not equals on two primitive boxing classes
    // (i.e. Long x, Long y), we should fall back to call `SqlFunctions.eq(x, y)`
    // or `SqlFunctions.ne(x, y)`, rather than `x == y`
    final Primitive boxPrimitive0 = Primitive.ofBox(type0);
    final Primitive boxPrimitive1 = Primitive.ofBox(type1);
    if (EQUALS_OPERATORS.contains(op)
        && boxPrimitive0 != null && boxPrimitive1 != null) {
      return Expressions.call(SqlFunctions.class, backupMethodName,
          argValueList);
    }
  }
  return Expressions.makeBinary(expressionType,
      argValueList.get(0), argValueList.get(1));
}
 
Example 19
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Override Expression implementSafe(final RexToLixTranslator translator,
    final RexCall call, final List<Expression> argValueList) {
  switch (call.getOperands().size()) {
  case 1:
    switch (call.getType().getSqlTypeName()) {
    case BIGINT:
    case INTEGER:
    case SMALLINT:
    case TINYINT:
      return argValueList.get(0);
    default:
      return super.implementSafe(translator, call, argValueList);
    }

  case 2:
    final Type type;
    final Method floorMethod;
    final boolean preFloor;
    Expression operand = argValueList.get(0);
    switch (call.getType().getSqlTypeName()) {
    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
      operand = Expressions.call(
          BuiltInMethod.TIMESTAMP_WITH_LOCAL_TIME_ZONE_TO_TIMESTAMP.method,
          operand,
          Expressions.call(BuiltInMethod.TIME_ZONE.method, translator.getRoot()));
      // fall through
    case TIMESTAMP:
      type = long.class;
      floorMethod = timestampMethod;
      preFloor = true;
      break;
    default:
      type = int.class;
      floorMethod = dateMethod;
      preFloor = false;
    }
    final TimeUnitRange timeUnitRange =
        (TimeUnitRange) translator.getLiteralValue(argValueList.get(1));
    switch (timeUnitRange) {
    case YEAR:
    case QUARTER:
    case MONTH:
    case WEEK:
    case DAY:
      final Expression operand1 =
          preFloor ? call(operand, type, TimeUnit.DAY) : operand;
      return Expressions.call(floorMethod,
          translator.getLiteral(argValueList.get(1)), operand1);
    case NANOSECOND:
    default:
      return call(operand, type, timeUnitRange.startUnit);
    }

  default:
    throw new AssertionError();
  }
}
 
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)));
}