org.apache.calcite.adapter.enumerable.EnumerableConvention Java Examples

The following examples show how to use org.apache.calcite.adapter.enumerable.EnumerableConvention. 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: SortRemoveRuleTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/**
 * The default schema that is used in these tests provides tables sorted on the primary key. Due
 * to this scan operators always come with a {@link org.apache.calcite.rel.RelCollation} trait.
 */
private RelNode transform(String sql, RuleSet prepareRules) throws Exception {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final SchemaPlus defSchema = rootSchema.add("hr", new HrClusteredSchema());
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(defSchema)
      .traitDefs(ConventionTraitDef.INSTANCE, RelCollationTraitDef.INSTANCE)
      .programs(
          Programs.of(prepareRules),
          Programs.ofRules(SortRemoveRule.INSTANCE))
      .build();
  Planner planner = Frameworks.getPlanner(config);
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelRoot planRoot = planner.rel(validate);
  RelNode planBefore = planRoot.rel;
  RelTraitSet desiredTraits = planBefore.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode planAfter = planner.transform(0, desiredTraits, planBefore);
  return planner.transform(1, desiredTraits, planAfter);
}
 
Example #2
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testAdoptConventionEnumerable() {
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root = builder
      .adoptConvention(EnumerableConvention.INSTANCE)
      .scan("DEPT")
      .filter(
          builder.equals(builder.field("DEPTNO"), builder.literal(20)))
      .sort(builder.field(2), builder.desc(builder.field(0)))
      .project(builder.field(0))
      .build();
  String expected = ""
      + "EnumerableProject(DEPTNO=[$0])\n"
      + "  EnumerableSort(sort0=[$2], sort1=[$0], dir0=[ASC], dir1=[DESC])\n"
      + "    EnumerableFilter(condition=[=($0, 20)])\n"
      + "      EnumerableTableScan(table=[[scott, DEPT]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #3
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Override public RelNode convert(RelNode rel) {
  LogicalJoin join = (LogicalJoin) rel;
  assertThat(join.getHints().size(), is(1));
  assertThat(join.getHints().get(0), is(expectedHint));
  List<RelNode> newInputs = new ArrayList<>();
  for (RelNode input : join.getInputs()) {
    if (!(input.getConvention() instanceof EnumerableConvention)) {
      input =
        convert(
          input,
          input.getTraitSet()
            .replace(EnumerableConvention.INSTANCE));
    }
    newInputs.add(input);
  }
  final RelOptCluster cluster = join.getCluster();
  final RelNode left = newInputs.get(0);
  final RelNode right = newInputs.get(1);
  final JoinInfo info = join.analyzeCondition();
  return EnumerableHashJoin.create(
    left,
    right,
    info.getEquiCondition(left, right, cluster.getRexBuilder()),
    join.getVariablesSet(),
    join.getJoinType());
}
 
Example #4
Source File: TableEnv.java    From marble with Apache License 2.0 6 votes vote down vote up
protected RelRoot getSqlPlanRel(String sql) throws Throwable {
  try (Planner planner = Frameworks.getPlanner(frameworkConfig)) {
    RelRoot root;
    final SqlNode parsedSqlNode = planner.parse(sql);
    final Pair<SqlNode, RelDataType> validatedSqlNodeAndType = planner
        .validateAndGetType(
            parsedSqlNode);
    root = planner.rel(validatedSqlNodeAndType.getKey());
    final Program program = createProgram();
    //getDesiredTraits
    final RelTraitSet desiredTraits = root.rel.getTraitSet()
        .replace(EnumerableConvention.INSTANCE)
        .replace(root.collation)
        .simplify();

    RelNode logicalRelNode = root.rel;
    final RelNode optimizedRelNode = program.run(
        root.rel.getCluster().getPlanner(), logicalRelNode, desiredTraits,
        Collections.emptyList(), Collections.emptyList());
    root = root.withRel(optimizedRelNode);
    return root;
  }

}
 
Example #5
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testUseMergeJoin() {
  final String sql = "select /*+ use_merge_join(emp, dept) */\n"
      + "ename, job, sal, dept.name\n"
      + "from emp join dept on emp.deptno = dept.deptno";
  RelOptPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
  planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
  Tester tester1 = tester.withDecorrelation(true)
      .withClusterFactory(
          relOptCluster -> RelOptCluster.create(planner, relOptCluster.getRexBuilder()));
  final RelNode rel = tester1.convertSqlToRel(sql).rel;
  RuleSet ruleSet = RuleSets.ofList(
      EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE,
      EnumerableRules.ENUMERABLE_JOIN_RULE,
      EnumerableRules.ENUMERABLE_PROJECT_RULE,
      EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
      EnumerableRules.ENUMERABLE_SORT_RULE,
      AbstractConverter.ExpandConversionRule.INSTANCE);
  Program program = Programs.of(ruleSet);
  RelTraitSet toTraits = rel
      .getCluster()
      .traitSet()
      .replace(EnumerableConvention.INSTANCE);

  RelNode relAfter = program.run(planner, rel, toTraits,
      Collections.emptyList(), Collections.emptyList());

  String planAfter = NL + RelOptUtil.toString(relAfter);
  getDiffRepos().assertEquals("planAfter", "${planAfter}", planAfter);
}
 
Example #6
Source File: RelBuilderTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testSwitchConventions() {
  final RelBuilder builder = RelBuilder.create(config().build());
  RelNode root = builder
      .scan("DEPT")
      .adoptConvention(EnumerableConvention.INSTANCE)
      .filter(
          builder.equals(builder.field("DEPTNO"), builder.literal(20)))
      .sort(builder.field(2), builder.desc(builder.field(0)))
      .adoptConvention(Convention.NONE)
      .project(builder.field(0))
      .build();
  String expected = ""
      + "LogicalProject(DEPTNO=[$0])\n"
      + "  EnumerableSort(sort0=[$2], sort1=[$0], dir0=[ASC], dir1=[DESC])\n"
      + "    EnumerableFilter(condition=[=($0, 20)])\n"
      + "      LogicalTableScan(table=[[scott, DEPT]])\n";
  assertThat(root, hasTree(expected));
}
 
Example #7
Source File: EnumerableTableModifyExtensionRule.java    From kareldb with Apache License 2.0 6 votes vote down vote up
@Override
public RelNode convert(RelNode rel) {
    final LogicalTableModify modify =
        (LogicalTableModify) rel;
    final ModifiableTable modifiableTable =
        modify.getTable().unwrap(ModifiableTable.class);
    if (modifiableTable == null) {
        return null;
    }
    final RelTraitSet traitSet =
        modify.getTraitSet().replace(EnumerableConvention.INSTANCE);
    return new EnumerableTableModifyExtension(
        modify.getCluster(), traitSet,
        modify.getTable(),
        modify.getCatalogReader(),
        convert(modify.getInput(), traitSet),
        modify.getOperation(),
        modify.getUpdateColumnList(),
        modify.getSourceExpressionList(),
        modify.isFlattened());
}
 
Example #8
Source File: MycatCalcitePlanner.java    From Mycat2 with GNU General Public License v3.0 6 votes vote down vote up
public static RelNode toPhysical(RelNode rel, Consumer<RelOptPlanner> setting) {
    final RelOptPlanner planner = rel.getCluster().getPlanner();
    planner.clear();
    setting.accept(planner);
    planner.addRule(new RelOptRule(operand(MycatTransientSQLTableScan.class, none()), RelFactories.LOGICAL_BUILDER, "MycatTransientSQLTableScan") {

        @Override
        public void onMatch(RelOptRuleCall call) {
            final MycatTransientSQLTableScan scan = call.rel(0);
            final RelOptTable table = scan.getTable();
            if (Bindables.BindableTableScan.canHandle(table)) {
                call.transformTo(
                        Bindables.BindableTableScan.create(scan.getCluster(), table));
            }
        }
    });
    final Program program = Programs.of(RuleSets.ofList(planner.getRules()));
    return program.run(planner, rel, rel.getTraitSet().replace(EnumerableConvention.INSTANCE),
            ImmutableList.of(), ImmutableList.of());
}
 
Example #9
Source File: PlannerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Checks that a query returns a particular plan, using a planner with
 * MultiJoinOptimizeBushyRule enabled. */
private void checkBushy(String sql, String expected) throws Exception {
  final SchemaPlus rootSchema = Frameworks.createRootSchema(true);
  final FrameworkConfig config = Frameworks.newConfigBuilder()
      .parserConfig(SqlParser.Config.DEFAULT)
      .defaultSchema(
          CalciteAssert.addSchema(rootSchema,
              CalciteAssert.SchemaSpec.CLONE_FOODMART))
      .traitDefs((List<RelTraitDef>) null)
      .programs(Programs.heuristicJoinOrder(Programs.RULE_SET, true, 2))
      .build();
  Planner planner = Frameworks.getPlanner(config);
  SqlNode parse = planner.parse(sql);

  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).project();
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform), containsString(expected));
}
 
Example #10
Source File: PlannerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Unit test that calls {@link Planner#transform} twice. */
@Test void testPlanTransformTwice() throws Exception {
  RuleSet ruleSet =
      RuleSets.ofList(
          FilterMergeRule.INSTANCE,
          EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
          EnumerableRules.ENUMERABLE_FILTER_RULE,
          EnumerableRules.ENUMERABLE_PROJECT_RULE);
  Planner planner = getPlanner(null, Programs.of(ruleSet));
  SqlNode parse = planner.parse("select * from \"emps\"");
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).project();
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  RelNode transform2 = planner.transform(0, traitSet, transform);
  assertThat(toString(transform2),
      equalTo(
          "EnumerableProject(empid=[$0], deptno=[$1], name=[$2], salary=[$3], commission=[$4])\n"
          + "  EnumerableTableScan(table=[[hr, emps]])\n"));
}
 
Example #11
Source File: PlannerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private void runDuplicateSortCheck(String sql, String plan) throws Exception {
  RuleSet ruleSet =
      RuleSets.ofList(
          SortRemoveRule.INSTANCE,
          EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
          EnumerableRules.ENUMERABLE_PROJECT_RULE,
          EnumerableRules.ENUMERABLE_WINDOW_RULE,
          EnumerableRules.ENUMERABLE_SORT_RULE,
          ProjectToWindowRule.PROJECT);
  Planner planner = getPlanner(null,
      SqlParser.configBuilder().setLex(Lex.JAVA).build(),
      Programs.of(ruleSet));
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  if (traitSet.getTrait(RelCollationTraitDef.INSTANCE) == null) {
    // SortRemoveRule can only work if collation trait is enabled.
    return;
  }
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform), equalTo(plan));
}
 
Example #12
Source File: QueryPlanner.java    From sql-gremlin with Apache License 2.0 6 votes vote down vote up
public RelNode plan(String sql) {
    try {
        // hack to capitalize group by columns...not sure why the parser complains if the group by columns
        // are not capitalized
        final int groupByIndex = sql.toLowerCase().indexOf("group by");
        if(groupByIndex > -1) {
            final String firstPart = sql.substring(0, groupByIndex + "group by".length());
            final String groupPart = sql.substring(groupByIndex + "group by".length(), sql.length());
            sql = firstPart + groupPart.toUpperCase();
            // from index
            final int fromIndex = sql.toLowerCase().indexOf("from");
            sql = sql.substring(0, fromIndex).toUpperCase() + sql.substring(fromIndex, sql.length());
        }
        final SqlNode parse = planner.parse(sql);

        final SqlNode validate = planner.validate(parse);
        final RelNode convert = planner.convert(validate);
        final RelTraitSet traitSet = planner.getEmptyTraitSet()
                .replace(EnumerableConvention.INSTANCE);
        final RelNode transform = planner.transform(0, traitSet, convert);

        return transform;
    } catch (Exception e) {
        throw new ParseException("Error parsing: " + sql, e);
    }
}
 
Example #13
Source File: PlannerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Unit test that parses, validates, converts and
 * plans for query using order by */
@Test void testSortPlan() throws Exception {
  RuleSet ruleSet =
      RuleSets.ofList(
          SortRemoveRule.INSTANCE,
          EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
          EnumerableRules.ENUMERABLE_PROJECT_RULE,
          EnumerableRules.ENUMERABLE_SORT_RULE);
  Planner planner = getPlanner(null, Programs.of(ruleSet));
  SqlNode parse = planner.parse(
      "select * from \"emps\" "
          + "order by \"emps\".\"deptno\"");
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).project();
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform),
      equalTo("EnumerableSort(sort0=[$1], dir0=[ASC])\n"
          + "  EnumerableProject(empid=[$0], deptno=[$1], name=[$2], salary=[$3], commission=[$4])\n"
          + "    EnumerableTableScan(table=[[hr, emps]])\n"));
}
 
Example #14
Source File: RelTraitTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
@Test void testTraitSetDefault() {
  RelTraitSet traits = RelTraitSet.createEmpty();
  traits = traits.plus(Convention.NONE).plus(RelCollations.EMPTY);
  assertEquals(traits.size(), 2);
  assertTrue(traits.isDefault());
  traits = traits.replace(EnumerableConvention.INSTANCE);
  assertFalse(traits.isDefault());
  assertTrue(traits.isDefaultSansConvention());
  traits = traits.replace(RelCollations.of(0));
  assertFalse(traits.isDefault());
  assertFalse(traits.replace(Convention.NONE).isDefaultSansConvention());
  assertTrue(traits.getDefault().isDefault());
  traits = traits.getDefaultSansConvention();
  assertFalse(traits.isDefault());
  assertEquals(traits.getConvention(), EnumerableConvention.INSTANCE);
  assertTrue(traits.isDefaultSansConvention());
  assertEquals(traits.toString(), "ENUMERABLE.[]");
}
 
Example #15
Source File: PlannerTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
/** Unit test that parses, validates, converts and plans. */
@Test void testPlan() throws Exception {
  Program program =
      Programs.ofRules(
          FilterMergeRule.INSTANCE,
          EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
          EnumerableRules.ENUMERABLE_FILTER_RULE,
          EnumerableRules.ENUMERABLE_PROJECT_RULE);
  Planner planner = getPlanner(null, program);
  SqlNode parse = planner.parse("select * from \"emps\"");
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).project();
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform),
      equalTo(
          "EnumerableProject(empid=[$0], deptno=[$1], name=[$2], salary=[$3], commission=[$4])\n"
          + "  EnumerableTableScan(table=[[hr, emps]])\n"));
}
 
Example #16
Source File: LexCaseSensitiveTest.java    From calcite with Apache License 2.0 6 votes vote down vote up
private static void runProjectQueryWithLex(Lex lex, String sql)
    throws SqlParseException, ValidationException, RelConversionException {
  Config javaLex = SqlParser.configBuilder().setLex(lex).build();
  Planner planner = getPlanner(null, javaLex, Programs.ofRules(Programs.RULE_SET));
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  RelTraitSet traitSet =
      convert.getTraitSet().replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(transform, instanceOf(EnumerableProject.class));
  List<String> fieldNames = transform.getRowType().getFieldNames();
  assertThat(fieldNames.size(), is(2));
  if (lex.caseSensitive) {
    assertThat(fieldNames.get(0), is("EMPID"));
    assertThat(fieldNames.get(1), is("empid"));
  } else {
    assertThat(fieldNames.get(0) + "-" + fieldNames.get(1),
        anyOf(is("EMPID-empid0"), is("EMPID0-empid")));
  }
}
 
Example #17
Source File: VolcanoPlannerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Disabled("CALCITE-2592 EnumerableMergeJoin is never taken")
@Test void testMergeJoin() {
  VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  // Below two lines are important for the planner to use collation trait and generate merge join
  planner.addRelTraitDef(RelCollationTraitDef.INSTANCE);
  planner.registerAbstractRelationalRules();

  planner.addRule(EnumerableRules.ENUMERABLE_MERGE_JOIN_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_VALUES_RULE);
  planner.addRule(EnumerableRules.ENUMERABLE_SORT_RULE);

  RelOptCluster cluster = newCluster(planner);

  RelBuilder relBuilder = RelFactories.LOGICAL_BUILDER.create(cluster, null);
  RelNode logicalPlan = relBuilder
      .values(new String[]{"id", "name"}, "2", "a", "1", "b")
      .values(new String[]{"id", "name"}, "1", "x", "2", "y")
      .join(JoinRelType.INNER, "id")
      .build();

  RelTraitSet desiredTraits =
      cluster.traitSet().replace(EnumerableConvention.INSTANCE);
  final RelNode newRoot = planner.changeTraits(logicalPlan, desiredTraits);
  planner.setRoot(newRoot);

  RelNode bestExp = planner.findBestExp();

  final String plan = ""
      + "EnumerableMergeJoin(condition=[=($0, $2)], joinType=[inner])\n"
      + "  EnumerableSort(sort0=[$0], dir0=[ASC])\n"
      + "    EnumerableValues(tuples=[[{ '2', 'a' }, { '1', 'b' }]])\n"
      + "  EnumerableValues(tuples=[[{ '1', 'x' }, { '2', 'y' }]])\n";
  assertThat("Merge join + sort is expected", plan,
      isLinux(RelOptUtil.toString(bestExp)));
}
 
Example #18
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
MockEnumerableJoinRule(RelHint hint) {
  super(
      LogicalJoin.class,
      Convention.NONE,
      EnumerableConvention.INSTANCE,
      "MockEnumerableJoinRule");
  this.expectedHint = hint;
}
 
Example #19
Source File: SqlHintsConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testHintsPropagationInVolcanoPlannerRules() {
  final String sql = "select /*+ use_hash_join(r, s), use_hash_join(emp, dept) */\n"
      + "ename, job, sal, dept.name\n"
      + "from emp join dept on emp.deptno = dept.deptno";
  RelOptPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
  Tester tester1 = tester.withDecorrelation(true)
      .withClusterFactory(
        relOptCluster -> RelOptCluster.create(planner, relOptCluster.getRexBuilder()));
  final RelNode rel = tester1.convertSqlToRel(sql).rel;
  final RelHint hint = RelHint.builder("USE_HASH_JOIN")
      .inheritPath(0)
      .hintOption("EMP")
      .hintOption("DEPT")
      .build();
  // Validate Volcano planner.
  RuleSet ruleSet = RuleSets.ofList(
      new MockEnumerableJoinRule(hint), // Rule to validate the hint.
      FilterProjectTransposeRule.INSTANCE,
      FilterMergeRule.INSTANCE,
      ProjectMergeRule.INSTANCE,
      EnumerableRules.ENUMERABLE_JOIN_RULE,
      EnumerableRules.ENUMERABLE_PROJECT_RULE,
      EnumerableRules.ENUMERABLE_FILTER_RULE,
      EnumerableRules.ENUMERABLE_SORT_RULE,
      EnumerableRules.ENUMERABLE_LIMIT_RULE,
      EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE);
  Program program = Programs.of(ruleSet);
  RelTraitSet toTraits = rel
      .getCluster()
      .traitSet()
      .replace(EnumerableConvention.INSTANCE);

  program.run(planner, rel, toTraits,
      Collections.emptyList(), Collections.emptyList());
}
 
Example #20
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 #21
Source File: MaterializedViewRelOptRulesTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
protected List<RelNode> optimize(TestConfig testConfig) {
  RelNode queryRel = testConfig.queryRel;
  RelOptPlanner planner = queryRel.getCluster().getPlanner();
  RelTraitSet traitSet = queryRel.getCluster().traitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelOptUtil.registerDefaultRules(planner, true, false);
  return ImmutableList.of(
      Programs.standard().run(
          planner, queryRel, traitSet, testConfig.materializations, ImmutableList.of()));
}
 
Example #22
Source File: VolcanoPlannerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
PhysToIteratorConverter(
    RelOptCluster cluster,
    RelNode child) {
  super(
      cluster,
      ConventionTraitDef.INSTANCE,
      cluster.traitSetOf(EnumerableConvention.INSTANCE),
      child);
}
 
Example #23
Source File: PlannerTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private void checkHeuristic(String sql, String expected) throws Exception {
  Planner planner = getPlanner(null,
      Programs.heuristicJoinOrder(Programs.RULE_SET, false, 0));
  SqlNode parse = planner.parse(sql);
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE);
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform), containsString(expected));
}
 
Example #24
Source File: VolcanoPlannerTraitTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
@Test void testRuleMatchAfterConversion() {
  VolcanoPlanner planner = new VolcanoPlanner();

  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);
  planner.addRelTraitDef(ALT_TRAIT_DEF);

  planner.addRule(new PhysToIteratorConverterRule());
  planner.addRule(new PhysLeafRule());
  planner.addRule(new IterSingleRule());
  planner.addRule(new IterSinglePhysMergeRule());

  RelOptCluster cluster = newCluster(planner);

  NoneLeafRel noneLeafRel =
      RelOptUtil.addTrait(
          new NoneLeafRel(cluster, "noneLeafRel"), ALT_TRAIT);

  NoneSingleRel noneRel =
      RelOptUtil.addTrait(
          new NoneSingleRel(cluster, noneLeafRel), ALT_EMPTY_TRAIT);

  RelNode convertedRel =
      planner.changeTraits(noneRel,
          cluster.traitSetOf(EnumerableConvention.INSTANCE)
              .replace(ALT_EMPTY_TRAIT));

  planner.setRoot(convertedRel);
  RelNode result = planner.chooseDelegate().findBestExp();

  assertTrue(result instanceof IterMergedRel);
}
 
Example #25
Source File: CalcitePrepareImpl.java    From calcite with Apache License 2.0 5 votes vote down vote up
private ParseResult convert_(Context context, String sql, boolean analyze,
    boolean fail, CalciteCatalogReader catalogReader, SqlValidator validator,
    SqlNode sqlNode1) {
  final JavaTypeFactory typeFactory = context.getTypeFactory();
  final Convention resultConvention =
      enableBindable ? BindableConvention.INSTANCE
          : EnumerableConvention.INSTANCE;
  // Use the Volcano because it can handle the traits.
  final VolcanoPlanner planner = new VolcanoPlanner();
  planner.addRelTraitDef(ConventionTraitDef.INSTANCE);

  final SqlToRelConverter.ConfigBuilder configBuilder =
      SqlToRelConverter.configBuilder().withTrimUnusedFields(true);

  final CalcitePreparingStmt preparingStmt =
      new CalcitePreparingStmt(this, context, catalogReader, typeFactory,
          context.getRootSchema(), null, createCluster(planner, new RexBuilder(typeFactory)),
          resultConvention, createConvertletTable());
  final SqlToRelConverter converter =
      preparingStmt.getSqlToRelConverter(validator, catalogReader,
          configBuilder.build());

  final RelRoot root = converter.convertQuery(sqlNode1, false, true);
  if (analyze) {
    return analyze_(validator, sql, sqlNode1, root, fail);
  }
  return new ConvertResult(this, validator, sql, sqlNode1,
      validator.getValidatedNodeType(sqlNode1), root);
}
 
Example #26
Source File: ToLogicalConverterTest.java    From calcite with Apache License 2.0 5 votes vote down vote up
private static RelNode toPhysical(RelNode rel) {
  final RelOptPlanner planner = rel.getCluster().getPlanner();
  planner.clear();
  for (RelOptRule rule : RULE_SET) {
    planner.addRule(rule);
  }

  final Program program = Programs.of(RuleSets.ofList(planner.getRules()));
  return program.run(planner, rel, rel.getTraitSet().replace(EnumerableConvention.INSTANCE),
      ImmutableList.of(), ImmutableList.of());
}
 
Example #27
Source File: JdbcToEnumerableConverterRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/** Creates a JdbcToEnumerableConverterRule. */
public JdbcToEnumerableConverterRule(JdbcConvention out,
    RelBuilderFactory relBuilderFactory) {
  super(RelNode.class, (Predicate<RelNode>) r -> true, out,
      EnumerableConvention.INSTANCE, relBuilderFactory,
      "JdbcToEnumerableConverterRule");
}
 
Example #28
Source File: ElasticsearchToEnumerableConverterRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates an ElasticsearchToEnumerableConverterRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
private ElasticsearchToEnumerableConverterRule(
    RelBuilderFactory relBuilderFactory) {
  super(RelNode.class, (Predicate<RelNode>) r -> true,
      ElasticsearchRel.CONVENTION, EnumerableConvention.INSTANCE,
      relBuilderFactory, "ElasticsearchToEnumerableConverterRule");
}
 
Example #29
Source File: CassandraToEnumerableConverterRule.java    From calcite with Apache License 2.0 5 votes vote down vote up
/**
 * Creates a CassandraToEnumerableConverterRule.
 *
 * @param relBuilderFactory Builder for relational expressions
 */
public CassandraToEnumerableConverterRule(
    RelBuilderFactory relBuilderFactory) {
  super(RelNode.class, (Predicate<RelNode>) r -> true,
      CassandraRel.CONVENTION, EnumerableConvention.INSTANCE,
      relBuilderFactory, "CassandraToEnumerableConverterRule");
}
 
Example #30
Source File: PlannerTest.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-2554">[CALCITE-2554]
 * Enrich EnumerableHashJoin operator with order preserving information</a>.
 *
 * <p>Since the left input to the join is sorted, and this join preserves
 * order, there shouldn't be any sort operator above the join.
 */
@Test void testRedundantSortOnJoinPlan() throws Exception {
  RuleSet ruleSet =
      RuleSets.ofList(
          SortRemoveRule.INSTANCE,
          SortJoinTransposeRule.INSTANCE,
          SortProjectTransposeRule.INSTANCE,
          EnumerableRules.ENUMERABLE_TABLE_SCAN_RULE,
          EnumerableRules.ENUMERABLE_LIMIT_RULE,
          EnumerableRules.ENUMERABLE_JOIN_RULE,
          EnumerableRules.ENUMERABLE_PROJECT_RULE,
          EnumerableRules.ENUMERABLE_SORT_RULE);
  Planner planner = getPlanner(null, Programs.of(ruleSet));
  SqlNode parse = planner.parse(
      "select e.\"deptno\" from \"emps\" e "
          + "left outer join \"depts\" d "
          + " on e.\"deptno\" = d.\"deptno\" "
          + "order by e.\"deptno\" "
          + "limit 10");
  SqlNode validate = planner.validate(parse);
  RelNode convert = planner.rel(validate).rel;
  RelTraitSet traitSet = convert.getTraitSet()
      .replace(EnumerableConvention.INSTANCE).simplify();
  RelNode transform = planner.transform(0, traitSet, convert);
  assertThat(toString(transform),
      equalTo("EnumerableProject(deptno=[$1])\n"
      + "  EnumerableLimit(fetch=[10])\n"
      + "    EnumerableHashJoin(condition=[=($1, $5)], joinType=[left])\n"
      + "      EnumerableLimit(fetch=[10])\n"
      + "        EnumerableSort(sort0=[$1], dir0=[ASC])\n"
      + "          EnumerableTableScan(table=[[hr, emps]])\n"
      + "      EnumerableProject(deptno=[$0], name=[$1], employees=[$2], x=[$3.x], y=[$3.y])\n"
      + "        EnumerableTableScan(table=[[hr, depts]])\n"));
}