You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@calcite.apache.org by hy...@apache.org on 2020/05/28 05:51:57 UTC

[calcite] branch master updated: [CALCITE-3972] Allow RelBuilder to create RelNode with convention (Xiening Dai)

This is an automated email from the ASF dual-hosted git repository.

hyuan pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/calcite.git


The following commit(s) were added to refs/heads/master by this push:
     new ada6cc4  [CALCITE-3972] Allow RelBuilder to create RelNode with convention (Xiening Dai)
ada6cc4 is described below

commit ada6cc4309dd79e09abcbd67570b786d80340018
Author: Xiening Dai <xn...@live.com>
AuthorDate: Tue Mar 24 16:29:57 2020 -0700

    [CALCITE-3972] Allow RelBuilder to create RelNode with convention (Xiening Dai)
    
    1. Provide Convention.transformRelBuilder() to transform an existing RelBuilder
    into one with specific convention.
    2. RelBuilder provides withRelFactories() method to allow caller swap the
    underlying RelFactories and create a new builder.
    We can avoid ~1/3 of total rule firings in a N way join case with this change.
    
    Close #1884
---
 .../adapter/enumerable/EnumerableConvention.java   |  11 +++
 .../adapter/enumerable/EnumerableRelFactories.java | 102 +++++++++++++++++++++
 .../apache/calcite/plan/AbstractRelOptPlanner.java |  10 ++
 .../java/org/apache/calcite/plan/Convention.java   |   8 ++
 .../calcite/rel/rules/JoinPushThroughJoinRule.java |   2 +-
 .../java/org/apache/calcite/tools/RelBuilder.java  |  18 +++-
 .../org/apache/calcite/test/RelBuilderTest.java    |  39 ++++++++
 site/_docs/algebra.md                              |  15 +++
 8 files changed, 203 insertions(+), 2 deletions(-)

diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableConvention.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableConvention.java
index 5b583da..48ae551 100644
--- a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableConvention.java
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableConvention.java
@@ -16,6 +16,7 @@
  */
 package org.apache.calcite.adapter.enumerable;
 
+import org.apache.calcite.plan.Contexts;
 import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.ConventionTraitDef;
 import org.apache.calcite.plan.RelOptPlanner;
@@ -25,6 +26,7 @@ import org.apache.calcite.plan.RelTraitSet;
 import org.apache.calcite.rel.RelCollation;
 import org.apache.calcite.rel.RelCollationTraitDef;
 import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.RelFactories;
 
 /**
  * Family of calling conventions that return results as an
@@ -84,4 +86,13 @@ public enum EnumerableConvention implements Convention {
       RelTraitSet toTraits) {
     return true;
   }
+
+  public RelFactories.Struct getRelFactories() {
+    return RelFactories.Struct.fromContext(
+            Contexts.of(
+                EnumerableRelFactories.ENUMERABLE_TABLE_SCAN_FACTORY,
+                EnumerableRelFactories.ENUMERABLE_PROJECT_FACTORY,
+                EnumerableRelFactories.ENUMERABLE_FILTER_FACTORY,
+                EnumerableRelFactories.ENUMERABLE_SORT_FACTORY));
+  }
 }
diff --git a/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelFactories.java b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelFactories.java
new file mode 100644
index 0000000..ab9cdd0
--- /dev/null
+++ b/core/src/main/java/org/apache/calcite/adapter/enumerable/EnumerableRelFactories.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to you under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License.  You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.calcite.adapter.enumerable;
+
+import org.apache.calcite.plan.RelOptTable;
+import org.apache.calcite.rel.RelCollation;
+import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.CorrelationId;
+import org.apache.calcite.rel.hint.RelHint;
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.rex.RexUtil;
+import org.apache.calcite.sql.validate.SqlValidatorUtil;
+
+import java.util.List;
+import java.util.Set;
+
+/**
+ * Contains factory interface and default implementation for creating various
+ * rel nodes.
+ */
+public class EnumerableRelFactories {
+
+  public static final org.apache.calcite.rel.core.RelFactories.TableScanFactory
+      ENUMERABLE_TABLE_SCAN_FACTORY = new TableScanFactoryImpl();
+
+  public static final org.apache.calcite.rel.core.RelFactories.ProjectFactory
+      ENUMERABLE_PROJECT_FACTORY = new ProjectFactoryImpl();
+
+  public static final org.apache.calcite.rel.core.RelFactories.FilterFactory
+      ENUMERABLE_FILTER_FACTORY = new FilterFactoryImpl();
+
+  public static final org.apache.calcite.rel.core.RelFactories.SortFactory
+      ENUMERABLE_SORT_FACTORY = new SortFactoryImpl();
+
+  /**
+   * Implementation of {@link org.apache.calcite.rel.core.RelFactories.TableScanFactory} that
+   * returns a vanilla {@link EnumerableTableScan}.
+   */
+  private static class TableScanFactoryImpl
+      implements org.apache.calcite.rel.core.RelFactories.TableScanFactory {
+    public RelNode createScan(RelOptTable.ToRelContext toRelContext, RelOptTable table) {
+      return EnumerableTableScan.create(toRelContext.getCluster(), table);
+    }
+  }
+
+  /**
+   * Implementation of {@link org.apache.calcite.rel.core.RelFactories.ProjectFactory} that
+   * returns a vanilla {@link EnumerableProject}.
+   */
+  private static class ProjectFactoryImpl
+      implements org.apache.calcite.rel.core.RelFactories.ProjectFactory {
+    public RelNode createProject(RelNode input, List<RelHint> hints,
+                          List<? extends RexNode> childExprs, List<String> fieldNames) {
+      final RelDataType rowType =
+          RexUtil.createStructType(input.getCluster().getTypeFactory(), childExprs,
+              fieldNames, SqlValidatorUtil.F_SUGGESTER);
+      return EnumerableProject.create(input, childExprs, rowType);
+    }
+  }
+
+  /**
+   * Implementation of {@link org.apache.calcite.rel.core.RelFactories.FilterFactory} that
+   * returns a vanilla {@link EnumerableFilter}.
+   */
+  private static class FilterFactoryImpl
+      implements org.apache.calcite.rel.core.RelFactories.FilterFactory {
+    public RelNode createFilter(RelNode input, RexNode condition,
+                         Set<CorrelationId> variablesSet) {
+      return EnumerableFilter.create(input, condition);
+    }
+  }
+
+  /**
+   * Implementation of {@link org.apache.calcite.rel.core.RelFactories.SortFactory} that
+   * returns a vanilla {@link EnumerableSort}.
+   */
+  private static class SortFactoryImpl
+      implements org.apache.calcite.rel.core.RelFactories.SortFactory {
+    public RelNode createSort(RelNode input, RelCollation collation,
+                              RexNode offset, RexNode fetch) {
+      return EnumerableSort.create(input, collation, offset, fetch);
+    }
+  }
+
+  private EnumerableRelFactories() {
+  }
+}
diff --git a/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java b/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
index 222fcbb..c08975e 100644
--- a/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
+++ b/core/src/main/java/org/apache/calcite/plan/AbstractRelOptPlanner.java
@@ -518,13 +518,23 @@ public abstract class AbstractRelOptPlanner implements RelOptPlanner {
       sb.append(String
           .format(Locale.ROOT, "%n%-60s%20s%20s%n", "Rules", "Attempts", "Time (us)"));
       NumberFormat usFormat = NumberFormat.getNumberInstance(Locale.US);
+      long totalAttempts = 0;
+      long totalTime = 0;
       for (Map.Entry<String, Pair<Long, Long>> entry : list) {
         sb.append(
             String.format(Locale.ROOT, "%-60s%20s%20s%n",
                 entry.getKey(),
                 usFormat.format(entry.getValue().left),
                 usFormat.format(entry.getValue().right)));
+        totalAttempts += entry.getValue().left;
+        totalTime += entry.getValue().right;
       }
+      sb.append(
+          String.format(Locale.ROOT, "%-60s%20s%20s%n",
+              "* Total",
+              usFormat.format(totalAttempts),
+              usFormat.format(totalTime)));
+
       return sb.toString();
     }
   }
diff --git a/core/src/main/java/org/apache/calcite/plan/Convention.java b/core/src/main/java/org/apache/calcite/plan/Convention.java
index 1d7b5f7..ac30507 100644
--- a/core/src/main/java/org/apache/calcite/plan/Convention.java
+++ b/core/src/main/java/org/apache/calcite/plan/Convention.java
@@ -17,6 +17,7 @@
 package org.apache.calcite.plan;
 
 import org.apache.calcite.rel.RelNode;
+import org.apache.calcite.rel.core.RelFactories;
 
 /**
  * Calling convention trait.
@@ -82,6 +83,13 @@ public interface Convention extends RelTrait {
   }
 
   /**
+   * Return RelFactories struct for the convention which can be used to build RelNode
+   */
+  default RelFactories.Struct getRelFactories() {
+    return RelFactories.DEFAULT_STRUCT;
+  }
+
+  /**
    * Default implementation.
    */
   class Impl implements Convention {
diff --git a/core/src/main/java/org/apache/calcite/rel/rules/JoinPushThroughJoinRule.java b/core/src/main/java/org/apache/calcite/rel/rules/JoinPushThroughJoinRule.java
index ac205e9..58d188a 100644
--- a/core/src/main/java/org/apache/calcite/rel/rules/JoinPushThroughJoinRule.java
+++ b/core/src/main/java/org/apache/calcite/rel/rules/JoinPushThroughJoinRule.java
@@ -87,7 +87,7 @@ public class JoinPushThroughJoinRule extends RelOptRule implements Transformatio
     super(
         operand(clazz,
             operand(clazz, any()),
-            operand(RelNode.class, any())),
+            operandJ(RelNode.class, null, n -> !n.isEnforcer(), any())),
         relBuilderFactory, description);
     this.right = right;
   }
diff --git a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
index 24577be..5d5f391 100644
--- a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
+++ b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
@@ -152,7 +152,7 @@ public class RelBuilder {
   private final RexSimplify simplifier;
   private final Config config;
   private final RelOptTable.ViewExpander viewExpander;
-  private final RelFactories.Struct struct;
+  private RelFactories.Struct struct;
 
   protected RelBuilder(Context context, RelOptCluster cluster,
       RelOptSchema relOptSchema) {
@@ -230,6 +230,13 @@ public class RelBuilder {
     return cluster.getTypeFactory();
   }
 
+  /** Returns new RelBuilder that adopts the convention provided.
+   * RelNode will be created with such convention if corresponding factory is provided. */
+  public RelBuilder adoptConvention(Convention convention) {
+    this.struct = convention.getRelFactories();
+    return this;
+  }
+
   /** Returns the builder for {@link RexNode} expressions. */
   public RexBuilder getRexBuilder() {
     return cluster.getRexBuilder();
@@ -2497,6 +2504,15 @@ public class RelBuilder {
     return sortLimit(offset, fetch, ImmutableList.copyOf(nodes));
   }
 
+  /** Creates a {@link Sort} by specifying collations.
+   */
+  public RelBuilder sort(RelCollation collation) {
+    final RelNode sort =
+        struct.sortFactory.createSort(peek(), collation, null, null);
+    replaceTop(sort);
+    return this;
+  }
+
   /** Creates a {@link Sort} by a list of expressions, with limit and offset.
    *
    * @param offset Number of rows to skip; non-positive means don't skip any
diff --git a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
index f096e39..1273960 100644
--- a/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
+++ b/core/src/test/java/org/apache/calcite/test/RelBuilderTest.java
@@ -16,8 +16,10 @@
  */
 package org.apache.calcite.test;
 
+import org.apache.calcite.adapter.enumerable.EnumerableConvention;
 import org.apache.calcite.jdbc.CalciteConnection;
 import org.apache.calcite.plan.Contexts;
+import org.apache.calcite.plan.Convention;
 import org.apache.calcite.plan.RelOptTable;
 import org.apache.calcite.plan.RelTraitDef;
 import org.apache.calcite.rel.RelCollations;
@@ -3357,6 +3359,43 @@ public class RelBuilderTest {
     assertThat(root, hasTree(expected));
   }
 
+  @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));
+  }
+
+  @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));
+  }
+
   @Test void testHints() {
     final RelHint indexHint = RelHint.builder("INDEX")
         .hintOption("_idx1")
diff --git a/site/_docs/algebra.md b/site/_docs/algebra.md
index c9aab8c..7310c53 100644
--- a/site/_docs/algebra.md
+++ b/site/_docs/algebra.md
@@ -187,6 +187,21 @@ final RelNode result = builder
   .build();
 {% endhighlight %}
 
+### Switch Convention
+
+The default RelBuilder creates logical RelNode without coventions. But you could
+switch to use a different convention through `adoptConvention()`:
+
+{% highlight java %}
+final RelNode result = builder
+  .push(input)
+  .adoptConvention(EnumerableConvention.INSTANCE)
+  .sort(toCollation)
+  .build();
+{% endhighlight %}
+
+In this case, we create an EnumerableSort on top of the input RelNode.
+
 ### Field names and ordinals
 
 You can reference a field by name or ordinal.