Java Code Examples for org.apache.calcite.linq4j.tree.Expressions

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions. These examples are extracted from open source projects. 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 Project: calcite   Source File: PhysTypeTest.java    License: Apache License 2.0 6 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-3364">[CALCITE-3364]
 * Can't group table function result due to a type cast error if table function
 * returns a row with a single value</a>. */
@Test void testOneColumnJavaRowFormatConversion() {
  RelDataType rowType = TYPE_FACTORY.createStructType(
      ImmutableList.of(TYPE_FACTORY.createSqlType(SqlTypeName.INTEGER)),
      ImmutableList.of("intField"));
  final PhysType rowPhysType = PhysTypeImpl.of(TYPE_FACTORY, rowType,
      JavaRowFormat.ARRAY, false);
  final Expression e = rowPhysType.convertTo(
      Expressions.parameter(Enumerable.class, "input"),
      JavaRowFormat.SCALAR);
  final String expected = "input.select(new org.apache.calcite.linq4j.function.Function1() {\n"
      + "  public int apply(Object[] o) {\n"
      + "    return org.apache.calcite.runtime.SqlFunctions.toInt(o[0]);\n"
      + "  }\n"
      + "  public Object apply(Object o) {\n"
      + "    return apply(\n"
      + "      (Object[]) o);\n"
      + "  }\n"
      + "}\n"
      + ")";
  assertEquals(Expressions.toString(e), expected);
}
 
Example 2
Source Project: calcite   Source File: DeterministicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testFactorOutBinaryAddNameCollision() {
  assertThat(
      optimize(
          Expressions.new_(
              Runnable.class,
              Collections.emptyList(),
              Expressions.methodDecl(
                  0,
                  int.class,
                  "test",
                  Collections.emptyList(),
                  Blocks.toFunctionBlock(
                      Expressions.multiply(Expressions.add(ONE, TWO),
                          Expressions.subtract(ONE, TWO)))))),
      equalTo("{\n"
          + "  return new Runnable(){\n"
          + "      int test() {\n"
          + "        return $L4J$C$1_2_1_20;\n"
          + "      }\n"
          + "\n"
          + "      static final int $L4J$C$1_2 = 1 + 2;\n"
          + "      static final int $L4J$C$1_20 = 1 - 2;\n"
          + "      static final int $L4J$C$1_2_1_20 = $L4J$C$1_2 * $L4J$C$1_20;\n"
          + "    };\n"
          + "}\n"));
}
 
Example 3
Source Project: calcite   Source File: RexExecutorImpl.java    License: 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 4
Source Project: calcite   Source File: ExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testWriteTryCatch() {
  final ParameterExpression cce_ =
      Expressions.parameter(Modifier.FINAL, ClassCastException.class, "cce");
  final ParameterExpression re_ =
      Expressions.parameter(0, RuntimeException.class, "re");
  Node node =
      Expressions.tryCatch(
          Expressions.block(
              Expressions.return_(null,
                  Expressions.call(Expressions.constant("foo"), "length"))),
          Expressions.catch_(cce_,
              Expressions.return_(null, Expressions.constant(null))),
          Expressions.catch_(re_,
              Expressions.return_(null,
                  Expressions.call(re_, "toString"))));
  assertEquals(
      "try {\n"
          + "  return \"foo\".length();\n"
          + "} catch (final ClassCastException cce) {\n"
          + "  return null;\n"
          + "} catch (RuntimeException re) {\n"
          + "  return re.toString();\n"
          + "}\n",
      Expressions.toString(node));
}
 
Example 5
Source Project: calcite   Source File: EnumerableRelImplementor.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Stashes a value for the executor. Given values are de-duplicated if
 * identical (see {@link java.util.IdentityHashMap}).
 *
 * <p>For instance, to pass {@code ArrayList} to your method, you can use
 * {@code Expressions.call(method, implementor.stash(arrayList))}.
 *
 * <p>For simple literals (strings, numbers) the result is equivalent to
 * {@link org.apache.calcite.linq4j.tree.Expressions#constant(Object, java.lang.reflect.Type)}.
 *
 * <p>Note: the input value is held in memory as long as the statement
 * is alive. If you are using just a subset of its content, consider creating
 * a slimmer holder.
 *
 * @param input Value to be stashed
 * @param clazz Java class type of the value when it is used
 * @param <T> Java class type of the value when it is used
 * @return Expression that will represent {@code input} in runtime
 */
public <T> Expression stash(T input, Class<? super T> clazz) {
  // Well-known final classes that can be used as literals
  if (input == null
      || input instanceof String
      || input instanceof Boolean
      || input instanceof Byte
      || input instanceof Short
      || input instanceof Integer
      || input instanceof Long
      || input instanceof Float
      || input instanceof Double) {
    return Expressions.constant(input, clazz);
  }
  ParameterExpression cached = stashedParameters.get(input);
  if (cached != null) {
    return cached;
  }
  // "stashed" avoids name clash since this name will be used as the variable
  // name at the very start of the method.
  final String name = "v" + map.size() + "stashed";
  final ParameterExpression x = Expressions.variable(clazz, name);
  map.put(name, input);
  stashedParameters.put(input, x);
  return x;
}
 
Example 6
Source Project: calcite   Source File: ReflectiveCallNotNullImplementor.java    License: Apache License 2.0 6 votes vote down vote up
public Expression implement(RexToLixTranslator translator,
    RexCall call, List<Expression> translatedOperands) {
  translatedOperands =
      EnumUtils.fromInternal(method.getParameterTypes(), translatedOperands);
  translatedOperands =
      EnumUtils.convertAssignableTypes(method.getParameterTypes(), translatedOperands);
  final Expression callExpr;
  if ((method.getModifiers() & Modifier.STATIC) != 0) {
    callExpr = Expressions.call(method, translatedOperands);
  } else {
    // The UDF class must have a public zero-args constructor.
    // Assume that the validator checked already.
    final Expression target =
        Expressions.new_(method.getDeclaringClass());
    callExpr = Expressions.call(target, method, translatedOperands);
  }
  if (!containsCheckedException(method)) {
    return callExpr;
  }
  return translator.handleMethodCheckedExceptions(callExpr);
}
 
Example 7
Source Project: calcite   Source File: ExpressionTest.java    License: 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 8
Source Project: calcite   Source File: Schemas.java    License: Apache License 2.0 6 votes vote down vote up
/** Returns the expression for a sub-schema. */
public static Expression subSchemaExpression(SchemaPlus schema, String name,
    Class type) {
  // (Type) schemaExpression.getSubSchema("name")
  final Expression schemaExpression = expression(schema);
  Expression call =
      Expressions.call(
          schemaExpression,
          BuiltInMethod.SCHEMA_GET_SUB_SCHEMA.method,
          Expressions.constant(name));
  //CHECKSTYLE: IGNORE 2
  //noinspection unchecked
  if (false && type != null && !type.isAssignableFrom(Schema.class)) {
    return unwrap(call, type);
  }
  return call;
}
 
Example 9
Source Project: calcite   Source File: SplunkTableScan.java    License: Apache License 2.0 6 votes vote down vote up
private static Expression constantStringList(final List<String> strings) {
  return Expressions.call(
      Arrays.class,
      "asList",
      Expressions.newArrayInit(
          Object.class,
          new AbstractList<Expression>() {
            @Override public Expression get(int index) {
              return Expressions.constant(strings.get(index));
            }

            @Override public int size() {
              return strings.size();
            }
          }));
}
 
Example 10
Source Project: calcite   Source File: DeterministicTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testDeterministicMethodCall() {
  assertThat(
      optimize(
          Expressions.new_(
              Runnable.class,
              Collections.emptyList(),
              Expressions.methodDecl(
                  0,
                  int.class,
                  "test",
                  Collections.emptyList(),
                  Blocks.toFunctionBlock(
                      Expressions.call(null,
                          Types.lookupMethod(TestClass.class,
                              "deterministic", int.class),
                          ONE))))),
      equalTo("{\n"
          + "  return new Runnable(){\n"
          + "      int test() {\n"
          + "        return $L4J$C$org_apache_calcite_linq4j_test_DeterministicTest_TestClass_dete33e8af1c;\n"
          + "      }\n"
          + "\n"
          + "      static final int $L4J$C$org_apache_calcite_linq4j_test_DeterministicTest_TestClass_dete33e8af1c = org.apache.calcite.linq4j.test.DeterministicTest.TestClass.deterministic(1);\n"
          + "    };\n"
          + "}\n"));
}
 
Example 11
Source Project: calcite   Source File: ExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testTenElementsMapLiteral() throws Exception {
  Map<String, String> map = new LinkedHashMap<>(); // for consistent output
  for (int i = 0; i < 10; i++) {
    map.put("key_" + i, "value_" + i);
  }
  assertEquals("com.google.common.collect.ImmutableMap.builder().put(\"key_0\", \"value_0\")\n"
          + ".put(\"key_1\", \"value_1\")\n"
          + ".put(\"key_2\", \"value_2\")\n"
          + ".put(\"key_3\", \"value_3\")\n"
          + ".put(\"key_4\", \"value_4\")\n"
          + ".put(\"key_5\", \"value_5\")\n"
          + ".put(\"key_6\", \"value_6\")\n"
          + ".put(\"key_7\", \"value_7\")\n"
          + ".put(\"key_8\", \"value_8\")\n"
          + ".put(\"key_9\", \"value_9\").build()",
      Expressions.toString(Expressions.constant(map)));
}
 
Example 12
Source Project: calcite   Source File: ExpressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testTenElementsLinkedHashSetLiteral() throws Exception {
  Set set = new LinkedHashSet(); // for consistent output
  for (Integer i = 0; i < 10; i++) {
    set.add(i);
  }
  assertEquals("com.google.common.collect.ImmutableSet.builder().add(0)\n"
          + ".add(1)\n"
          + ".add(2)\n"
          + ".add(3)\n"
          + ".add(4)\n"
          + ".add(5)\n"
          + ".add(6)\n"
          + ".add(7)\n"
          + ".add(8)\n"
          + ".add(9).build()",
      Expressions.toString(Expressions.constant(set)));
}
 
Example 13
Source Project: calcite   Source File: InlinerTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testAssignInConditionMultipleUsage() {
  // int t;
  // return (t = 1) != a ? t : c
  final BlockBuilder builder = new BlockBuilder(true);
  final ParameterExpression t = Expressions.parameter(int.class, "t");

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

  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;\n"
          + "  return (t = 1) != a ? t : c;\n"
          + "}\n",
      Expressions.toString(builder.toBlock()));
}
 
Example 14
Source Project: marble   Source File: RelDataTypeHolder.java    License: Apache License 2.0 5 votes vote down vote up
public static  Expression generateExpression(RelDataType relDataType) {
  SqlTypeName sqlTypeName = relDataType.getSqlTypeName();
  RelDataType componentType = relDataType.getComponentType();
  if (componentType == null) {
    return Expressions.new_(RelDataTypeHolder.class,
        new ConstantExpression(SqlTypeName.class, sqlTypeName));
  } else {
    Expression componentTypeExpr = generateExpression(componentType);
    return Expressions.new_(RelDataTypeHolder.class,
        new ConstantExpression(SqlTypeName.class, sqlTypeName),
        componentTypeExpr);
  }
}
 
Example 15
Source Project: marble   Source File: RelDataTypeHolder.java    License: Apache License 2.0 5 votes vote down vote up
public static Expression generateExpressionWithConstantValue(RelDataType relDataType,
    Expression valueExpression) {
  return Expressions.new_(RelDataTypeHolder.class,
      new ConstantExpression(SqlTypeName.class,
          relDataType.getSqlTypeName()),
      new ConstantExpression(boolean.class, true),
      valueExpression);
}
 
Example 16
Source Project: calcite   Source File: RexToLixTranslator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * For {@code PREV} operator, the offset of {@code inputGetter}
 * should be set first
 */
private Result implementPrev(RexCall call) {
  final RexNode node = call.getOperands().get(0);
  final RexNode offset = call.getOperands().get(1);
  final Expression offs = Expressions.multiply(translate(offset),
          Expressions.constant(-1));
  ((EnumerableMatch.PrevInputGetter) inputGetter).setOffset(offs);
  return node.accept(this);
}
 
Example 17
Source Project: marble   Source File: HiveRexExecutorImpl.java    License: 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 18
Source Project: calcite   Source File: RexToLixTranslator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Handle checked Exceptions declared in Method. In such case,
 * method call should be wrapped in a try...catch block.
 * "
 *      final Type method_call;
 *      try {
 *        method_call = callExpr
 *      } catch (Exception e) {
 *        throw new RuntimeException(e);
 *      }
 * "
 */
Expression handleMethodCheckedExceptions(Expression callExpr) {
  // Try statement
  ParameterExpression methodCall = Expressions.parameter(
      callExpr.getType(), list.newName("method_call"));
  list.add(Expressions.declare(Modifier.FINAL, methodCall, null));
  Statement st = Expressions.statement(Expressions.assign(methodCall, callExpr));
  // Catch Block, wrap checked exception in unchecked exception
  ParameterExpression e = Expressions.parameter(0, Exception.class, "e");
  Expression uncheckedException = Expressions.new_(RuntimeException.class, e);
  CatchBlock cb = Expressions.catch_(e, Expressions.throw_(uncheckedException));
  list.add(Expressions.tryCatch(st, cb));
  return methodCall;
}
 
Example 19
Source Project: calcite   Source File: RexImpTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void implementReset(AggContext info,
    AggResetContext reset) {
  reset.currentBlock().add(
      Expressions.statement(
          Expressions.assign(reset.accumulator().get(0),
              Expressions.new_(HashMap.class))));
}
 
Example 20
Source Project: marble   Source File: HiveUDFImplementor.java    License: Apache License 2.0 5 votes vote down vote up
private MemberDeclaration generateUdfInstanceDeclaration(String opName,
    SqlSyntax syntax, String fieldName) {
  try {
    if (opName.equals("NOT RLIKE")) {
      //we use a RexImpTable.NotImplementor to wrapper a HiveUDFImplementor ,
      // so `NOT RLIKE` and `RLIKE` would be treated as same here
      opName = "RLIKE";
    }
    if (opName.equals("NOT REGEXP")) {
      opName = "REGEXP";
    }
    Class hiveUDFClazz = HiveSqlOperatorTable.instance()
        .getHiveUDFClass(opName, syntax);
    Expression newUdfExpr;
    if (GenericUDF.class.isAssignableFrom(hiveUDFClazz)) {
      newUdfExpr = Expressions.new_(hiveUDFClazz.getConstructor());
    } else if (UDF.class.isAssignableFrom(hiveUDFClazz)) {
      newUdfExpr = Expressions.new_(GENERIC_UDF_BRIDGE_CONSTRUCTOR
          , new ConstantExpression(String.class, opName)
          , new ConstantExpression(boolean.class, false)
          , new ConstantExpression(String.class, hiveUDFClazz.getName()));
    } else {
      throw new IllegalArgumentException("unknown hive udf class for opName="
          + opName
          + ",and syntax="
          + syntax);
    }
    MemberDeclaration udfMemberDeclaration = Expressions.fieldDecl(
        Modifier.PUBLIC,
        Expressions.parameter(GenericUDF.class, fieldName),
        newUdfExpr);
    return udfMemberDeclaration;
  } catch (NoSuchMethodException e) {
    throw new RuntimeException("fail to new instance for op name " + opName, e);
  }
}
 
Example 21
Source Project: calcite   Source File: InlinerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testInlineConstant() {
  DeclarationStatement decl = Expressions.declare(16, "x", ONE);
  b.add(decl);
  b.add(
      Expressions.return_(null,
          Expressions.add(decl.parameter, decl.parameter)));
  assertEquals("{\n  return 1 + 1;\n}\n", b.toBlock().toString());
}
 
Example 22
Source Project: calcite   Source File: RexImpTable.java    License: Apache License 2.0 5 votes vote down vote up
@Override public void implementAdd(AggContext info, AggAddContext add) {
  final SqlJsonObjectAggAggFunction function =
      (SqlJsonObjectAggAggFunction) info.aggregation();
  add.currentBlock().add(
      Expressions.statement(
          Expressions.call(m,
              Iterables.concat(
                  Collections.singletonList(add.accumulator().get(0)),
                  add.arguments(),
                  Collections.singletonList(
                      Expressions.constant(function.getNullClause()))))));
}
 
Example 23
Source Project: calcite   Source File: OptimizerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testOptimizeTernaryAneqBBA() {
  // a != b ? b : a
  ParameterExpression a = Expressions.parameter(boolean.class, "a");
  ParameterExpression b = Expressions.parameter(boolean.class, "b");
  assertEquals("{\n  return b;\n}\n",
      optimize(Expressions.condition(Expressions.notEqual(a, b), b, a)));
}
 
Example 24
Source Project: calcite   Source File: OptimizerTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testOptimizeTernaryABfalse() {
  // a ? b : false === a && b
  assertEquals("{\n  return a && b;\n}\n",
      optimize(
          Expressions.condition(Expressions.parameter(boolean.class, "a"),
              Expressions.parameter(boolean.class, "b"), FALSE)));
}
 
Example 25
Source Project: calcite   Source File: ExpressionTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testWriteTryCatchFinally() {
  final ParameterExpression cce_ =
      Expressions.parameter(Modifier.FINAL, ClassCastException.class, "cce");
  final ParameterExpression re_ =
      Expressions.parameter(0, RuntimeException.class, "re");
  Node node =
      Expressions.tryCatchFinally(
          Expressions.block(
              Expressions.return_(null,
                  Expressions.call(
                      Expressions.constant("foo"),
                      "length"))),
          Expressions.statement(
              Expressions.call(
                  Expressions.constant("foo"),
                  "toUpperCase")),
          Expressions.catch_(cce_,
              Expressions.return_(null, Expressions.constant(null))),
          Expressions.catch_(re_,
              Expressions.throw_(
                  Expressions.new_(IndexOutOfBoundsException.class))));
  assertEquals(
      "try {\n"
          + "  return \"foo\".length();\n"
          + "} catch (final ClassCastException cce) {\n"
          + "  return null;\n"
          + "} catch (RuntimeException re) {\n"
          + "  throw new IndexOutOfBoundsException();\n"
          + "} finally {\n"
          + "  \"foo\".toUpperCase();\n"
          + "}\n",
      Expressions.toString(node));
}
 
Example 26
Source Project: calcite   Source File: StrictAggImplementor.java    License: 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 27
Source Project: calcite   Source File: OptimizerTest.java    License: 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 28
Source Project: lucene-solr   Source File: SolrToEnumerableConverter.java    License: Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  // Generates a call to "query" with the appropriate fields
  final BlockBuilder list = new BlockBuilder();
  final SolrRel.Implementor solrImplementor = new SolrRel.Implementor();
  solrImplementor.visitChild(0, getInput());
  final RelDataType rowType = getRowType();
  final PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), rowType, pref.prefer(JavaRowFormat.ARRAY));
  final Expression table = list.append("table", solrImplementor.table.getExpression(SolrTable.SolrQueryable.class));
  @SuppressWarnings({"rawtypes"})
  final Expression fields =
      list.append("fields",
          constantArrayList(
              Pair.zip(generateFields(SolrRules.solrFieldNames(rowType), solrImplementor.fieldMappings),
                  new AbstractList<Class>() {
                    @Override
                    @SuppressWarnings({"rawtypes"})
                    public Class get(int index) {
                      return physType.fieldClass(index);
                    }

                    @Override
                    public int size() {
                      return rowType.getFieldCount();
                    }
                  }),
              Pair.class));
  final Expression query = list.append("query", Expressions.constant(solrImplementor.query, String.class));
  final Expression orders = list.append("orders", constantArrayList(solrImplementor.orders, Pair.class));
  final Expression buckets = list.append("buckets", constantArrayList(solrImplementor.buckets, String.class));
  final Expression metricPairs = list.append("metricPairs", constantArrayList(solrImplementor.metricPairs, Pair.class));
  final Expression limit = list.append("limit", Expressions.constant(solrImplementor.limitValue));
  final Expression negativeQuery = list.append("negativeQuery", Expressions.constant(Boolean.toString(solrImplementor.negativeQuery), String.class));
  final Expression havingPredicate = list.append("havingTest", Expressions.constant(solrImplementor.havingPredicate, String.class));
  Expression enumerable = list.append("enumerable", Expressions.call(table, SolrMethod.SOLR_QUERYABLE_QUERY.method,
      fields, query, orders, buckets, metricPairs, limit, negativeQuery, havingPredicate));
  Hook.QUERY_PLAN.run(query);
  list.add(Expressions.return_(null, enumerable));
  return implementor.result(physType, list.toBlock());
}
 
Example 29
Source Project: calcite   Source File: RexImpTable.java    License: Apache License 2.0 5 votes vote down vote up
private Expression call(Expression operand, Type type,
    TimeUnit timeUnit) {
  return Expressions.call(SqlFunctions.class, methodName,
      EnumUtils.convert(operand, type),
      EnumUtils.convert(
          Expressions.constant(timeUnit.multiplier), type));
}
 
Example 30
Source Project: attic-apex-malhar   Source File: ExpressionCompiler.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Create quasi-Java expression from given {@link RexNode}
 *
 * @param node Expression in the form of {@link RexNode}
 * @param inputRowType Input Data type to expression in the form of {@link RelDataType}
 * @param outputRowType Output data type of expression in the form of {@link RelDataType}
 *
 * @return Returns quasi-Java expression
 */
public String getExpression(RexNode node, RelDataType inputRowType, RelDataType outputRowType)
{
  final RexProgramBuilder programBuilder = new RexProgramBuilder(inputRowType, rexBuilder);
  programBuilder.addProject(node, null);
  final RexProgram program = programBuilder.getProgram();

  final BlockBuilder builder = new BlockBuilder();
  final JavaTypeFactory javaTypeFactory = (JavaTypeFactory)rexBuilder.getTypeFactory();

  final RexToLixTranslator.InputGetter inputGetter = new RexToLixTranslator.InputGetterImpl(ImmutableList
      .of(Pair.<Expression, PhysType>of(Expressions.variable(Object[].class, "inputValues"),
      PhysTypeImpl.of(javaTypeFactory, inputRowType, JavaRowFormat.ARRAY, false))));
  final Function1<String, RexToLixTranslator.InputGetter> correlates =
      new Function1<String, RexToLixTranslator.InputGetter>()
    {
      public RexToLixTranslator.InputGetter apply(String a0)
      {
        throw new UnsupportedOperationException();
      }
    };

  final List<Expression> list = RexToLixTranslator.translateProjects(program, javaTypeFactory, builder,
      PhysTypeImpl.of(javaTypeFactory, outputRowType, JavaRowFormat.ARRAY, false), null, inputGetter, correlates);

  for (int i = 0; i < list.size(); i++) {
    Statement statement = Expressions.statement(list.get(i));
    builder.add(statement);
  }

  return finalizeExpression(builder.toBlock(), inputRowType);
}