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

The following examples show how to use org.apache.calcite.linq4j.tree.Expressions. 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: InlinerTest.java    From calcite with 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 #2
Source File: Schemas.java    From calcite with 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 #3
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 #4
Source File: SplunkTableScan.java    From calcite with 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 #5
Source File: ExpressionTest.java    From calcite with 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 #6
Source File: DeterministicTest.java    From calcite with 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 #7
Source File: DeterministicTest.java    From calcite with 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 #8
Source File: EnumerableRelImplementor.java    From calcite with 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 #9
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 #10
Source File: PhysTypeTest.java    From calcite with 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 #11
Source File: ExpressionTest.java    From calcite with 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 #12
Source File: ReflectiveCallNotNullImplementor.java    From calcite with 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 #13
Source File: ExpressionTest.java    From calcite with 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 #14
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testBigDecimalConstantExpression() {
  assertEquals("java.math.BigDecimal.valueOf(104L)",
      Expressions.toString(Expressions.constant("104", BigDecimal.class)));
  assertEquals("java.math.BigDecimal.valueOf(1L, -3)",
      Expressions.toString(Expressions.constant("1000", BigDecimal.class)));
  assertEquals("java.math.BigDecimal.valueOf(1L, -3)",
      Expressions.toString(Expressions.constant(1000, BigDecimal.class)));
  assertEquals("java.math.BigDecimal.valueOf(107L)",
      Expressions.toString(Expressions.constant(107, BigDecimal.class)));
  assertEquals("java.math.BigDecimal.valueOf(199999999999999L)",
      Expressions.toString(Expressions.constant(199999999999999L, BigDecimal.class)));
  assertEquals("java.math.BigDecimal.valueOf(1234L, 2)",
      Expressions.toString(Expressions.constant(12.34, BigDecimal.class)));
}
 
Example #15
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Expression implementResult(AggContext info,
    AggResultContext result) {
  WinAggResultContext winResult = (WinAggResultContext) result;

  return Expressions.condition(winResult.hasRows(),
      winResult.rowTranslator(
          winResult.computeIndex(Expressions.constant(0), seekType))
          .translate(winResult.rexArguments().get(0), info.returnType()),
      getDefaultValue(info.returnType()));
}
 
Example #16
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private Expression maybeBox(Expression expression) {
  final Primitive primitive = Primitive.of(expression.getType());
  if (primitive != null) {
    expression = Expressions.box(expression, primitive);
  }
  return expression;
}
 
Example #17
Source File: ExpressionTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testWriteArray() {
  assertEquals(
      "1 + integers[2 + index]",
      Expressions.toString(
          Expressions.add(
              Expressions.constant(1),
              Expressions.arrayIndex(
                  Expressions.variable(int[].class, "integers"),
                  Expressions.add(
                      Expressions.constant(2),
                      Expressions.variable(int.class, "index"))))));
}
 
Example #18
Source File: InlinerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testInlineSingleUsage() {
  DeclarationStatement decl = Expressions.declare(16, "x",
      Expressions.add(ONE, TWO));
  b.add(decl);
  b.add(Expressions.return_(null, decl.parameter));
  assertEquals("{\n  return 1 + 2;\n}\n", b.toBlock().toString());
}
 
Example #19
Source File: EnumUtils.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Declares a method that overrides another method. */
public static MethodDeclaration overridingMethodDecl(Method method,
    Iterable<ParameterExpression> parameters,
    BlockStatement body) {
  return Expressions.methodDecl(
      method.getModifiers() & ~Modifier.ABSTRACT,
      method.getReturnType(),
      method.getName(),
      parameters,
      body);
}
 
Example #20
Source File: OLAPTableScan.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {

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

    PhysType physType = PhysTypeImpl.of(implementor.getTypeFactory(), getRowType(), JavaRowFormat.ARRAY);
    MethodCallExpression exprCall = Expressions.call(table.getExpression(OLAPTable.class), execFunction,
            implementor.getRootExpression(), Expressions.constant(context.id));
    return implementor.result(physType, Blocks.toBlock(exprCall));
}
 
Example #21
Source File: OptimizerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testOptimizeTernaryInEqualABCeqC() {
  // (v ? inp0_ : (Integer) null) == null
  assertEquals("{\n  return !v || inp0_ == null;\n}\n",
      optimize(
          Expressions.equal(
              Expressions.condition(Expressions.parameter(boolean.class, "v"),
                  Expressions.parameter(Integer.class, "inp0_"),
                  NULL_INTEGER),
          NULL)));
}
 
Example #22
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 #23
Source File: EnumerableSort.java    From calcite with Apache License 2.0 5 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(),
          result.format);
  Expression childExp =
      builder.append("child", result.block);

  PhysType inputPhysType = result.physType;
  final Pair<Expression, Expression> pair =
      inputPhysType.generateCollationKey(
          collation.getFieldCollations());

  builder.add(
      Expressions.return_(null,
          Expressions.call(childExp,
              BuiltInMethod.ORDER_BY.method,
              Expressions.list(
                  builder.append("keySelector", pair.left))
                  .appendIfNotNull(
                      builder.appendIfNotNull("comparator", pair.right)))));
  return implementor.result(physType, builder.toBlock());
}
 
Example #24
Source File: RexImpTable.java    From calcite with Apache License 2.0 5 votes vote down vote up
private ParameterExpression genIsNullStatement(
    final RexToLixTranslator translator, final ParameterExpression value) {
  final ParameterExpression isNullVariable =
      Expressions.parameter(Boolean.TYPE,
          translator.getBlockBuilder().newName(getVariableName() + "_isNull"));
  final Expression isNullExpression = translator.checkNull(value);
  translator.getBlockBuilder().add(
      Expressions.declare(Modifier.FINAL, isNullVariable, isNullExpression));
  return isNullVariable;
}
 
Example #25
Source File: RelToSqlConverter.java    From quark with Apache License 2.0 5 votes vote down vote up
private Result(SqlNode node, Collection<Clause> clauses, String neededAlias,
               List<Pair<String, RelDataType>> aliases) {
  this.node = node;
  this.neededAlias = neededAlias;
  this.aliases = aliases;
  this.clauses = Expressions.list(clauses);
}
 
Example #26
Source File: RelToSqlConverter.java    From quark with Apache License 2.0 5 votes vote down vote up
/**
 * Converts a call to an aggregate function to an expression.
 */
public SqlNode toSql(AggregateCall aggCall) {
  SqlOperator op = (SqlAggFunction) aggCall.getAggregation();
  if (op instanceof SqlSumEmptyIsZeroAggFunction) {
    op = SqlStdOperatorTable.SUM;
  }
  final List<SqlNode> operands = Expressions.list();
  for (int arg : aggCall.getArgList()) {
    operands.add(field(arg));
  }
  return op.createCall(
      aggCall.isDistinct() ? SqlSelectKeyword.DISTINCT.symbol(POS) : null,
      POS, operands.toArray(new SqlNode[operands.size()]));
}
 
Example #27
Source File: QuarkTileScan.java    From quark with Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  PhysType physType =
      PhysTypeImpl.of(
          implementor.getTypeFactory(),
          getRowType(),
          pref.preferArray());

  return implementor.result(
      physType,
      Blocks.toBlock(
          Expressions.call(table.getExpression(QuarkTileTable.class),
              "project", Expressions.constant(
                  QuarkEnumerator.identityList(getRowType().getFieldCount())))));
}
 
Example #28
Source File: EnumerableLimit.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static Expression getExpression(RexNode offset) {
  if (offset instanceof RexDynamicParam) {
    final RexDynamicParam param = (RexDynamicParam) offset;
    return Expressions.convert_(
        Expressions.call(DataContext.ROOT,
            BuiltInMethod.DATA_CONTEXT_GET.method,
            Expressions.constant("?" + param.getIndex())),
        Integer.class);
  } else {
    return Expressions.constant(RexLiteral.intValue(offset));
  }
}
 
Example #29
Source File: EnumerableNestedLoopJoin.java    From calcite with Apache License 2.0 5 votes vote down vote up
public Result implement(EnumerableRelImplementor implementor, Prefer pref) {
  final BlockBuilder builder = new BlockBuilder();
  final Result leftResult =
      implementor.visitChild(this, 0, (EnumerableRel) left, pref);
  Expression leftExpression =
      builder.append("left", leftResult.block);
  final Result rightResult =
      implementor.visitChild(this, 1, (EnumerableRel) right, pref);
  Expression rightExpression =
      builder.append("right", rightResult.block);
  final PhysType physType =
      PhysTypeImpl.of(implementor.getTypeFactory(),
          getRowType(),
          pref.preferArray());
  final Expression predicate =
      EnumUtils.generatePredicate(implementor, getCluster().getRexBuilder(), left, right,
          leftResult.physType, rightResult.physType, condition);
  return implementor.result(
      physType,
      builder.append(
          Expressions.call(BuiltInMethod.NESTED_LOOP_JOIN.method,
              leftExpression,
              rightExpression,
              predicate,
              EnumUtils.joinSelector(joinType,
                  physType,
                  ImmutableList.of(leftResult.physType,
                      rightResult.physType)),
              Expressions.constant(EnumUtils.toLinq4jJoinType(joinType))))
          .toBlock());
}
 
Example #30
Source File: DataSourceSchema.java    From quark with Apache License 2.0 5 votes vote down vote up
@Override
public Expression getExpression(SchemaPlus parentSchema,
                                String name) {
  return Expressions.call(
      DataContext.ROOT,
      BuiltInMethod.DATA_CONTEXT_GET_ROOT_SCHEMA.method);
}