org.apache.calcite.sql.SqlExplainLevel Java Examples

The following examples show how to use org.apache.calcite.sql.SqlExplainLevel. 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: PrelSequencer.java    From dremio-oss with Apache License 2.0 7 votes vote down vote up
/**
 * Generate readable text and json plans and set them in <code>planHolder</code>
 * @param rel
 * @param explainlevel explain plan level.
 * @param observer
 */
public static String setPlansWithIds(final Prel rel, final SqlExplainLevel explainlevel, final AttemptObserver observer, final long millisTaken) {
  if (rel == null) {
    return null;
  }

  Map<Prel, OpId> relIdMap = getIdMap(rel);
  final StringWriter sw = new StringWriter();
  final RelWriter textPlanWriter = new NumberingRelWriter(relIdMap, new PrintWriter(sw), explainlevel);
  rel.explain(textPlanWriter);

  final String textPlan = sw.toString();
  observer.planText(sw.toString(), millisTaken);
  final RelJsonWriter jsonPlanWriter = new RelJsonWriter(getIdMap(rel), explainlevel);
  rel.explain(jsonPlanWriter);
  observer.planJsonPlan(jsonPlanWriter.asString());
  return textPlan;
}
 
Example #2
Source File: RelDecorrelator.java    From Bats with 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 #3
Source File: RelWriterTest.java    From calcite with 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 #4
Source File: RelOptMaterialization.java    From calcite with 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 File: RelWriterTest.java    From calcite with 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 File: RelOptMaterialization.java    From Bats with 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 #7
Source File: RelWriterTest.java    From calcite with 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 #8
Source File: RelWriterTest.java    From calcite with 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 #9
Source File: RelWriterTest.java    From calcite with 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 #10
Source File: ScanRelBase.java    From dremio-oss with Apache License 2.0 6 votes vote down vote up
@Override
public RelWriter explainTerms(RelWriter pw) {
  pw.item("table", tableMetadata.getName());
  if(projectedColumns != null){
    pw.item("columns", FluentIterable.from(projectedColumns).transform(new Function<SchemaPath, String>(){

      @Override
      public String apply(SchemaPath input) {
        return input.toString();
      }}).join(Joiner.on(", ")));
  }

  pw.item("splits", getTableMetadata().getSplitCount());

  if(observedRowcountAdjustment != 1.0d){
    pw.item("rowAdjust", observedRowcountAdjustment);
  }

  // we need to include the table metadata digest since not all properties (specifically which splits) are included in the explain output  (what base computeDigest uses).
  pw.itemIf("tableDigest", tableMetadata.computeDigest(), pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES);

  return pw;
}
 
Example #11
Source File: VolcanoPlanner.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * Dumps the internal state of this VolcanoPlanner to a writer.
 *
 * @param pw Print writer
 * @see #normalizePlan(String)
 */
public void dump(PrintWriter pw) {
  pw.println("Root: " + root);
  pw.println("Original rel:");

  if (originalRoot != null) {
    originalRoot.explain(
        new RelWriterImpl(pw, SqlExplainLevel.ALL_ATTRIBUTES, false));
  }

  try {
    if (CalciteSystemProperty.DUMP_SETS.value()) {
      pw.println();
      pw.println("Sets:");
      Dumpers.dumpSets(this, pw);
    }
    if (CalciteSystemProperty.DUMP_GRAPHVIZ.value()) {
      pw.println();
      pw.println("Graphviz:");
      Dumpers.dumpGraphviz(this, pw);
    }
  } catch (Exception | AssertionError e) {
    pw.println("Error when dumping plan state: \n"
        + e);
  }
}
 
Example #12
Source File: RelWriterTest.java    From calcite with 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 #13
Source File: SqlToOperationConverter.java    From flink with 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 #14
Source File: Project.java    From calcite with Apache License 2.0 5 votes vote down vote up
public RelWriter explainTerms(RelWriter pw) {
  super.explainTerms(pw);
  // Skip writing field names so the optimizer can reuse the projects that differ in
  // field names only
  if (pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES) {
    final int firstNonTrivial = countTrivial(exps);
    if (firstNonTrivial == 1) {
      pw.item("inputs", "0");
    } else if (firstNonTrivial != 0) {
      pw.item("inputs", "0.." + (firstNonTrivial - 1));
    }
    if (firstNonTrivial != exps.size()) {
      pw.item("exprs", exps.subList(firstNonTrivial, exps.size()));
    }
    return pw;
  }

  if (pw.nest()) {
    pw.item("fields", rowType.getFieldNames());
    pw.item("exprs", exps);
  } else {
    for (Ord<RelDataTypeField> field : Ord.zip(rowType.getFieldList())) {
      String fieldName = field.e.getName();
      if (fieldName == null) {
        fieldName = "field#" + field.i;
      }
      pw.item(fieldName, exps.get(field.i));
    }
  }

  return pw;
}
 
Example #15
Source File: PrelTransformer.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
public static void log(final String description, final RelNode node, final Logger logger, Stopwatch watch) {
  if (logger.isDebugEnabled()) {
    final String plan = RelOptUtil.toString(node, SqlExplainLevel.ALL_ATTRIBUTES);
    final String time = watch == null ? "" : String.format(" (%dms)", watch.elapsed(TimeUnit.MILLISECONDS));
    logger.debug(String.format("%s%s:\n%s", description, time, plan));
  }
}
 
Example #16
Source File: PlanTestBase.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * This method will take a SQL string statement, get the LOGICAL plan in Calcite
 * RelNode format. Then check the physical plan against the list expected
 * substrs. Verify all the expected strings are contained in the physical plan
 * string.
 */
public static void testRelLogicalPlanLevExplain(String sql, String... expectedSubstrs) throws Exception {
  final String planStr = getRelPlanInString(sql, SqlExplainLevel.EXPPLAN_ATTRIBUTES, Depth.LOGICAL);

  for (final String substr : expectedSubstrs) {
    assertTrue(planStr.contains(substr));
  }
}
 
Example #17
Source File: PlanTestBase.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
/**
 * This method will take a SQL string statement, get the PHYSICAL plan in
 * Calcite RelNode format. Then check the physical plan against the list
 * expected substrs. Verify all the expected strings are contained in the
 * physical plan string.
 */
public static void testRelPhysicalPlanLevDigest(String sql, String... expectedSubstrs)
    throws Exception {
  final String planStr = getRelPlanInString(sql, SqlExplainLevel.DIGEST_ATTRIBUTES, Depth.PHYSICAL);
  for (final String substr : expectedSubstrs) {
    assertTrue(planStr.contains(substr));
  }
}
 
Example #18
Source File: FrameworksTest.java    From calcite with 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 #19
Source File: LogicalProjectDigestTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Planner does not compare
 */
@Test void fieldNamesDoNotInfluenceDigest() {
  final RelBuilder rb = RelBuilder.create(Frameworks.newConfigBuilder().build());
  final RelNode xAsEmpid = rb.values(new String[]{"x", "y", "z"}, 1, 2, 3)
      .project(
          rb.alias(rb.field("x"), "renamed_x"),
          rb.alias(rb.field("y"), "renamed_y"),
          rb.alias(rb.literal("u"), "extra_field"))
      .build();

  assertThat(
      "project column name should not be included to the project digest",
      RelOptUtil.toString(xAsEmpid, SqlExplainLevel.DIGEST_ATTRIBUTES),
      isLinux(""
          + "LogicalProject(inputs=[0..1], exprs=[['u']])\n"
          + "  LogicalValues(type=[RecordType(INTEGER x, INTEGER y, INTEGER z)], tuples=[[{ 1, 2, 3 }]])\n"));

  assertThat(
      "project column names should be present in EXPPLAN_ATTRIBUTES",
      RelOptUtil.toString(xAsEmpid, SqlExplainLevel.EXPPLAN_ATTRIBUTES),
      isLinux(""
          + "LogicalProject(renamed_x=[$0], renamed_y=[$1], extra_field=['u'])\n"
          + "  LogicalValues(tuples=[[{ 1, 2, 3 }]])\n"));

  assertThat(
      "project column names should be present with default RelOptUtil.toString(...)",
      RelOptUtil.toString(xAsEmpid),
      isLinux(""
          + "LogicalProject(renamed_x=[$0], renamed_y=[$1], extra_field=['u'])\n"
          + "  LogicalValues(tuples=[[{ 1, 2, 3 }]])\n"));
}
 
Example #20
Source File: LogicalPlanCaptureListener.java    From dremio-oss with 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 #21
Source File: RelWriterTest.java    From calcite with 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 #22
Source File: ValuesRel.java    From dremio-oss with Apache License 2.0 5 votes vote down vote up
@Override
public RelWriter explainTerms(RelWriter pw) {
  return super.explainTerms(pw)
      .itemIf("type", this.rowType, pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES)
      .itemIf("type", this.rowType.getFieldList(), pw.nest())
      .itemIf("tuplesCount", rowCount, pw.getDetailLevel() != SqlExplainLevel.ALL_ATTRIBUTES)
      .itemIf("tuples", options.asNode(), pw.getDetailLevel() == SqlExplainLevel.DIGEST_ATTRIBUTES);
}
 
Example #23
Source File: RelWriterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testTableModifyDelete() {
  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.DELETE,
      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=[DELETE], flattened=[false])\n"
      + "  LogicalFilter(condition=[=($2, 'c')])\n"
      + "    LogicalTableScan(table=[[scott, EMP]])\n";
  assertThat(s, isLinux(expected));
}
 
Example #24
Source File: CalcitePrepareImpl.java    From calcite with 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 #25
Source File: SqlQueryParser.java    From quark with Apache License 2.0 5 votes vote down vote up
private RelNode parseInternal(String sql) throws SQLException {
  try {
    //final CalcitePrepare.Context prepareContext = context.getPrepareContext();
    //Class elementType = Object[].class;
    //RelNode relNode = new QuarkPrepare().prepare(prepareContext, sql, elementType, -1);
    RelNode relNode =  this.worker.parse(sql);
    LOG.info("\n" + RelOptUtil.dumpPlan(
        "", relNode, false, SqlExplainLevel.ALL_ATTRIBUTES));
    return relNode;
  } catch (CalciteContextException e) {
    throw new SQLException(e.getMessage(), e);
  }
}
 
Example #26
Source File: HBTBaseTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void testRel(Schema schema, String relText, String normalSugarText) {
    RelNode relNode = toRelNode(schema);
    Schema schema1 = toDSL(relNode);
    Assert.assertEquals(normalSugarText, toNormalString(schema1));

    Assert.assertEquals(
            relText.replace("\n", "").replace("\r", "").trim()
            ,
            RelOptUtil.toString(relNode, SqlExplainLevel.EXPPLAN_ATTRIBUTES)
                    .replace("\n", "").replace("\r", "").trim()
    );
}
 
Example #27
Source File: HBTBaseTest.java    From Mycat2 with GNU General Public License v3.0 5 votes vote down vote up
private void testRel(RelNode relNode, String expect) {
    Assert.assertEquals(
            expect.replace("\n", "").replace("\r", "").trim()
            ,
            RelOptUtil.toString(relNode, SqlExplainLevel.EXPPLAN_ATTRIBUTES)
                    .replace("\n", "").replace("\r", "").trim()
    );
}
 
Example #28
Source File: SqlToOperationConverter.java    From flink with 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 #29
Source File: RelDecorrelator.java    From calcite with 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 #30
Source File: TestCompilerUtils.java    From streamline with Apache License 2.0 5 votes vote down vote up
public static CalciteState sqlOverDummyTable(String sql)
        throws RelConversionException, ValidationException, SqlParseException {
    SchemaPlus schema = Frameworks.createRootSchema(true);
    JavaTypeFactory typeFactory = new JavaTypeFactoryImpl
            (RelDataTypeSystem.DEFAULT);
    StreamableTable streamableTable = new CompilerUtil.TableBuilderInfo(typeFactory)
            .field("ID", SqlTypeName.INTEGER)
            .field("NAME", typeFactory.createType(String.class))
            .field("ADDR", typeFactory.createType(String.class))
            .build();
    Table table = streamableTable.stream();
    schema.add("FOO", table);
    schema.add("BAR", table);
    schema.add("MYPLUS", ScalarFunctionImpl.create(MyPlus.class, "eval"));

    List<SqlOperatorTable> sqlOperatorTables = new ArrayList<>();
    sqlOperatorTables.add(SqlStdOperatorTable.instance());
    sqlOperatorTables.add(new CalciteCatalogReader(CalciteSchema.from(schema),
            false,
            Collections.<String>emptyList(), typeFactory));
    SqlOperatorTable chainedSqlOperatorTable = new ChainedSqlOperatorTable(sqlOperatorTables);
    FrameworkConfig config = Frameworks.newConfigBuilder().defaultSchema(
            schema).operatorTable(chainedSqlOperatorTable).build();
    Planner planner = Frameworks.getPlanner(config);
    SqlNode parse = planner.parse(sql);
    SqlNode validate = planner.validate(parse);
    RelNode tree = planner.convert(validate);
    System.out.println(RelOptUtil.toString(tree, SqlExplainLevel.ALL_ATTRIBUTES));
    return new CalciteState(schema, tree);
}