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

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions#parameter() . 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: OptimizerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testConditionalIfBoolFalseTrue() {
  // if (bool) {1} else if (false) {2} if (true) {4} else {5}
  Expression bool = Expressions.parameter(boolean.class, "bool");
  assertEquals(
      "{\n"
          + "  if (bool) {\n"
          + "    return 1;\n"
          + "  } else {\n"
          + "    return 4;\n"
          + "  }\n"
          + "}\n",
      optimize(
          Expressions.ifThenElse(bool,
              Expressions.return_(null, ONE),
              FALSE,
              Expressions.return_(null, TWO),
              TRUE,
              Expressions.return_(null, FOUR),
              Expressions.return_(null, Expressions.constant(5)))));
}
 
Example 2
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testAssignInConditionMultipleUsageNonOptimized() {
  // int t = 2;
  // return (t = 1) != a ? 1 : c
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression t = Expressions.parameter(int.class, "t");

  builder.add(Expressions.declare(0, t, TWO));

  Expression v = builder.append("v",
      Expressions.makeTernary(ExpressionType.Conditional,
          Expressions.makeBinary(ExpressionType.NotEqual,
              Expressions.assign(t, Expressions.constant(1)),
              Expressions.parameter(int.class, "a")),
          t,
          Expressions.parameter(int.class, "c")));
  builder.add(Expressions.return_(null, v));
  assertEquals(
      "{\n"
          + "  int t = 2;\n"
          + "  return (t = 1) != a ? t : c;\n"
          + "}\n",
      Expressions.toString(builder.toBlock()));
}
 
Example 3
Source File: ExpressionTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testForEach() {
  final BlockBuilder builder = new BlockBuilder();
  final ParameterExpression i_ = Expressions.parameter(int.class, "i");
  final ParameterExpression list_ = Expressions.parameter(List.class, "list");
  builder.add(
      Expressions.forEach(i_, list_,
          Expressions.ifThen(
              Expressions.lessThan(
                  Expressions.constant(1),
                  Expressions.constant(2)),
              Expressions.break_(null))));
  assertThat(Expressions.toString(builder.toBlock()),
      is("{\n"
          + "  for (int i : list) {\n"
          + "    if (1 < 2) {\n"
          + "      break;\n"
          + "    }\n"
          + "  }\n"
          + "}\n"));
}
 
Example 4
Source File: LinqFrontJdbcBackTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTableWhere() throws SQLException,
    ClassNotFoundException {
  final Connection connection =
      CalciteAssert.that(CalciteAssert.Config.JDBC_FOODMART).connect();
  final CalciteConnection calciteConnection =
      connection.unwrap(CalciteConnection.class);
  final SchemaPlus rootSchema = calciteConnection.getRootSchema();
  ParameterExpression c =
      Expressions.parameter(JdbcTest.Customer.class, "c");
  String s =
      Schemas.queryable(Schemas.createDataContext(connection, rootSchema),
          rootSchema.getSubSchema("foodmart"),
          JdbcTest.Customer.class, "customer")
          .where(
              Expressions.lambda(
                  Expressions.lessThan(
                      Expressions.field(c, "customer_id"),
                      Expressions.constant(5)),
                  c))
          .toList()
          .toString();
  Util.discard(s);
}
 
Example 5
Source File: OptimizerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testConditionalIfBoolTrue() {
  // if (bool) {return 1} else if (true) {return 2}
  Expression bool = Expressions.parameter(boolean.class, "bool");
  assertEquals(
      "{\n"
          + "  if (bool) {\n"
          + "    return 1;\n"
          + "  } else {\n"
          + "    return 2;\n"
          + "  }\n"
          + "}\n",
      optimize(
          Expressions.ifThenElse(bool,
              Expressions.return_(null, ONE),
              TRUE,
              Expressions.return_(null, TWO))));
}
 
Example 6
Source File: InlinerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testMultiPassOptimization() {
  // int t = u + v;
  // boolean b = t > 1 ? true : true; -- optimized out, thus t can be inlined
  // return b ? t : 2
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression u = Expressions.parameter(int.class, "u");
  final ParameterExpression v = Expressions.parameter(int.class, "v");

  Expression t = builder.append("t", Expressions.add(u, v));
  Expression b = builder.append("b",
      Expressions.condition(Expressions.greaterThan(t, ONE), TRUE, TRUE));

  builder.add(Expressions.return_(null, Expressions.condition(b, t, TWO)));
  assertEquals(
      "{\n"
          + "  return u + v;\n"
          + "}\n",
      Expressions.toString(builder.toBlock()));
}
 
Example 7
Source File: HiveRexExecutorImpl.java    From marble with Apache License 2.0 5 votes vote down vote up
private String compile(RexBuilder rexBuilder, List<RexNode> constExps,
    RexToLixTranslator.InputGetter getter, RelDataType rowType) {
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(rowType, rexBuilder);
  for (RexNode node : constExps) {
    programBuilder.addProject(
        node, "c" + programBuilder.getProjectList().size());
  }
  final JavaTypeFactoryImpl javaTypeFactory =
      new JavaTypeFactoryImpl(rexBuilder.getTypeFactory().getTypeSystem());
  final BlockBuilder blockBuilder = new BlockBuilder();
  final ParameterExpression root0_ =
      Expressions.parameter(Object.class, "root0");
  final ParameterExpression root_ = DataContext.ROOT;
  blockBuilder.add(
      Expressions.declare(
          Modifier.FINAL, root_,
          Expressions.convert_(root0_, DataContext.class)));
  final SqlConformance conformance = SqlConformanceEnum.HIVE;
  final RexProgram program = programBuilder.getProgram();
  final List<Expression> expressions =
      RexToLixTranslator.translateProjects(program, javaTypeFactory,
          conformance, blockBuilder, null, root_, getter, null);
  blockBuilder.add(
      Expressions.return_(null,
          Expressions.newArrayInit(Object[].class, expressions)));
  final MethodDeclaration methodDecl =
      Expressions.methodDecl(Modifier.PUBLIC, Object[].class,
          BuiltInMethod.FUNCTION1_APPLY.method.getName(),
          ImmutableList.of(root0_), blockBuilder.toBlock());
  String code = Expressions.toString(methodDecl);
  if (CalcitePrepareImpl.DEBUG) {
    Util.debugCode(System.out, code);
  }
  return code;
}
 
Example 8
Source File: EnumerableAggregateBase.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected List<Type> createAggStateTypes(
    final List<Expression> initExpressions,
    final BlockBuilder initBlock,
    final List<AggImpState> aggs,
    JavaTypeFactory typeFactory) {
  final List<Type> aggStateTypes = new ArrayList<>();
  for (final AggImpState agg : aggs) {
    agg.context = new AggContextImpl(agg, typeFactory);
    final List<Type> state = agg.implementor.getStateType(agg.context);

    if (state.isEmpty()) {
      agg.state = ImmutableList.of();
      continue;
    }

    aggStateTypes.addAll(state);

    final List<Expression> decls = new ArrayList<>(state.size());
    for (int i = 0; i < state.size(); i++) {
      String aggName = "a" + agg.aggIdx;
      if (CalciteSystemProperty.DEBUG.value()) {
        aggName = Util.toJavaId(agg.call.getAggregation().getName(), 0)
            .substring("ID$0$".length()) + aggName;
      }
      Type type = state.get(i);
      ParameterExpression pe =
          Expressions.parameter(type,
              initBlock.newName(aggName + "s" + i));
      initBlock.add(Expressions.declare(0, pe, null));
      decls.add(pe);
    }
    agg.state = decls;
    initExpressions.addAll(decls);
    agg.implementor.implementReset(agg.context,
        new AggResultContextImpl(initBlock, agg.call, decls, null, null));
  }
  return aggStateTypes;
}
 
Example 9
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Returns a predicate expression based on a join condition. **/
static Expression generatePredicate(
    EnumerableRelImplementor implementor,
    RexBuilder rexBuilder,
    RelNode left,
    RelNode right,
    PhysType leftPhysType,
    PhysType rightPhysType,
    RexNode condition) {
  final BlockBuilder builder = new BlockBuilder();
  final ParameterExpression left_ =
      Expressions.parameter(leftPhysType.getJavaRowType(), "left");
  final ParameterExpression right_ =
      Expressions.parameter(rightPhysType.getJavaRowType(), "right");
  final RexProgramBuilder program =
      new RexProgramBuilder(
          implementor.getTypeFactory().builder()
              .addAll(left.getRowType().getFieldList())
              .addAll(right.getRowType().getFieldList())
              .build(),
          rexBuilder);
  program.addCondition(condition);
  builder.add(
      Expressions.return_(null,
          RexToLixTranslator.translateCondition(program.getProgram(),
              implementor.getTypeFactory(),
              builder,
              new RexToLixTranslator.InputGetterImpl(
                  ImmutableList.of(Pair.of(left_, leftPhysType),
                      Pair.of(right_, rightPhysType))),
              implementor.allCorrelateVariables,
              implementor.getConformance())));
  return Expressions.lambda(Predicate2.class, builder.toBlock(), left_, right_);
}
 
Example 10
Source File: OptimizerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testAssign2() {
  // long x = 0;
  // final long y = System.currentTimeMillis();
  // if (System.currentTimeMillis() > 0) {
  //   x = y;
  // }
  //
  // Make sure we don't fold two calls to System.currentTimeMillis into one.
  final ParameterExpression x_ = Expressions.parameter(long.class, "x");
  final ParameterExpression y_ = Expressions.parameter(long.class, "y");
  final Method mT = Linq4j.getMethod("java.lang.System", "currentTimeMillis");
  final ConstantExpression zero = Expressions.constant(0L);
  assertThat(
      optimize(
          Expressions.block(
              Expressions.declare(0, x_, zero),
              Expressions.declare(Modifier.FINAL, y_, Expressions.call(mT)),
              Expressions.ifThen(
                  Expressions.greaterThan(Expressions.call(mT), zero),
                  Expressions.statement(Expressions.assign(x_, y_))))),
      equalTo("{\n"
          + "  long x = 0L;\n"
          + "  if (System.currentTimeMillis() > 0L) {\n"
          + "    x = System.currentTimeMillis();\n"
          + "  }\n"
          + "}\n"));
}
 
Example 11
Source File: StrictAggImplementor.java    From calcite with Apache License 2.0 5 votes vote down vote up
public final Expression implementResult(AggContext info,
    final AggResultContext result) {
  if (!needTrackEmptySet) {
    return EnumUtils.convert(
        implementNotNullResult(info, result), info.returnType());
  }
  String tmpName = result.accumulator().isEmpty()
      ? "ar"
      : (result.accumulator().get(0) + "$Res");
  ParameterExpression res = Expressions.parameter(0, info.returnType(),
      result.currentBlock().newName(tmpName));

  List<Expression> acc = result.accumulator();
  final BlockBuilder thenBlock = result.nestBlock();
  Expression nonNull = EnumUtils.convert(
      implementNotNullResult(info, result), info.returnType());
  result.exitBlock();
  thenBlock.add(Expressions.statement(Expressions.assign(res, nonNull)));
  BlockStatement thenBranch = thenBlock.toBlock();
  Expression seenNotNullRows =
      trackNullsPerRow
      ? acc.get(acc.size() - 1)
      : ((WinAggResultContext) result).hasRows();

  if (thenBranch.statements.size() == 1) {
    return Expressions.condition(seenNotNullRows,
        nonNull, RexImpTable.getDefaultValue(res.getType()));
  }
  result.currentBlock().add(Expressions.declare(0, res, null));
  result.currentBlock().add(
      Expressions.ifThenElse(seenNotNullRows,
          thenBranch,
          Expressions.statement(
              Expressions.assign(res,
                  RexImpTable.getDefaultValue(res.getType())))));
  return res;
}
 
Example 12
Source File: OptimizerTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testNotEqualPrimitiveNull() {
  // (int) x == null
  ParameterExpression x = Expressions.parameter(int.class, "x");
  assertEquals("{\n  return true;\n}\n",
      optimize(Expressions.notEqual(x, NULL)));
}
 
Example 13
Source File: OptimizerTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testNotEqualBoolFalse() {
  // x != false
  ParameterExpression x = Expressions.parameter(boolean.class, "x");
  assertEquals("{\n  return x;\n}\n",
      optimize(Expressions.notEqual(x, FALSE)));
}
 
Example 14
Source File: ExpressionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testLambdaCallsBinaryOpShort() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Short.TYPE, "arg");

  // This expression represents a lambda expression
  // that adds 1 to the parameter value.
  Short a = 2;
  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.add(
          paramExpr,
          Expressions.constant(a)),
      Arrays.asList(paramExpr));

  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public int apply(short arg) {\n"
          + "    return arg + (short)2;\n"
          + "  }\n"
          + "  public Object apply(Short arg) {\n"
          + "    return apply(\n"
          + "      arg.shortValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Short) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 1.
  Short b = 1;
  Integer n = (Integer) lambdaExpr.compile().dynamicInvoke(b);

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3
  assertEquals(3, n, 0);
}
 
Example 15
Source File: OptimizerTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testAssign() {
  // long x = 0;
  // final long y = System.currentTimeMillis();
  // if (System.nanoTime() > 0) {
  //   x = y;
  // }
  // System.out.println(x);
  //
  // In bug https://github.com/julianhyde/linq4j/issues/27, this was
  // incorrectly optimized to
  //
  // if (System.nanoTime() > 0L) {
  //    System.currentTimeMillis();
  // }
  // System.out.println(0L);
  final ParameterExpression x_ = Expressions.parameter(long.class, "x");
  final ParameterExpression y_ = Expressions.parameter(long.class, "y");
  final Method mT = Linq4j.getMethod("java.lang.System", "currentTimeMillis");
  final Method mNano = Linq4j.getMethod("java.lang.System", "nanoTime");
  final ConstantExpression zero = Expressions.constant(0L);
  assertThat(
      optimize(
          Expressions.block(
              Expressions.declare(0, x_, zero),
              Expressions.declare(Modifier.FINAL, y_, Expressions.call(mT)),
              Expressions.ifThen(
                  Expressions.greaterThan(Expressions.call(mNano), zero),
                  Expressions.statement(Expressions.assign(x_, y_))),
              Expressions.statement(
                  Expressions.call(
                      Expressions.field(null, System.class, "out"),
                      "println",
                      x_)))),
      equalTo("{\n"
          + "  long x = 0L;\n"
          + "  if (System.nanoTime() > 0L) {\n"
          + "    x = System.currentTimeMillis();\n"
          + "  }\n"
          + "  System.out.println(x);\n"
          + "}\n"));
}
 
Example 16
Source File: RexImpTable.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Expression implementResult(AggContext info,
    AggResultContext result) {
  WinAggResultContext winResult = (WinAggResultContext) result;

  List<RexNode> rexArgs = winResult.rexArguments();

  ParameterExpression res = Expressions.parameter(0, info.returnType(),
      result.currentBlock().newName(isLead ? "lead" : "lag"));

  Expression offset;
  RexToLixTranslator currentRowTranslator =
      winResult.rowTranslator(
          winResult.computeIndex(Expressions.constant(0), SeekType.SET));
  if (rexArgs.size() >= 2) {
    // lead(x, offset) or lead(x, offset, default)
    offset = currentRowTranslator.translate(
        rexArgs.get(1), int.class);
  } else {
    offset = Expressions.constant(1);
  }
  if (!isLead) {
    offset = Expressions.negate(offset);
  }
  Expression dstIndex = winResult.computeIndex(offset, SeekType.SET);

  Expression rowInRange = winResult.rowInPartition(dstIndex);

  BlockBuilder thenBlock = result.nestBlock();
  Expression lagResult = winResult.rowTranslator(dstIndex).translate(
      rexArgs.get(0), res.type);
  thenBlock.add(Expressions.statement(Expressions.assign(res, lagResult)));
  result.exitBlock();
  BlockStatement thenBranch = thenBlock.toBlock();

  Expression defaultValue = rexArgs.size() == 3
      ? currentRowTranslator.translate(rexArgs.get(2), res.type)
      : getDefaultValue(res.type);

  result.currentBlock().add(Expressions.declare(0, res, null));
  result.currentBlock().add(
      Expressions.ifThenElse(rowInRange, thenBranch,
          Expressions.statement(Expressions.assign(res, defaultValue))));
  return res;
}
 
Example 17
Source File: EnumerableMatch.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Generates code for a predicate. */
private Expression implementPredicate(PhysType physType,
    ParameterExpression rows_, BlockStatement body) {
  final List<MemberDeclaration> memberDeclarations = new ArrayList<>();
  ParameterExpression row_ = Expressions.parameter(
      Types.of(MemoryFactory.Memory.class,
          physType.getJavaRowType()), "row_");
  Expressions.assign(row_,
      Expressions.call(rows_, BuiltInMethod.MEMORY_GET0.method));

  // Implement the Predicate here based on the pattern definition

  // Add a predicate method:
  //
  //   public boolean test(E row, List<E> rows) {
  //     return ...;
  //   }
  memberDeclarations.add(
      EnumUtils.overridingMethodDecl(
          BuiltInMethod.PREDICATE_TEST.method,
          ImmutableList.of(row_), body));
  if (EnumerableRules.BRIDGE_METHODS) {
    // Add a bridge method:
    //
    //   public boolean test(Object row, Object rows) {
    //     return this.test(row, (List) rows);
    //   }
    final ParameterExpression row0_ =
        Expressions.parameter(Object.class, "row");
    final ParameterExpression rowsO_ =
        Expressions.parameter(Object.class, "rows");
    BlockBuilder bridgeBody = new BlockBuilder();
    bridgeBody.add(
        Expressions.return_(null,
            Expressions.call(
                Expressions.parameter(Comparable.class, "this"),
                BuiltInMethod.PREDICATE_TEST.method,
                Expressions.convert_(row0_,
                    Types.of(MemoryFactory.Memory.class,
                        physType.getJavaRowType())))));
    memberDeclarations.add(
        EnumUtils.overridingMethodDecl(
            BuiltInMethod.PREDICATE_TEST.method,
            ImmutableList.of(row0_), bridgeBody.toBlock()));
  }
  return Expressions.new_(Types.of(Predicate.class), NO_EXPRS,
      memberDeclarations);
}
 
Example 18
Source File: SparkRules.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Result implementSpark(Implementor implementor) {
  final JavaTypeFactory typeFactory = implementor.getTypeFactory();
  final BlockBuilder builder = new BlockBuilder();
  final SparkRel child = (SparkRel) getInput();

  final Result result = implementor.visitInput(this, 0, child);

  final PhysType physType =
      PhysTypeImpl.of(
          typeFactory, getRowType(), JavaRowFormat.CUSTOM);

  // final RDD<Employee> inputRdd = <<child adapter>>;
  // return inputRdd.flatMap(
  //   new FlatMapFunction<Employee, X>() {
  //          public List<X> call(Employee e) {
  //              if (!(e.empno < 10)) {
  //                  return Collections.emptyList();
  //              }
  //              return Collections.singletonList(
  //                  new X(...)));
  //          }
  //      })


  Type outputJavaType = physType.getJavaRowType();
  final Type rddType =
      Types.of(
          JavaRDD.class, outputJavaType);
  Type inputJavaType = result.physType.getJavaRowType();
  final Expression inputRdd_ =
      builder.append(
          "inputRdd",
          result.block);

  BlockBuilder builder2 = new BlockBuilder();

  final ParameterExpression e_ =
      Expressions.parameter(inputJavaType, "e");
  if (program.getCondition() != null) {
    Expression condition =
        RexToLixTranslator.translateCondition(
            program,
            typeFactory,
            builder2,
            new RexToLixTranslator.InputGetterImpl(
                Collections.singletonList(
                    Pair.of((Expression) e_, result.physType))),
            null, implementor.getConformance());
    builder2.add(
        Expressions.ifThen(
            Expressions.not(condition),
            Expressions.return_(null,
                Expressions.call(
                    BuiltInMethod.COLLECTIONS_EMPTY_LIST.method))));
  }

  final SqlConformance conformance = SqlConformanceEnum.DEFAULT;
  List<Expression> expressions =
      RexToLixTranslator.translateProjects(
          program,
          typeFactory,
          conformance,
          builder2,
          null,
          DataContext.ROOT,
          new RexToLixTranslator.InputGetterImpl(
              Collections.singletonList(
                  Pair.of((Expression) e_, result.physType))),
          null);
  builder2.add(
      Expressions.return_(null,
          Expressions.convert_(
              Expressions.call(
                  BuiltInMethod.COLLECTIONS_SINGLETON_LIST.method,
                  physType.record(expressions)),
              List.class)));

  final BlockStatement callBody = builder2.toBlock();
  builder.add(
      Expressions.return_(
          null,
          Expressions.call(
              inputRdd_,
              SparkMethod.RDD_FLAT_MAP.method,
              Expressions.lambda(
                  SparkRuntime.CalciteFlatMapFunction.class,
                  callBody,
                  e_))));
  return implementor.result(physType, builder.toBlock());
}
 
Example 19
Source File: JaninoRexCompiler.java    From calcite with Apache License 2.0 4 votes vote down vote up
public Scalar compile(List<RexNode> nodes, RelDataType inputRowType) {
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(inputRowType, rexBuilder);
  for (RexNode node : nodes) {
    programBuilder.addProject(node, null);
  }
  final RexProgram program = programBuilder.getProgram();

  final BlockBuilder builder = new BlockBuilder();
  final ParameterExpression context_ =
      Expressions.parameter(Context.class, "context");
  final ParameterExpression outputValues_ =
      Expressions.parameter(Object[].class, "outputValues");
  final JavaTypeFactoryImpl javaTypeFactory =
      new JavaTypeFactoryImpl(rexBuilder.getTypeFactory().getTypeSystem());

  // public void execute(Context, Object[] outputValues)
  final RexToLixTranslator.InputGetter inputGetter =
      new RexToLixTranslator.InputGetterImpl(
          ImmutableList.of(
              Pair.of(
                  Expressions.field(context_,
                      BuiltInMethod.CONTEXT_VALUES.field),
                  PhysTypeImpl.of(javaTypeFactory, inputRowType,
                      JavaRowFormat.ARRAY, false))));
  final Function1<String, RexToLixTranslator.InputGetter> correlates = a0 -> {
    throw new UnsupportedOperationException();
  };
  final Expression root =
      Expressions.field(context_, BuiltInMethod.CONTEXT_ROOT.field);
  final SqlConformance conformance =
      SqlConformanceEnum.DEFAULT; // TODO: get this from implementor
  final List<Expression> list =
      RexToLixTranslator.translateProjects(program, javaTypeFactory,
          conformance, builder, null, root, inputGetter, correlates);
  for (int i = 0; i < list.size(); i++) {
    builder.add(
        Expressions.statement(
            Expressions.assign(
                Expressions.arrayIndex(outputValues_,
                    Expressions.constant(i)),
                list.get(i))));
  }
  return baz(context_, outputValues_, builder.toBlock());
}
 
Example 20
Source File: HiveUDFImplementor.java    From marble with Apache License 2.0 4 votes vote down vote up
@Override public Expression implement(RexToLixTranslator translator,
    RexCall call, List<Expression> translatedOperands) {
  try {
    SqlOperator operator = call.getOperator();
    int hiveUdfId = HiveUDFInstanceCollecterPerSqlQuery.get().getSizeOfStashedHiveUDFInstance();
    String udfInstanceName = "udfInstance_" + hiveUdfId;

    HiveUDFInstanceCollecterPerSqlQuery.get().incrementSizeOfStashedHiveUDFInstance();

    ParameterExpression udfInstanceVariableExpr = Expressions
        .parameter(Types.of(GenericUDF.class, Object.class),
            "hiveUDFInstanceHolder." + udfInstanceName);

    ParameterExpression udfInstanceVariableLocalExpr = Expressions
        .parameter(Types.of(GenericUDF.class, Object.class),
            udfInstanceName);

    HiveUDFInstanceCollecterPerSqlQuery.get()
        .getStashedFieldsForHiveUDFInstanceHolder()
        .add(generateUdfInstanceDeclaration(operator.getName(), operator.getSyntax(), udfInstanceName));

    Expression argTypeArrayExpr = generateArgsTypeExpr(call, translatedOperands);

    Expression argsExpr = new NewArrayExpression(Object.class, 1, null,
        translatedOperands);

    String outputOiName = "udfOutputOi_" + hiveUdfId;

    ParameterExpression udfOutputOiVariableExpr = Expressions
        .parameter(Types.of(GenericUDF.class, Object.class),
            "hiveUDFInstanceHolder." + outputOiName);

    HiveUDFInstanceCollecterPerSqlQuery.get()
        .getStashedFieldsForHiveUDFInstanceHolder()
        .add(generateUdfOutputOIDeclaration(udfInstanceVariableLocalExpr, argTypeArrayExpr, outputOiName));

    Expression callExpr = Expressions.call(CALL_GENERIC_UDF_METHOD,
        Arrays.asList(udfInstanceVariableExpr, argsExpr, argTypeArrayExpr, udfOutputOiVariableExpr));
    String castMethodName =
        TypeConvertUtil.CALCITE_SQL_TYPE_2_CAST_METHOD.get(
            call.type.getSqlTypeName());
    Method castMethod = TypeConvertUtil.class.getMethod(castMethodName,
        Object.class);
    Expression castExpr = Expressions.call(castMethod, callExpr);
    return castExpr;

  } catch (Exception e) {
    throw new RuntimeException(e);
  }
}