org.apache.calcite.tools.RelBuilder Java Examples

The following examples show how to use org.apache.calcite.tools.RelBuilder. 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: SubQueryRemoveRule.java    From calcite with Apache License 2.0 6 votes vote down vote up
protected RexNode apply(RexSubQuery e, Set<CorrelationId> variablesSet,
    RelOptUtil.Logic logic,
    RelBuilder builder, int inputCount, int offset) {
  switch (e.getKind()) {
  case SCALAR_QUERY:
    return rewriteScalarQuery(e, variablesSet, builder, inputCount, offset);
  case SOME:
    return rewriteSome(e, variablesSet, builder);
  case IN:
    return rewriteIn(e, variablesSet, logic, builder, offset);
  case EXISTS:
    return rewriteExists(e, variablesSet, logic, builder);
  default:
    throw new AssertionError(e.getKind());
  }
}
 
Example #2
Source File: QueryOperationConverter.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public RelBuilder.AggCall visit(CallExpression call) {
	FunctionDefinition def = call.getFunctionDefinition();
	if (BuiltInFunctionDefinitions.DISTINCT == def) {
		Expression innerAgg = call.getChildren().get(0);
		return innerAgg.accept(new AggCallVisitor(relBuilder, expressionConverter, name, true));
	} else {
		SqlAggFunction sqlAggFunction = call.accept(sqlAggFunctionVisitor);
		return relBuilder.aggregateCall(
			sqlAggFunction,
			isDistinct,
			false,
			null,
			name,
			call.getChildren().stream().map(expr -> expr.accept(expressionConverter))
				.collect(Collectors.toList()));
	}
}
 
Example #3
Source File: PushDownLogicTableRule.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
private RelNode shardingTable(RelBuilder builder, Bindables.BindableTableScan bindableTableScan, RelOptCluster cluster, RelOptSchema relOptSchema, MycatLogicTable logicTable) {
    RelNode value;
    ArrayList<RexNode> filters = new ArrayList<>(bindableTableScan.filters == null ? Collections.emptyList() : bindableTableScan.filters);
    List<DataNode> backendTableInfos = CalciteUtls.getBackendTableInfos((ShardingTableHandler) logicTable.logicTable(), filters);

    ////////////////////////////////////////////////////////////////////////////////////////////////
    //视图优化


    ////////////////////////////////////////////////////////////////////////////////////////////////
    builder.clear();
    for (DataNode backendTableInfo : backendTableInfos) {
        builder.push(getBindableTableScan(bindableTableScan, cluster, relOptSchema, backendTableInfo));
    }
    value = builder.union(true, backendTableInfos.size()).build();
    return value;
}
 
Example #4
Source File: RelBuilderTest.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-3926">[CALCITE-3926]
 * CannotPlanException when an empty LogicalValues requires a certain collation</a>. */
@Test void testEmptyValuesWithCollation() throws Exception {
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelNode root =
      builder
          .scan("DEPT").empty()
          .sort(
              builder.field("DNAME"),
              builder.field("DEPTNO"))
          .build();
  try (PreparedStatement preparedStatement = RelRunners.run(root)) {
    final String result = CalciteAssert.toString(preparedStatement.executeQuery());
    final String expectedResult = "";
    assertThat(result, is(expectedResult));
  }
}
 
Example #5
Source File: PigRelBuilderStyleTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test @Disabled("CALCITE-1751")
public void testImplWithJoinAndGroupBy() throws Exception {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t").scan("s")
      .join(JoinRelType.LEFT,
          builder.equals(builder.field(2, 0, "tc1"), builder.field(2, 1, "sc0")))
      .filter(builder.call(GREATER_THAN, builder.field("tc0"), builder.literal("abc")))
      .aggregate(builder.groupKey("tc1"), builder.count(false, "c", builder.field("sc1")))
      .build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = FILTER t BY (tc0 > 'abc');\n"
          + "s = LOAD 'target/data2.txt"
          + "' USING PigStorage() AS (sc0:chararray, sc1:chararray);\n"
          + "t = JOIN t BY tc1 LEFT, s BY sc0;\n"
          + "t = GROUP t BY (tc1);\n"
          + "t = FOREACH t {\n"
          + "  GENERATE group AS tc1, COUNT(t.sc1) AS c;\n"
          + "};",
      new String[] { "(2,1)", "(3,0)" });
}
 
Example #6
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that project field name aliases are suggested incrementally.
 */
@Test void testAliasSuggester() {
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root = builder.scan("EMP")
      .project(builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0),
          builder.field(0))
      .build();
  final String expected = ""
      + "LogicalProject(EMPNO=[$0], EMPNO0=[$0], EMPNO1=[$0], "
      + "EMPNO2=[$0], EMPNO3=[$0], EMPNO4=[$0], EMPNO5=[$0], "
      + "EMPNO6=[$0], EMPNO7=[$0], EMPNO8=[$0], EMPNO9=[$0], EMPNO10=[$0])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #7
Source File: RelFieldTrimmerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testSortExchangeFieldTrimmerWhenProjectCannotBeMerged() {
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelNode root =
      builder.scan("EMP")
          .project(builder.field("EMPNO"), builder.field("ENAME"), builder.field("DEPTNO"))
          .sortExchange(RelDistributions.hash(Lists.newArrayList(1)), RelCollations.of(0))
          .project(builder.field("EMPNO"))
          .build();

  RelFieldTrimmer fieldTrimmer = new RelFieldTrimmer(null, builder);
  RelNode trimmed = fieldTrimmer.trim(root);

  final String expected = ""
      + "LogicalProject(EMPNO=[$0])\n"
      + "  LogicalSortExchange(distribution=[hash[1]], collation=[[0]])\n"
      + "    LogicalProject(EMPNO=[$0], ENAME=[$1])\n"
      + "      LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(trimmed, hasTree(expected));
}
 
Example #8
Source File: JoinRule.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public void onMatch(RelOptRuleCall call) {
  final Join join = call.rel(0);
  final RelNode left = join.getLeft();
  final RelNode right = join.getRight();
  final RelNode convertedLeft = convertIfNecessary(left);
  final RelNode convertedRight = convertIfNecessary(right);
  final RelBuilder builder = factory.create(join.getCluster(), null);

  builder.pushAll(ImmutableList.of(convertedLeft, convertedRight));
  builder.join(join.getJoinType(), join.getCondition());

  final RelNode newJoin = builder.build();
  if(newJoin != null) {
    call.transformTo(newJoin);
  }
}
 
Example #9
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests that a projection retains field names after a join. */
@Test void testProjectJoin() {
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.scan("EMP")
          .as("e")
          .scan("DEPT")
          .join(JoinRelType.INNER)
          .project(builder.field("DEPT", "DEPTNO"),
              builder.field(0),
              builder.field("e", "MGR"))
          // essentially a no-op, was previously throwing exception due to
          // project() using join-renamed fields
          .project(builder.field("DEPT", "DEPTNO"),
              builder.field(1),
              builder.field("e", "MGR"))
          .build();
  final String expected = ""
      + "LogicalProject(DEPTNO=[$8], EMPNO=[$0], MGR=[$3])\n"
      + "  LogicalJoin(condition=[true], joinType=[inner])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n"
      + "    LogicalTableScan(table=[[scott, DEPT]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #10
Source File: MutableRelTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Verifies equivalence of {@link MutableScan} */
@Test public void testMutableScanEquivalence() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);

  assertThat(mutableScanOf(builder, "EMP"),
      equalTo(mutableScanOf(builder, "EMP")));
  assertThat(mutableScanOf(builder, "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "scott", "EMP"),
      equalTo(mutableScanOf(builder, "scott", "EMP")));
  assertThat(mutableScanOf(builder, "scott", "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "scott", "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "scott", "EMP"),
      equalTo(mutableScanOf(builder, "EMP")));
  assertThat(mutableScanOf(builder, "scott", "EMP").hashCode(),
      equalTo(mutableScanOf(builder, "EMP").hashCode()));

  assertThat(mutableScanOf(builder, "EMP"),
      not(equalTo(mutableScanOf(builder, "DEPT"))));
}
 
Example #11
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testFilterCastNull() {
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelDataTypeFactory typeFactory = builder.getTypeFactory();
  final RelNode root =
      builder.scan("EMP")
          .filter(
              builder.getRexBuilder().makeCast(
                  typeFactory.createTypeWithNullability(
                      typeFactory.createSqlType(SqlTypeName.BOOLEAN), true),
                  builder.equals(builder.field("DEPTNO"),
                      builder.literal(10))))
          .build();
  final String expected = ""
      + "LogicalFilter(condition=[=($7, 10)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #12
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testUnion1() {
  // Equivalent SQL:
  //   SELECT deptno FROM dept
  //   UNION ALL
  //   SELECT empno FROM emp
  //   UNION ALL
  //   SELECT deptno FROM emp
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.scan("DEPT")
          .project(builder.field("DEPTNO"))
          .scan("EMP")
          .project(builder.field("EMPNO"))
          .scan("EMP")
          .project(builder.field("DEPTNO"))
          .union(true, 1)
          .build();
  final String expected = "LogicalProject(DEPTNO=[$7])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #13
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testSortByExpression() {
  // Equivalent SQL:
  //   SELECT *
  //   FROM emp
  //   ORDER BY ename ASC NULLS LAST, hiredate + mgr DESC NULLS FIRST
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelNode root =
      builder.scan("EMP")
          .sort(builder.nullsLast(builder.desc(builder.field(1))),
              builder.nullsFirst(
                  builder.call(SqlStdOperatorTable.PLUS, builder.field(4),
                      builder.field(3))))
          .build();
  final String expected =
      "LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], HIREDATE=[$4], SAL=[$5], COMM=[$6], DEPTNO=[$7])\n"
          + "  LogicalSort(sort0=[$1], sort1=[$8], dir0=[DESC-nulls-last], dir1=[ASC-nulls-first])\n"
          + "    LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], HIREDATE=[$4], SAL=[$5], COMM=[$6], DEPTNO=[$7], $f8=[+($4, $3)])\n"
          + "      LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #14
Source File: PigRelBuilderStyleTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test @Disabled("CALCITE-1751")
public void testImplWithMultipleFilters() {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t")
      .filter(
          builder.and(builder.call(GREATER_THAN, builder.field("tc0"), builder.literal("abc")),
              builder.call(EQUALS, builder.field("tc1"), builder.literal("3"))))
      .build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = FILTER t BY (tc0 > 'abc') AND (tc1 == '3');",
      new String[] { "(c,3)" });
}
 
Example #15
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests that table aliases are propagated and are available to a filter,
 * even when there is a project on top of a project. (Aliases tend to get lost
 * when projects are merged). */
@Test void testAliasFilter() {
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.scan("EMP")
          .as("EMP_alias")
          .project(builder.field("DEPTNO"),
              builder.literal(20))
          .project(builder.field(1), // literal 20
              builder.literal(10),
              builder.field(0)) // DEPTNO
          .filter(
              builder.call(SqlStdOperatorTable.GREATER_THAN,
                  builder.field(1),
                  builder.field("EMP_alias", "DEPTNO")))
          .build();
  final String expected = ""
      + "LogicalFilter(condition=[>($1, $2)])\n"
      + "  LogicalProject($f1=[20], $f2=[10], DEPTNO=[$7])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #16
Source File: RelWriterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testCorrelateQuery() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final Holder<RexCorrelVariable> v = Holder.of(null);
  RelNode relNode = builder.scan("EMP")
      .variable(v)
      .scan("DEPT")
      .filter(
          builder.equals(builder.field(0), builder.field(v.get(), "DEPTNO")))
      .correlate(
          JoinRelType.INNER, v.get().id, builder.field(2, 0, "DEPTNO"))
      .build();
  RelJsonWriter jsonWriter = new RelJsonWriter();
  relNode.explain(jsonWriter);
  final String relJson = jsonWriter.asString();
  String s = deserializeAndDumpToTextFormat(getSchema(relNode), relJson);
  final String expected = ""
      + "LogicalCorrelate(correlation=[$cor0], joinType=[inner], requiredColumns=[{7}])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n"
      + "  LogicalFilter(condition=[=($0, $cor0.DEPTNO)])\n"
      + "    LogicalTableScan(table=[[scott, DEPT]])\n";

  assertThat(s, isLinux(expected));
}
 
Example #17
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testFilterCastAny() {
  final RelBuilder builder = RelBuilder.create(config().build());
  final RelDataType anyType =
      builder.getTypeFactory().createSqlType(SqlTypeName.ANY);
  final RelNode root =
      builder.scan("EMP")
          .filter(
              builder.cast(
                  builder.getRexBuilder().makeInputRef(anyType, 0),
                  SqlTypeName.BOOLEAN))
          .build();
  final String expected = ""
      + "LogicalFilter(condition=[CAST($0):BOOLEAN NOT NULL])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #18
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Tests {@link org.apache.calcite.tools.RelRunner} for a table scan + filter
 * query. */
@Test void testRun() throws Exception {
  // Equivalent SQL:
  //   SELECT * FROM EMP WHERE DEPTNO = 20
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.scan("EMP")
          .filter(
              builder.equals(builder.field("DEPTNO"), builder.literal(20)))
          .build();

  // Note that because the table has been resolved in the RelNode tree
  // we do not need to supply a "schema" as context to the runner.
  try (PreparedStatement preparedStatement = RelRunners.run(root)) {
    String s = CalciteAssert.toString(preparedStatement.executeQuery());
    final String result = ""
        + "EMPNO=7369; ENAME=SMITH; JOB=CLERK; MGR=7902; HIREDATE=1980-12-17; SAL=800.00; COMM=null; DEPTNO=20\n"
        + "EMPNO=7566; ENAME=JONES; JOB=MANAGER; MGR=7839; HIREDATE=1981-02-04; SAL=2975.00; COMM=null; DEPTNO=20\n"
        + "EMPNO=7788; ENAME=SCOTT; JOB=ANALYST; MGR=7566; HIREDATE=1987-04-19; SAL=3000.00; COMM=null; DEPTNO=20\n"
        + "EMPNO=7876; ENAME=ADAMS; JOB=CLERK; MGR=7788; HIREDATE=1987-05-23; SAL=1100.00; COMM=null; DEPTNO=20\n"
        + "EMPNO=7902; ENAME=FORD; JOB=ANALYST; MGR=7566; HIREDATE=1981-12-03; SAL=3000.00; COMM=null; DEPTNO=20\n";
    assertThat(s, is(result));
  }
}
 
Example #19
Source File: JoinCommuteRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
public void onMatch(final RelOptRuleCall call) {
  Join join = call.rel(0);

  final RelNode swapped = swap(join, this.swapOuter, call.builder());
  if (swapped == null) {
    return;
  }

  // The result is either a Project or, if the project is trivial, a
  // raw Join.
  final Join newJoin =
      swapped instanceof Join
          ? (Join) swapped
          : (Join) swapped.getInput(0);

  call.transformTo(swapped);

  // We have converted join='a join b' into swapped='select
  // a0,a1,a2,b0,b1 from b join a'. Now register that project='select
  // b0,b1,a0,a1,a2 from (select a0,a1,a2,b0,b1 from b join a)' is the
  // same as 'b join a'. If we didn't do this, the swap join rule
  // would fire on the new join, ad infinitum.
  final RelBuilder relBuilder = call.builder();
  final List<RexNode> exps =
      RelOptUtil.createSwappedJoinExprs(newJoin, join, false);
  relBuilder.push(swapped)
      .project(exps, newJoin.getRowType().getFieldNames());

  call.getPlanner().ensureRegistered(relBuilder.build(), newJoin);
}
 
Example #20
Source File: RelDecorrelator.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected RelDecorrelator(
    CorelMap cm,
    Context context,
    RelBuilder relBuilder) {
  this.cm = cm;
  this.context = context;
  this.relBuilder = relBuilder;
}
 
Example #21
Source File: FlinkFilterJoinRule.java    From flink with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a FilterProjectTransposeRule with an explicit root operand and
 * factories.
 */
@Deprecated // to be removed before 2.0
protected FlinkFilterJoinRule(RelOptRuleOperand operand, String id,
		boolean smart, RelFactories.FilterFactory filterFactory,
		RelFactories.ProjectFactory projectFactory,
		Predicate predicate) {
	this(operand, id, smart, RelBuilder.proto(filterFactory, projectFactory),
			predicate);
}
 
Example #22
Source File: FilterJoinRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a FilterJoinRule with an explicit root operand and
 * factories.
 */
@Deprecated // to be removed before 2.0
protected FilterJoinRule(RelOptRuleOperand operand, String id,
    boolean smart, RelFactories.FilterFactory filterFactory,
    RelFactories.ProjectFactory projectFactory) {
  this(operand, id, smart, RelBuilder.proto(filterFactory, projectFactory),
      TRUE_PREDICATE);
}
 
Example #23
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testValuesBadNoFields() {
  try {
    final RelBuilder builder = RelBuilder.create(config().build());
    RelBuilder root = builder.values(new String[0], 1, 2, 3);
    fail("expected error, got " + root);
  } catch (IllegalArgumentException e) {
    assertThat(e.getMessage(),
        is("Value count must be a positive multiple of field count"));
  }
}
 
Example #24
Source File: FlinkAggregateJoinTransposeRule.java    From flink with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public FlinkAggregateJoinTransposeRule(Class<? extends Aggregate> aggregateClass,
		RelFactories.AggregateFactory aggregateFactory,
		Class<? extends Join> joinClass,
		RelFactories.JoinFactory joinFactory,
		RelFactories.ProjectFactory projectFactory,
		boolean allowFunctions) {
	this(aggregateClass, joinClass,
			RelBuilder.proto(aggregateFactory, joinFactory, projectFactory),
			allowFunctions);
}
 
Example #25
Source File: LogicalProjectDigestTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testProjectDigestWithOneTrivialField() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(builder.field("EMPNO"))
      .build();
  String digest = RelOptUtil.toString(rel, SqlExplainLevel.DIGEST_ATTRIBUTES);
  final String expected = ""
      + "LogicalProject(inputs=[0])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(digest, isLinux(expected));
}
 
Example #26
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private RexNode caseCall(RelBuilder b, RexNode ref, RexNode... nodes) {
  final List<RexNode> list = new ArrayList<>();
  for (int i = 0; i + 1 < nodes.length; i += 2) {
    list.add(b.equals(ref, nodes[i]));
    list.add(nodes[i + 1]);
  }
  list.add(nodes.length % 2 == 1 ? nodes[nodes.length - 1]
      : b.literal(null));
  return b.call(SqlStdOperatorTable.CASE, list);
}
 
Example #27
Source File: PigRelBuilderStyleTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testImplWithCountWithoutGroupBy() {
  final SchemaPlus schema = createTestSchema();
  final RelBuilder builder = createRelBuilder(schema);
  final RelNode node = builder.scan("t")
      .aggregate(builder.groupKey(), builder.count(false, "c", builder.field("tc0"))).build();
  final RelNode optimized = optimizeWithVolcano(node);
  assertScriptAndResults("t", getPigScript(optimized, schema),
      "t = LOAD 'target/data.txt"
          + "' USING PigStorage() AS (tc0:chararray, tc1:chararray);\n"
          + "t = GROUP t ALL;\n"
          + "t = FOREACH t {\n"
          + "  GENERATE COUNT(t.tc0) AS c;\n"
          + "};",
      new String[] { "(3)" });
}
 
Example #28
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testValues() {
  // Equivalent SQL:
  //   VALUES (true, 1), (false, -50) AS t(a, b)
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root =
      builder.values(new String[]{"a", "b"}, true, 1, false, -50)
          .build();
  final String expected =
      "LogicalValues(tuples=[[{ true, 1 }, { false, -50 }]])\n";
  assertThat(root, hasTree(expected));
  final String expectedType =
      "RecordType(BOOLEAN NOT NULL a, INTEGER NOT NULL b) NOT NULL";
  assertThat(root.getRowType().getFullTypeString(), is(expectedType));
}
 
Example #29
Source File: AggregateUnionAggregateRule.java    From Bats with Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public AggregateUnionAggregateRule(Class<? extends Aggregate> aggregateClass,
    RelFactories.AggregateFactory aggregateFactory,
    Class<? extends Union> unionClass,
    RelFactories.SetOpFactory setOpFactory) {
  this(aggregateClass, unionClass, RelNode.class, RelNode.class,
      RelBuilder.proto(aggregateFactory, setOpFactory),
      "AggregateUnionAggregateRule");
}
 
Example #30
Source File: RexShuttleTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Test case for
 * <a href="https://issues.apache.org/jira/browse/CALCITE-3165">[CALCITE-3165]
 * Project#accept(RexShuttle shuttle) does not update rowType</a>. */
@Test void testProjectUpdatesRowType() {
  final RelBuilder builder = RelBuilder.create(RelBuilderTest.config().build());

  // Equivalent SQL: SELECT deptno, sal FROM emp
  final RelNode root =
      builder
          .scan("EMP")
          .project(
              builder.field("DEPTNO"),
              builder.field("SAL"))
          .build();

  // Equivalent SQL: SELECT CAST(deptno AS VARCHAR), CAST(sal AS VARCHAR) FROM emp
  final RelNode rootWithCast =
      builder
          .scan("EMP")
          .project(
              builder.cast(builder.field("DEPTNO"), SqlTypeName.VARCHAR),
              builder.cast(builder.field("SAL"), SqlTypeName.VARCHAR))
          .build();
  final RelDataType type = rootWithCast.getRowType();

  // Transform the first expression into the second one, by using a RexShuttle
  // that converts every RexInputRef into a 'CAST(RexInputRef AS VARCHAR)'
  final RelNode rootWithCastViaRexShuttle = root.accept(new RexShuttle() {
    @Override public RexNode visitInputRef(RexInputRef inputRef) {
      return  builder.cast(inputRef, SqlTypeName.VARCHAR);
    }
  });
  final RelDataType type2 = rootWithCastViaRexShuttle.getRowType();

  assertThat(type, is(type2));
}