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

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions#toString() . 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 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 2
Source File: RexExecutorImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static 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.DEFAULT;
  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 (CalciteSystemProperty.DEBUG.value()) {
    Util.debugCode(System.out, code);
  }
  return code;
}
 
Example 3
Source File: EnumerableInterpretable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public static Bindable toBindable(Map<String, Object> parameters,
    CalcitePrepare.SparkHandler spark, EnumerableRel rel,
    EnumerableRel.Prefer prefer) {
  EnumerableRelImplementor relImplementor =
      new EnumerableRelImplementor(rel.getCluster().getRexBuilder(),
          parameters);

  final ClassDeclaration expr = relImplementor.implementRoot(rel, prefer);
  String s = Expressions.toString(expr.memberDeclarations, "\n", false);

  if (CalciteSystemProperty.DEBUG.value()) {
    Util.debugCode(System.out, s);
  }

  Hook.JAVA_PLAN.run(s);

  try {
    if (spark != null && spark.enabled()) {
      return spark.compile(expr, s);
    } else {
      return getBindable(expr, s, rel.getRowType().getFieldCount());
    }
  } catch (Exception e) {
    throw Helper.INSTANCE.wrap("Error while compiling generated Java code:\n"
        + s, e);
  }
}
 
Example 4
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLambdaPrimitiveTwoArgs() {
  // Parameters for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(int.class, "key");
  ParameterExpression param2Expr =
      Expressions.parameter(int.class, "key2");

  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.block(
          (Type) null,
          Expressions.return_(
              null, paramExpr)),
      Arrays.asList(paramExpr, param2Expr));

  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals("new org.apache.calcite.linq4j.function.Function2() {\n"
          + "  public int apply(int key, int key2) {\n"
          + "    return key;\n"
          + "  }\n"
          + "  public Integer apply(Integer key, Integer key2) {\n"
          + "    return apply(\n"
          + "      key.intValue(),\n"
          + "      key2.intValue());\n"
          + "  }\n"
          + "  public Integer apply(Object key, Object key2) {\n"
          + "    return apply(\n"
          + "      (Integer) key,\n"
          + "      (Integer) key2);\n"
          + "  }\n"
          + "}\n",
      s);
}
 
Example 5
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLambdaCallsBinaryOpMixDoubleType() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Double.TYPE, "arg");

  // This expression represents a lambda expression
  // that adds 10.1d to the parameter value.
  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.add(
          paramExpr,
          Expressions.constant(10.1d)),
      Arrays.asList(paramExpr));
  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public double apply(double arg) {\n"
          + "    return arg + 10.1D;\n"
          + "  }\n"
          + "  public Object apply(Double arg) {\n"
          + "    return apply(\n"
          + "      arg.doubleValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Double) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 5.0f.
  double n = (Double) lambdaExpr.compile().dynamicInvoke(5.0f);

  // This code example produces the following output:
  //
  // arg => (arg +10.1d)
  // 15.1d
  assertEquals(15.1d, n, 0d);
}
 
Example 6
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLambdaCallsBinaryOpMixType() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Long.TYPE, "arg");

  // This expression represents a lambda expression
  // that adds (int)10 to the parameter value.
  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.add(
          paramExpr,
          Expressions.constant(10)),
      Arrays.asList(paramExpr));
  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public long apply(long arg) {\n"
          + "    return arg + 10;\n"
          + "  }\n"
          + "  public Object apply(Long arg) {\n"
          + "    return apply(\n"
          + "      arg.longValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Long) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 5L.
  long n = (Long) lambdaExpr.compile().dynamicInvoke(5L);

  // This code example produces the following output:
  //
  // arg => (arg +10)
  // 15
  assertEquals(15L, n, 0d);
}
 
Example 7
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLambdaCallsBinaryOpFloat() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Float.TYPE, "arg");

  // This expression represents a lambda expression
  // that adds 1f to the parameter value.
  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.add(
          paramExpr,
          Expressions.constant(2.0f)),
      Arrays.asList(paramExpr));
  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public float apply(float arg) {\n"
          + "    return arg + 2.0F;\n"
          + "  }\n"
          + "  public Object apply(Float arg) {\n"
          + "    return apply(\n"
          + "      arg.floatValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Float) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 1f
  float n = (Float) lambdaExpr.compile().dynamicInvoke(1f);

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3.0
  assertEquals(3.0f, n, 0f);
}
 
Example 8
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testLambdaCallsBinaryOpLong() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Long.TYPE, "arg");

  // This expression represents a lambda expression
  // that adds 1L to the parameter value.
  FunctionExpression lambdaExpr = Expressions.lambda(
      Expressions.add(
          paramExpr,
          Expressions.constant(2L)),
      Arrays.asList(paramExpr));
  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public long apply(long arg) {\n"
          + "    return arg + 2L;\n"
          + "  }\n"
          + "  public Object apply(Long arg) {\n"
          + "    return apply(\n"
          + "      arg.longValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Long) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 1L.
  long n = (Long) lambdaExpr.compile().dynamicInvoke(1L);

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3
  assertEquals(3L, n, 0d);
}
 
Example 9
Source File: RexNodeToJavaCodeCompiler.java    From streamline with Apache License 2.0 5 votes vote down vote up
/** Given a method that implements {@link ExecutableExpression#execute(Context, Object[])},
 * adds a bridge method that implements {@link ExecutableExpression#execute(Context)}, and
 * compiles. */
static String baz(ParameterExpression context_,
                  ParameterExpression outputValues_, BlockStatement block, String className) {
  final List<MemberDeclaration> declarations = Lists.newArrayList();

  // public void execute(Context, Object[] outputValues)
  declarations.add(
          Expressions.methodDecl(Modifier.PUBLIC, void.class,
                  StreamlineBuiltInMethod.EXPR_EXECUTE2.method.getName(),
                  ImmutableList.of(context_, outputValues_), block));

  // public Object execute(Context)
  final BlockBuilder builder = new BlockBuilder();
  final Expression values_ = builder.append("values",
          Expressions.newArrayBounds(Object.class, 1,
                  Expressions.constant(1)));
  builder.add(
          Expressions.statement(
                  Expressions.call(
                          Expressions.parameter(ExecutableExpression.class, "this"),
                          StreamlineBuiltInMethod.EXPR_EXECUTE2.method, context_, values_)));
  builder.add(
          Expressions.return_(null,
                  Expressions.arrayIndex(values_, Expressions.constant(0))));
  declarations.add(
          Expressions.methodDecl(Modifier.PUBLIC, Object.class,
                  StreamlineBuiltInMethod.EXPR_EXECUTE1.method.getName(),
                  ImmutableList.of(context_), builder.toBlock()));

  final ClassDeclaration classDeclaration =
          Expressions.classDecl(Modifier.PUBLIC, className, null,
                  ImmutableList.<Type>of(ExecutableExpression.class), declarations);

  return Expressions.toString(Lists.newArrayList(classDeclaration), "\n", false);
}
 
Example 10
Source File: ExpressionCompiler.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
private String finalizeExpression(BlockStatement blockStatement, RelDataType inputRowType)
{
  String s = Expressions.toString(blockStatement.statements.get(0));
  int idx = 0;
  for (RelDataTypeField field : inputRowType.getFieldList()) {
    String fieldName = OperatorUtils.getFieldName(field);
    s = s.replaceAll(String.format("inputValues\\[%d\\]", idx++), "\\{\\$." + Matcher.quoteReplacement(fieldName) + "\\}");
  }

  return s.substring(0, s.length() - 2);
}
 
Example 11
Source File: HiveEnumerableInterpretable.java    From marble with Apache License 2.0 5 votes vote down vote up
public static Bindable toBindable(Map<String, Object> parameters,
    CalcitePrepare.SparkHandler spark, EnumerableRel rel,
    EnumerableRel.Prefer prefer) {
  HiveEnumerableRelImplementor relImplementor =
      new HiveEnumerableRelImplementor(rel.getCluster().getRexBuilder(),
          parameters);

  final ClassDeclaration expr = relImplementor.implementRoot(rel, prefer);
  String s = Expressions.toString(expr.memberDeclarations, "\n", false);

  if (CalcitePrepareImpl.DEBUG) {
    Util.debugCode(System.out, s);
  }

  Hook.JAVA_PLAN.run(s);

  try {
    if (spark != null && spark.enabled()) {
      return spark.compile(expr, s);
    } else {
      return getBindable(expr, s,
          rel.getRowType().getFieldCount());
    }
  } catch (Exception e) {
    throw Helper.INSTANCE.wrap("Error while compiling generated Java code:\n"
        + s, e);
  }
}
 
Example 12
Source File: ExpressionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testLambdaCallsBinaryOpDouble() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Double.TYPE, "arg");

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

  // Print out the expression.
  String s = Expressions.toString(lambdaExpr);
  assertEquals(
      "new org.apache.calcite.linq4j.function.Function1() {\n"
          + "  public double apply(double arg) {\n"
          + "    return arg + 2.0D;\n"
          + "  }\n"
          + "  public Object apply(Double arg) {\n"
          + "    return apply(\n"
          + "      arg.doubleValue());\n"
          + "  }\n"
          + "  public Object apply(Object arg) {\n"
          + "    return apply(\n"
          + "      (Double) arg);\n"
          + "  }\n"
          + "}\n",
      s);

  // Compile and run the lambda expression.
  // The value of the parameter is 1.5.
  double n = (Double) lambdaExpr.compile().dynamicInvoke(1.5d);

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3.5
  assertEquals(3.5D, n, 0d);
}
 
Example 13
Source File: ExpressionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testLambdaCallsBinaryOpByte() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Byte.TYPE, "arg");

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

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

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

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3
  assertEquals(3, n, 0);
}
 
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: ExpressionTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Test void testLambdaCallsBinaryOpInt() {
  // A parameter for the lambda expression.
  ParameterExpression paramExpr =
      Expressions.parameter(Integer.TYPE, "arg");

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

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

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

  // This code example produces the following output:
  //
  // arg => (arg +2)
  // 3
  assertEquals(3, n, 0);
}
 
Example 16
Source File: CodeGenerationBenchmark.java    From calcite with Apache License 2.0 4 votes vote down vote up
@Setup(Level.Trial)
public void setup() {
  planInfos = new PlanInfo[queries];
  VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
  planner.addRule(FilterToCalcRule.INSTANCE);
  planner.addRule(ProjectToCalcRule.INSTANCE);
  planner.addRule(EnumerableRules.ENUMERABLE_CALC_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_JOIN_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_VALUES_RULE);

  RelDataTypeFactory typeFactory =
      new JavaTypeFactoryImpl(org.apache.calcite.rel.type.RelDataTypeSystem.DEFAULT);
  RelOptCluster cluster = RelOptCluster.create(planner, new RexBuilder(typeFactory));
  RelTraitSet desiredTraits =
      cluster.traitSet().replace(EnumerableConvention.INSTANCE);

  RelBuilder relBuilder = RelFactories.LOGICAL_BUILDER.create(cluster, null);
  // Generates queries of the following form depending on the configuration parameters.
  // SELECT `t`.`name`
  // FROM (VALUES  (1, 'Value0')) AS `t` (`id`, `name`)
  // INNER JOIN (VALUES  (1, 'Value1')) AS `t` (`id`, `name`) AS `t0` ON `t`.`id` = `t0`.`id`
  // INNER JOIN (VALUES  (2, 'Value2')) AS `t` (`id`, `name`) AS `t1` ON `t`.`id` = `t1`.`id`
  // INNER JOIN (VALUES  (3, 'Value3')) AS `t` (`id`, `name`) AS `t2` ON `t`.`id` = `t2`.`id`
  // INNER JOIN ...
  // WHERE
  //  `t`.`name` = 'name0' OR
  //  `t`.`name` = 'name1' OR
  //  `t`.`name` = 'name2' OR
  //  ...
  //  OR `t`.`id` = 0
  // The last disjunction (i.e, t.id = $i) is what makes the queries different from one another
  // by assigning a different constant literal.
  for (int i = 0; i < queries; i++) {
    relBuilder.values(new String[]{"id", "name"}, 1, "Value" + 0);
    for (int j = 1; j <= joins; j++) {
      relBuilder
          .values(new String[]{"id", "name"}, j, "Value" + j)
          .join(JoinRelType.INNER, "id");
    }

    List<RexNode> disjunctions = new ArrayList<>();
    for (int j = 0; j < whereClauseDisjunctions; j++) {
      disjunctions.add(
          relBuilder.equals(
              relBuilder.field("name"),
              relBuilder.literal("name" + j)));
    }
    disjunctions.add(
        relBuilder.equals(
            relBuilder.field("id"),
            relBuilder.literal(i)));
    RelNode query =
        relBuilder
            .filter(relBuilder.or(disjunctions))
            .project(relBuilder.field("name"))
            .build();

    RelNode query0 = planner.changeTraits(query, desiredTraits);
    planner.setRoot(query0);

    PlanInfo info = new PlanInfo();
    EnumerableRel plan = (EnumerableRel) planner.findBestExp();

    EnumerableRelImplementor relImplementor =
        new EnumerableRelImplementor(plan.getCluster().getRexBuilder(), new HashMap<>());
    info.classExpr = relImplementor.implementRoot(plan, EnumerableRel.Prefer.ARRAY);
    info.javaCode =
        Expressions.toString(info.classExpr.memberDeclarations, "\n", false);

    ICompilerFactory compilerFactory;
    try {
      compilerFactory = CompilerFactoryFactory.getDefaultCompilerFactory();
    } catch (Exception e) {
      throw new IllegalStateException(
          "Unable to instantiate java compiler", e);
    }
    IClassBodyEvaluator cbe = compilerFactory.newClassBodyEvaluator();
    cbe.setClassName(info.classExpr.name);
    cbe.setExtendedClass(Utilities.class);
    cbe.setImplementedInterfaces(
        plan.getRowType().getFieldCount() == 1
            ? new Class[]{Bindable.class, Typed.class}
            : new Class[]{ArrayBindable.class});
    cbe.setParentClassLoader(EnumerableInterpretable.class.getClassLoader());
    info.cbe = cbe;
    planInfos[i] = info;
  }

}
 
Example 17
Source File: RexToJavaCompiler.java    From samza with Apache License 2.0 4 votes vote down vote up
/**
 * This method takes the java statement block, inputs, outputs needed by the statement block to create an object
 * of class that implements the interface {@link Expression}
 *
 * for e.g.
 *   Query : select id from profile
 *      where profile table has relational schema with id(NUMBER) and name(VARCHAR) columns.
 *    This query will result in the following relational plan
 *      LogicalProject(id=[$1])
 *        LogicalTableScan(table=[[profile]])
 *
 *
 *    And the corresponding expressions are
 *       inputs : EnumerableTableScan (Which is the output of LogicalTableScan)
 *       nodes : [$1] Which essentially means take pick the first column from the input
 *
 *    This expression corresponding to the logicalProject "[$1]" gets converted into a java statement block
 *    {
 *      outputValues[0] = (Integer) inputValues[1];
 *    }
 *
 *    This method converts this statement block into an equivalent {@link Expression} object whose execute methods
 *    execute the above java statement block
 *
 */
static org.apache.samza.sql.data.Expression createSamzaExpressionFromCalcite(ParameterExpression executionContext,
    ParameterExpression context, ParameterExpression dataContext, ParameterExpression inputValues,
    ParameterExpression outputValues, BlockStatement block) {
  final List<MemberDeclaration> declarations = Lists.newArrayList();

  // public void execute(Object[] inputValues, Object[] outputValues)
  declarations.add(
      Expressions.methodDecl(Modifier.PUBLIC, void.class, SamzaBuiltInMethod.EXPR_EXECUTE2.method.getName(),
          ImmutableList.of(executionContext, context, dataContext, inputValues, outputValues), block));

  final ClassDeclaration classDeclaration = Expressions.classDecl(Modifier.PUBLIC, "SqlExpression", null,
      ImmutableList.<Type>of(org.apache.samza.sql.data.Expression.class), declarations);
  String s = Expressions.toString(declarations, "\n", false);

  log.info("Generated code for expression: {}", s);

  try {
    return getExpression(classDeclaration, s);
  } catch (Exception e) {
    throw new SamzaException("Expression compilation failure.", e);
  }
}
 
Example 18
Source File: JaninoRexCompiler.java    From calcite with Apache License 2.0 4 votes vote down vote up
/** Given a method that implements {@link Scalar#execute(Context, Object[])},
 * adds a bridge method that implements {@link Scalar#execute(Context)}, and
 * compiles. */
static Scalar baz(ParameterExpression context_,
    ParameterExpression outputValues_, BlockStatement block) {
  final List<MemberDeclaration> declarations = new ArrayList<>();

  // public void execute(Context, Object[] outputValues)
  declarations.add(
      Expressions.methodDecl(Modifier.PUBLIC, void.class,
          BuiltInMethod.SCALAR_EXECUTE2.method.getName(),
          ImmutableList.of(context_, outputValues_), block));

  // public Object execute(Context)
  final BlockBuilder builder = new BlockBuilder();
  final Expression values_ = builder.append("values",
      Expressions.newArrayBounds(Object.class, 1,
          Expressions.constant(1)));
  builder.add(
      Expressions.statement(
          Expressions.call(
              Expressions.parameter(Scalar.class, "this"),
              BuiltInMethod.SCALAR_EXECUTE2.method, context_, values_)));
  builder.add(
      Expressions.return_(null,
          Expressions.arrayIndex(values_, Expressions.constant(0))));
  declarations.add(
      Expressions.methodDecl(Modifier.PUBLIC, Object.class,
          BuiltInMethod.SCALAR_EXECUTE1.method.getName(),
          ImmutableList.of(context_), builder.toBlock()));

  final ClassDeclaration classDeclaration =
      Expressions.classDecl(Modifier.PUBLIC, "Buzz", null,
          ImmutableList.of(Scalar.class), declarations);
  String s = Expressions.toString(declarations, "\n", false);
  if (CalciteSystemProperty.DEBUG.value()) {
    Util.debugCode(System.out, s);
  }
  try {
    return getScalar(classDeclaration, s);
  } catch (CompileException | IOException e) {
    throw new RuntimeException(e);
  }
}
 
Example 19
Source File: TypeFinderTest.java    From calcite with Apache License 2.0 4 votes vote down vote up
private void assertJavaCodeContains(String expected, List<Node> nodes) {
  final String javaCode = Expressions.toString(nodes, "\n", false);
  assertThat(javaCode, containsString(expected));
}