Java Code Examples for org.apache.calcite.sql.SqlExplainFormat

The following examples show how to use org.apache.calcite.sql.SqlExplainFormat. 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: Bats   Source File: RelDecorrelator.java    License: Apache License 2.0 6 votes vote down vote up
/** Decorrelates a query.
 *
 * <p>This is the main entry point to {@code RelDecorrelator}.
 *
 * @param rootRel           Root node of the query
 * @param relBuilder        Builder for relational expressions
 *
 * @return Equivalent query with all
 * {@link org.apache.calcite.rel.logical.LogicalCorrelate} instances removed
 */
public static RelNode decorrelateQuery(RelNode rootRel, RelBuilder relBuilder) {
    final CorelMap corelMap = new CorelMapBuilder().build(rootRel);
    if (!corelMap.hasCorrelation()) {
        return rootRel;
    }

    final RelOptCluster cluster = rootRel.getCluster();
    final RelDecorrelator decorrelator = new RelDecorrelator(corelMap, cluster.getPlanner().getContext(),
            relBuilder);

    RelNode newRootRel = decorrelator.removeCorrelationViaRule(rootRel);

    if (SQL2REL_LOGGER.isDebugEnabled()) {
        SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after removing Correlator", newRootRel,
                SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
    }

    if (!decorrelator.cm.mapCorToCorRel.isEmpty()) {
        newRootRel = decorrelator.decorrelate(newRootRel);
    }

    return newRootRel;
}
 
Example 2
Source Project: Bats   Source File: RelOptMaterialization.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a relational expression to a form where
 * {@link org.apache.calcite.rel.logical.LogicalJoin}s are
 * as close to leaves as possible.
 */
public static RelNode toLeafJoinForm(RelNode rel) {
  final Program program = Programs.hep(
      ImmutableList.of(
          JoinProjectTransposeRule.RIGHT_PROJECT,
          JoinProjectTransposeRule.LEFT_PROJECT,
          FilterJoinRule.FilterIntoJoinRule.FILTER_ON_JOIN,
          ProjectRemoveRule.INSTANCE,
          ProjectMergeRule.INSTANCE),
      false,
      DefaultRelMetadataProvider.INSTANCE);
  if (CalciteSystemProperty.DEBUG.value()) {
    System.out.println(
        RelOptUtil.dumpPlan("before", rel, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  final RelNode rel2 = program.run(null, rel, null,
      ImmutableList.of(),
      ImmutableList.of());
  if (CalciteSystemProperty.DEBUG.value()) {
    System.out.println(
        RelOptUtil.dumpPlan("after", rel2, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  return rel2;
}
 
Example 3
Source Project: calcite   Source File: RelFieldTrimmer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Trims unused fields from a relational expression.
 *
 * <p>We presume that all fields of the relational expression are wanted by
 * its consumer, so only trim fields that are not used within the tree.
 *
 * @param root Root node of relational expression
 * @return Trimmed relational expression
 */
public RelNode trim(RelNode root) {
  final int fieldCount = root.getRowType().getFieldCount();
  final ImmutableBitSet fieldsUsed = ImmutableBitSet.range(fieldCount);
  final Set<RelDataTypeField> extraFields = Collections.emptySet();
  final TrimResult trimResult =
      dispatchTrimFields(root, fieldsUsed, extraFields);
  if (!trimResult.right.isIdentity()) {
    throw new IllegalArgumentException();
  }
  if (SqlToRelConverter.SQL2REL_LOGGER.isDebugEnabled()) {
    SqlToRelConverter.SQL2REL_LOGGER.debug(
        RelOptUtil.dumpPlan("Plan after trimming unused fields",
            trimResult.left, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES));
  }
  return trimResult.left;
}
 
Example 4
Source Project: calcite   Source File: RelOptMaterialization.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Converts a relational expression to a form where
 * {@link org.apache.calcite.rel.logical.LogicalJoin}s are
 * as close to leaves as possible.
 */
public static RelNode toLeafJoinForm(RelNode rel) {
  final Program program = Programs.hep(
      ImmutableList.of(
          JoinProjectTransposeRule.RIGHT_PROJECT,
          JoinProjectTransposeRule.LEFT_PROJECT,
          FilterJoinRule.FilterIntoJoinRule.FILTER_ON_JOIN,
          ProjectRemoveRule.INSTANCE,
          ProjectMergeRule.INSTANCE),
      false,
      DefaultRelMetadataProvider.INSTANCE);
  if (CalciteSystemProperty.DEBUG.value()) {
    System.out.println(
        RelOptUtil.dumpPlan("before", rel, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  final RelNode rel2 = program.run(null, rel, null,
      ImmutableList.of(),
      ImmutableList.of());
  if (CalciteSystemProperty.DEBUG.value()) {
    System.out.println(
        RelOptUtil.dumpPlan("after", rel2, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  return rel2;
}
 
Example 5
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Unit test for {@link org.apache.calcite.rel.externalize.RelJsonReader}.
 */
@Test void testReader() {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        SchemaPlus schema =
            rootSchema.add("hr",
                new ReflectiveSchema(new JdbcTest.HrSchema()));
        final RelJsonReader reader =
            new RelJsonReader(cluster, relOptSchema, schema);
        RelNode node;
        try {
          node = reader.read(XX);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });

  assertThat(s,
      isLinux("LogicalAggregate(group=[{0}], c=[COUNT(DISTINCT $1)], d=[COUNT()])\n"
          + "  LogicalFilter(condition=[=($1, 10)])\n"
          + "    LogicalTableScan(table=[[hr, emps]])\n"));
}
 
Example 6
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Unit test for {@link org.apache.calcite.rel.externalize.RelJsonReader}.
 */
@Test void testReaderNull() {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        SchemaPlus schema =
            rootSchema.add("hr",
                new ReflectiveSchema(new JdbcTest.HrSchema()));
        final RelJsonReader reader =
            new RelJsonReader(cluster, relOptSchema, schema);
        RelNode node;
        try {
          node = reader.read(XXNULL);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });

  assertThat(s,
      isLinux("LogicalAggregate(group=[{0}], agg#0=[COUNT(DISTINCT $1)], agg#1=[COUNT()])\n"
          + "  LogicalFilter(condition=[=($1, null:INTEGER)])\n"
          + "    LogicalTableScan(table=[[hr, emps]])\n"));
}
 
Example 7
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testUdf() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(new MockSqlOperatorTable.MyFunction(),
              builder.field("EMPNO")))
      .build();
  String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[MYFUN($0)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 8
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testUDAF() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(builder.field("ENAME"), builder.field("DEPTNO"))
      .aggregate(
          builder.groupKey("ENAME"),
          builder.aggregateCall(new MockSqlOperatorTable.MyAggFunc(),
              builder.field("DEPTNO")))
      .build();
  final String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  final String result = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalAggregate(group=[{0}], agg#0=[myAggFunc($1)])\n"
      + "  LogicalProject(ENAME=[$1], DEPTNO=[$7])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(result, isLinux(expected));
}
 
Example 9
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testArrayType() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RelNode rel = builder
      .scan("EMP")
      .project(
          builder.call(new MockSqlOperatorTable.SplitFunction(),
              builder.field("ENAME"), builder.literal(",")))
      .build();
  final String relJson = RelOptUtil.dumpPlan("", rel,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  final String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[SPLIT($1, ',')])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 10
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Deserialize a relnode from the json string by {@link RelJsonReader},
 * and dump it to text format.
 */
private String deserializeAndDumpToTextFormat(RelOptSchema schema, String relJson) {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        final RelJsonReader reader = new RelJsonReader(
            cluster, schema, rootSchema);
        RelNode node;
        try {
          node = reader.read(relJson);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });
  return s;
}
 
Example 11
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test void testTableModifyInsert() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode project = builder
      .scan("EMP")
      .project(builder.fields(), ImmutableList.of(), true)
      .build();
  LogicalTableModify modify = LogicalTableModify.create(
      project.getInput(0).getTable(),
      (Prepare.CatalogReader) project.getInput(0).getTable().getRelOptSchema(),
      project,
      TableModify.Operation.INSERT,
      null,
      null,
      false);
  String relJson = RelOptUtil.dumpPlan("", modify,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(modify), relJson);
  final String expected = ""
      + "LogicalTableModify(table=[[scott, EMP]], operation=[INSERT], flattened=[false])\n"
      + "  LogicalProject(EMPNO=[$0], ENAME=[$1], JOB=[$2], MGR=[$3], HIREDATE=[$4], SAL=[$5], "
      + "COMM=[$6], DEPTNO=[$7])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 12
Source Project: Bats   Source File: RelFieldTrimmer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Trims unused fields from a relational expression.
 *
 * <p>We presume that all fields of the relational expression are wanted by
 * its consumer, so only trim fields that are not used within the tree.
 *
 * @param root Root node of relational expression
 * @return Trimmed relational expression
 */
public RelNode trim(RelNode root) {
    final int fieldCount = root.getRowType().getFieldCount();
    final ImmutableBitSet fieldsUsed = ImmutableBitSet.range(fieldCount);
    final Set<RelDataTypeField> extraFields = Collections.emptySet();
    final TrimResult trimResult = dispatchTrimFields(root, fieldsUsed, extraFields);
    if (!trimResult.right.isIdentity()) {
        throw new IllegalArgumentException();
    }
    if (SqlToRelConverter.SQL2REL_LOGGER.isDebugEnabled()) {
        SqlToRelConverter.SQL2REL_LOGGER.debug(RelOptUtil.dumpPlan("Plan after trimming unused fields",
                trimResult.left, SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
    }
    return trimResult.left;
}
 
Example 13
Source Project: flink   Source File: RelDecorrelator.java    License: Apache License 2.0 5 votes vote down vote up
/** Decorrelates a query.
 *
 * <p>This is the main entry point to {@code RelDecorrelator}.
 *
 * @param rootRel           Root node of the query
 * @param relBuilder        Builder for relational expressions
 *
 * @return Equivalent query with all
 * {@link LogicalCorrelate} instances removed
 */
public static RelNode decorrelateQuery(RelNode rootRel,
    RelBuilder relBuilder) {
  final CorelMap corelMap = new CorelMapBuilder().build(rootRel);
  if (!corelMap.hasCorrelation()) {
    return rootRel;
  }

  final RelOptCluster cluster = rootRel.getCluster();
  final RelDecorrelator decorrelator =
      new RelDecorrelator(corelMap,
          cluster.getPlanner().getContext(), relBuilder);

  RelNode newRootRel = decorrelator.removeCorrelationViaRule(rootRel);

  if (SQL2REL_LOGGER.isDebugEnabled()) {
    SQL2REL_LOGGER.debug(
        RelOptUtil.dumpPlan("Plan after removing Correlator", newRootRel,
            SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
  }

  if (!decorrelator.cm.mapCorToCorRel.isEmpty()) {
    newRootRel = decorrelator.decorrelate(newRootRel);
  }

  return newRootRel;
}
 
Example 14
Source Project: flink   Source File: RelDecorrelator.java    License: Apache License 2.0 5 votes vote down vote up
/** Decorrelates a query.
 *
 * <p>This is the main entry point to {@code RelDecorrelator}.
 *
 * @param rootRel           Root node of the query
 * @param relBuilder        Builder for relational expressions
 *
 * @return Equivalent query with all
 * {@link org.apache.calcite.rel.logical.LogicalCorrelate} instances removed
 */
public static RelNode decorrelateQuery(RelNode rootRel,
    RelBuilder relBuilder) {
  final CorelMap corelMap = new CorelMapBuilder().build(rootRel);
  if (!corelMap.hasCorrelation()) {
    return rootRel;
  }

  final RelOptCluster cluster = rootRel.getCluster();
  final RelDecorrelator decorrelator =
      new RelDecorrelator(corelMap,
          cluster.getPlanner().getContext(), relBuilder);

  RelNode newRootRel = decorrelator.removeCorrelationViaRule(rootRel);

  if (SQL2REL_LOGGER.isDebugEnabled()) {
    SQL2REL_LOGGER.debug(
        RelOptUtil.dumpPlan("Plan after removing Correlator", newRootRel,
            SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
  }

  if (!decorrelator.cm.mapCorToCorRel.isEmpty()) {
    newRootRel = decorrelator.decorrelate(newRootRel);
  }

  return newRootRel;
}
 
Example 15
Source Project: dremio-oss   Source File: PlanCaptureAttemptObserver.java    License: Apache License 2.0 5 votes vote down vote up
public String toStringOrEmpty(final RelNode plan, boolean ensureDump) {
  if (!verbose && !ensureDump) {
    return "";
  }

  if(plan == null) {
    return "";
  }

  return RelOptUtil.dumpPlan("", plan, SqlExplainFormat.TEXT,
    verbose ? SqlExplainLevel.ALL_ATTRIBUTES : SqlExplainLevel.EXPPLAN_ATTRIBUTES);
}
 
Example 16
Source Project: dremio-oss   Source File: LogicalPlanCaptureListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void onPhaseCompletion(final PlannerPhase phase, final RelNode before, final RelNode after, final long millisTaken) {
  if (!Strings.isNullOrEmpty(plan)) {
    return;
  }

  if (phase == PlannerPhase.LOGICAL) {
    plan = RelOptUtil.dumpPlan("", after, SqlExplainFormat.TEXT, SqlExplainLevel.ALL_ATTRIBUTES);
  }
}
 
Example 17
Source Project: flink   Source File: SqlToOperationConverter.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert EXPLAIN statement. */
private Operation convertExplain(SqlExplain sqlExplain) {
	Operation operation = convertSqlQuery(sqlExplain.getExplicandum());

	if (sqlExplain.getDetailLevel() != SqlExplainLevel.EXPPLAN_ATTRIBUTES ||
			sqlExplain.getDepth() != SqlExplain.Depth.PHYSICAL ||
			sqlExplain.getFormat() != SqlExplainFormat.TEXT) {
		throw new TableException("Only default behavior is supported now, EXPLAIN PLAN FOR xx");
	}

	return new ExplainOperation(operation);
}
 
Example 18
Source Project: flink   Source File: SqlToOperationConverter.java    License: Apache License 2.0 5 votes vote down vote up
/** Convert EXPLAIN statement. */
private Operation convertExplain(SqlExplain sqlExplain) {
	Operation operation = convertSqlQuery(sqlExplain.getExplicandum());

	if (sqlExplain.getDetailLevel() != SqlExplainLevel.EXPPLAN_ATTRIBUTES ||
			sqlExplain.getDepth() != SqlExplain.Depth.PHYSICAL ||
			sqlExplain.getFormat() != SqlExplainFormat.TEXT) {
		throw new TableException("Only default behavior is supported now, EXPLAIN PLAN FOR xx");
	}

	return new ExplainOperation(operation);
}
 
Example 19
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override protected PreparedResult createPreparedExplanation(
    RelDataType resultType,
    RelDataType parameterRowType,
    RelRoot root,
    SqlExplainFormat format,
    SqlExplainLevel detailLevel) {
  return new CalcitePreparedExplain(resultType, parameterRowType, root,
      format, detailLevel);
}
 
Example 20
Source Project: calcite   Source File: CalcitePrepareImpl.java    License: Apache License 2.0 5 votes vote down vote up
CalcitePreparedExplain(
    RelDataType resultType,
    RelDataType parameterRowType,
    RelRoot root,
    SqlExplainFormat format,
    SqlExplainLevel detailLevel) {
  super(resultType, parameterRowType, root, format, detailLevel);
}
 
Example 21
Source Project: calcite   Source File: Prepare.java    License: Apache License 2.0 5 votes vote down vote up
public PreparedExplain(
    RelDataType rowType,
    RelDataType parameterRowType,
    RelRoot root,
    SqlExplainFormat format,
    SqlExplainLevel detailLevel) {
  this.rowType = rowType;
  this.parameterRowType = parameterRowType;
  this.root = root;
  this.format = format;
  this.detailLevel = detailLevel;
}
 
Example 22
Source Project: calcite   Source File: RelDecorrelator.java    License: Apache License 2.0 5 votes vote down vote up
/** Decorrelates a query.
 *
 * <p>This is the main entry point to {@code RelDecorrelator}.
 *
 * @param rootRel           Root node of the query
 * @param relBuilder        Builder for relational expressions
 *
 * @return Equivalent query with all
 * {@link org.apache.calcite.rel.core.Correlate} instances removed
 */
public static RelNode decorrelateQuery(RelNode rootRel,
    RelBuilder relBuilder) {
  final CorelMap corelMap = new CorelMapBuilder().build(rootRel);
  if (!corelMap.hasCorrelation()) {
    return rootRel;
  }

  final RelOptCluster cluster = rootRel.getCluster();
  final RelDecorrelator decorrelator =
      new RelDecorrelator(corelMap,
          cluster.getPlanner().getContext(), relBuilder);

  RelNode newRootRel = decorrelator.removeCorrelationViaRule(rootRel);

  if (SQL2REL_LOGGER.isDebugEnabled()) {
    SQL2REL_LOGGER.debug(
        RelOptUtil.dumpPlan("Plan after removing Correlator", newRootRel,
            SqlExplainFormat.TEXT, SqlExplainLevel.EXPPLAN_ATTRIBUTES));
  }

  if (!decorrelator.cm.mapCorToCorRel.isEmpty()) {
    newRootRel = decorrelator.decorrelate(newRootRel);
  }

  // Re-propagate the hints.
  newRootRel = RelOptUtil.propagateRelHints(newRootRel, true);

  return newRootRel;
}
 
Example 23
Source Project: calcite   Source File: RelOptUtil.java    License: Apache License 2.0 5 votes vote down vote up
@Deprecated // to be removed before 2.0
public static String dumpPlan(
    String header,
    RelNode rel,
    boolean asXml,
    SqlExplainLevel detailLevel) {
  return dumpPlan(header, rel,
      asXml ? SqlExplainFormat.XML : SqlExplainFormat.TEXT, detailLevel);
}
 
Example 24
Source Project: calcite   Source File: FrameworksTest.java    License: Apache License 2.0 5 votes vote down vote up
private void executeQuery(FrameworkConfig config,
    @SuppressWarnings("SameParameterValue") String query, boolean debug)
    throws RelConversionException, SqlParseException, ValidationException {
  Planner planner = Frameworks.getPlanner(config);
  if (debug) {
    System.out.println("Query:" + query);
  }
  SqlNode n = planner.parse(query);
  n = planner.validate(n);
  RelNode root = planner.rel(n).project();
  if (debug) {
    System.out.println(
        RelOptUtil.dumpPlan("-- Logical Plan", root, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  RelOptCluster cluster = root.getCluster();
  final RelOptPlanner optPlanner = cluster.getPlanner();

  RelTraitSet desiredTraits  =
      cluster.traitSet().replace(EnumerableConvention.INSTANCE);
  final RelNode newRoot = optPlanner.changeTraits(root, desiredTraits);
  if (debug) {
    System.out.println(
        RelOptUtil.dumpPlan("-- Mid Plan", newRoot, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
  optPlanner.setRoot(newRoot);
  RelNode bestExp = optPlanner.findBestExp();
  if (debug) {
    System.out.println(
        RelOptUtil.dumpPlan("-- Best Plan", bestExp, SqlExplainFormat.TEXT,
            SqlExplainLevel.DIGEST_ATTRIBUTES));
  }
}
 
Example 25
Source Project: calcite   Source File: TraitPropagationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testOne() throws Exception {
  RelNode planned = run(new PropAction(), RULES);
  if (CalciteSystemProperty.DEBUG.value()) {
    System.out.println(
        RelOptUtil.dumpPlan("LOGICAL PLAN", planned, SqlExplainFormat.TEXT,
            SqlExplainLevel.ALL_ATTRIBUTES));
  }
  final RelMetadataQuery mq = planned.getCluster().getMetadataQuery();
  assertEquals(3, 0, mq.getCumulativeCost(planned).getRows(),
      "Sortedness was not propagated");
}
 
Example 26
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Unit test for {@link org.apache.calcite.rel.externalize.RelJsonReader}.
 */
@Test void testReader2() {
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        SchemaPlus schema =
            rootSchema.add("hr",
                new ReflectiveSchema(new JdbcTest.HrSchema()));
        final RelJsonReader reader =
            new RelJsonReader(cluster, relOptSchema, schema);
        RelNode node;
        try {
          node = reader.read(XX2);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });

  assertThat(s,
      isLinux("LogicalProject(field0=[$0],"
          + " field1=[COUNT($0) OVER (PARTITION BY $2 ORDER BY $1 NULLS LAST "
          + "ROWS UNBOUNDED PRECEDING)],"
          + " field2=[SUM($0) OVER (PARTITION BY $2 ORDER BY $1 NULLS LAST "
          + "RANGE BETWEEN CURRENT ROW AND 1 FOLLOWING)])\n"
          + "  LogicalTableScan(table=[[hr, emps]])\n"));
}
 
Example 27
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testCalc() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  final RexBuilder rexBuilder = builder.getRexBuilder();
  final LogicalTableScan scan = (LogicalTableScan) builder.scan("EMP").build();
  final RexProgramBuilder programBuilder =
      new RexProgramBuilder(scan.getRowType(), rexBuilder);
  final RelDataTypeField field = scan.getRowType().getField("SAL", false, false);
  programBuilder.addIdentity();
  programBuilder.addCondition(
      rexBuilder.makeCall(SqlStdOperatorTable.GREATER_THAN,
          new RexInputRef(field.getIndex(), field.getType()),
          builder.literal(10)));
  final LogicalCalc calc = LogicalCalc.create(scan, programBuilder.getProgram());
  String relJson = RelOptUtil.dumpPlan("", calc,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s =
      Frameworks.withPlanner((cluster, relOptSchema, rootSchema) -> {
        final RelJsonReader reader = new RelJsonReader(
            cluster, getSchema(calc), rootSchema);
        RelNode node;
        try {
          node = reader.read(relJson);
        } catch (IOException e) {
          throw TestUtil.rethrow(e);
        }
        return RelOptUtil.dumpPlan("", node, SqlExplainFormat.TEXT,
            SqlExplainLevel.EXPPLAN_ATTRIBUTES);
      });
  final String expected =
      "LogicalCalc(expr#0..7=[{inputs}], expr#8=[10], expr#9=[>($t5, $t8)],"
          + " proj#0..7=[{exprs}], $condition=[$t9])\n"
          + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 28
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testOverWithoutPartition() {
  // The rel stands for the sql of "select count(*) over (order by deptno) from EMP"
  final RelNode rel = mockCountOver("EMP", ImmutableList.of(), ImmutableList.of("DEPTNO"));
  String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON,
      SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[COUNT() OVER (ORDER BY $7 NULLS LAST "
      + "ROWS UNBOUNDED PRECEDING)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 29
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testOverWithoutOrderKey() {
  // The rel stands for the sql of "select count(*) over (partition by DEPTNO) from EMP"
  final RelNode rel = mockCountOver("EMP", ImmutableList.of("DEPTNO"), ImmutableList.of());
  String relJson = RelOptUtil.dumpPlan("", rel, SqlExplainFormat.JSON,
      SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(rel), relJson);
  final String expected = ""
      + "LogicalProject($f0=[COUNT() OVER (PARTITION BY $7)])\n"
      + "  LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example 30
Source Project: calcite   Source File: RelWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test void testTableModifyUpdate() {
  final FrameworkConfig config = RelBuilderTest.config().build();
  final RelBuilder builder = RelBuilder.create(config);
  RelNode filter = builder
      .scan("EMP")
      .filter(
          builder.call(
              SqlStdOperatorTable.EQUALS,
              builder.field("JOB"),
              builder.literal("c")))
      .build();
  LogicalTableModify modify = LogicalTableModify.create(
      filter.getInput(0).getTable(),
      (Prepare.CatalogReader) filter.getInput(0).getTable().getRelOptSchema(),
      filter,
      TableModify.Operation.UPDATE,
      ImmutableList.of("ENAME"),
      ImmutableList.of(builder.literal("a")),
      false);
  String relJson = RelOptUtil.dumpPlan("", modify,
      SqlExplainFormat.JSON, SqlExplainLevel.EXPPLAN_ATTRIBUTES);
  String s = deserializeAndDumpToTextFormat(getSchema(modify), relJson);
  final String expected = ""
      + "LogicalTableModify(table=[[scott, EMP]], operation=[UPDATE], updateColumnList=[[ENAME]],"
      + " sourceExpressionList=[['a']], flattened=[false])\n"
      + "  LogicalFilter(condition=[=($2, 'c')])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}