You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@calcite.apache.org by jh...@apache.org on 2017/01/29 22:06:20 UTC

calcite git commit: [CALCITE-1603] Support TUMBLE window function in the GROUP BY clause (Julian Hyde and Haohui Mai)

Repository: calcite
Updated Branches:
  refs/heads/master 2d7e1f1a6 -> bc232c269


[CALCITE-1603] Support TUMBLE window function in the GROUP BY clause (Julian Hyde and Haohui Mai)

Close apache/calcite#368


Project: http://git-wip-us.apache.org/repos/asf/calcite/repo
Commit: http://git-wip-us.apache.org/repos/asf/calcite/commit/bc232c26
Tree: http://git-wip-us.apache.org/repos/asf/calcite/tree/bc232c26
Diff: http://git-wip-us.apache.org/repos/asf/calcite/diff/bc232c26

Branch: refs/heads/master
Commit: bc232c2699a886b4af81c594fef43a08ab72fe90
Parents: 2d7e1f1
Author: Haohui Mai <wh...@apache.org>
Authored: Fri Jan 27 14:46:46 2017 -0800
Committer: Julian Hyde <jh...@apache.org>
Committed: Sun Jan 29 12:02:02 2017 -0800

----------------------------------------------------------------------
 .../apache/calcite/runtime/CalciteResource.java |  5 ++
 .../java/org/apache/calcite/sql/SqlKind.java    | 13 +++
 .../org/apache/calcite/sql/SqlOperator.java     | 26 ++++++
 .../calcite/sql/fun/SqlGroupFunction.java       | 89 ++++++++++++++++++++
 .../calcite/sql/fun/SqlStdOperatorTable.java    | 25 ++++++
 .../apache/calcite/sql/type/OperandTypes.java   | 13 +++
 .../apache/calcite/sql/validate/AggChecker.java | 41 +++++++++
 .../apache/calcite/sql/validate/AggFinder.java  | 20 +++--
 .../sql/validate/AggregatingSelectScope.java    | 43 +++++-----
 .../calcite/sql/validate/SqlValidatorImpl.java  | 47 +++++++----
 .../calcite/sql/validate/SqlValidatorUtil.java  | 71 +++++++++++-----
 .../calcite/sql2rel/SqlToRelConverter.java      | 52 +++++-------
 .../org/apache/calcite/tools/RelBuilder.java    |  7 +-
 .../calcite/runtime/CalciteResource.properties  |  2 +
 .../apache/calcite/test/SqlValidatorTest.java   | 47 +++++++++++
 .../calcite/test/SqlToRelConverterTest.xml      | 16 ++++
 16 files changed, 420 insertions(+), 97 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
index 9ada4f2..bf277a6 100644
--- a/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
+++ b/core/src/main/java/org/apache/calcite/runtime/CalciteResource.java
@@ -654,6 +654,11 @@ public interface CalciteResource {
   @BaseMessage("SELECT must have a FROM clause")
   ExInst<SqlValidatorException> selectMissingFrom();
 
+  @BaseMessage("Group function ''{0}'' can only appear in GROUP BY clause")
+  ExInst<SqlValidatorException> groupFunctionMustAppearInGroupByClause(String funcName);
+
+  @BaseMessage("Call to auxiliary group function ''{0}'' must have matching call to group function ''{1}'' in GROUP BY clause")
+  ExInst<SqlValidatorException> auxiliaryWithoutMatchingGroupCall(String func1, String func2);
 }
 
 // End CalciteResource.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/SqlKind.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlKind.java b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
index 2f6b5fd..e9ecd7d 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlKind.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlKind.java
@@ -773,6 +773,19 @@ public enum SqlKind {
   /** The {@code ROW_NUMBER} window function. */
   CUME_DIST,
 
+  // Group functions
+
+  /** The {@code TUMBLE} group function. */
+  TUMBLE,
+
+  /** The {@code TUMBLE_START} auxiliary function of
+   * the {@link #TUMBLE} function. */
+  TUMBLE_START,
+
+  /** The {@code TUMBLE_END} auxiliary function of
+   * the {@link #TUMBLE} function. */
+  TUMBLE_END,
+
   // DDL and session control statements follow. The list is not exhaustive: feel
   // free to add more.
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/SqlOperator.java b/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
index 7a65b10..8a7f345 100644
--- a/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
+++ b/core/src/main/java/org/apache/calcite/sql/SqlOperator.java
@@ -792,6 +792,32 @@ public abstract class SqlOperator {
   }
 
   /**
+   * Returns whether this is a group function.
+   *
+   * <p>Group functions can only appear in the GROUP BY clause.
+   *
+   * <p>Examples are {@code HOP}, {@code TUMBLE}, {@code SESSION}.
+   *
+   * <p>Group functions have auxiliary functions, e.g. {@code HOP_START}, but
+   * these are not group functions.
+   */
+  public boolean isGroup() {
+    return false;
+  }
+
+  /**
+   * Returns whether this is an group auxiliary function.
+   *
+   * <p>Examples are {@code HOP_START} and {@code HOP_END} (both auxiliary to
+   * {@code HOP}).
+   *
+   * @see #isGroup()
+   */
+  public boolean isGroupAuxiliary() {
+    return false;
+  }
+
+  /**
    * Accepts a {@link SqlVisitor}, visiting each operand of a call. Returns
    * null.
    *

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/fun/SqlGroupFunction.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlGroupFunction.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlGroupFunction.java
new file mode 100644
index 0000000..24f2b9c
--- /dev/null
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlGroupFunction.java
@@ -0,0 +1,89 @@
+/*
+ * 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.sql.fun;
+
+import org.apache.calcite.sql.SqlFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlOperatorBinding;
+import org.apache.calcite.sql.type.ReturnTypes;
+import org.apache.calcite.sql.type.SqlOperandTypeChecker;
+import org.apache.calcite.sql.validate.SqlMonotonicity;
+
+/**
+ * SQL function that computes keys by which rows can be partitioned and
+ * aggregated.
+ *
+ * <p>Group functions always occur in the GROUP BY clause. They often have
+ * auxiliary functions that access information about the group. For example,
+ * {@code HOP} is a group function, and its auxiliary functions are
+ * {@code HOP_START} and {@code HOP_END}. Here they are used in a streaming
+ * query:
+ *
+ * <blockquote><pre>
+ * SELECT STREAM HOP_START(rowtime, INTERVAL '1' HOUR),
+ *   HOP_END(rowtime, INTERVAL '1' HOUR),
+ *   MIN(unitPrice)
+ * FROM Orders
+ * GROUP BY HOP(rowtime, INTERVAL '1' HOUR), productId
+ * </pre></blockquote>
+ */
+class SqlGroupFunction extends SqlFunction {
+  private final SqlGroupFunction groupFunction;
+
+  /** Creates a SqlGroupFunction.
+   *
+   * @param kind Kind; also determines function name
+   * @param groupFunction Group function, if this is an auxiliary;
+   *                      null, if this is a group function
+   * @param operandTypeChecker Operand type checker
+   */
+  SqlGroupFunction(SqlKind kind, SqlGroupFunction groupFunction,
+      SqlOperandTypeChecker operandTypeChecker) {
+    super(kind.name(), kind, ReturnTypes.ARG0, null,
+        operandTypeChecker, SqlFunctionCategory.SYSTEM);
+    this.groupFunction = groupFunction;
+    if (groupFunction != null) {
+      assert groupFunction.groupFunction == null;
+    }
+  }
+
+  /** Creates an auxiliary function from this group function. */
+  SqlGroupFunction auxiliary(SqlKind kind) {
+    return new SqlGroupFunction(kind, this, getOperandTypeChecker());
+  }
+
+  @Override public boolean isGroup() {
+    // Auxiliary functions are not group functions
+    return groupFunction == null;
+  }
+
+  @Override public boolean isGroupAuxiliary() {
+    return groupFunction != null;
+  }
+
+  @Override public SqlMonotonicity getMonotonicity(SqlOperatorBinding call) {
+    // Monotonic iff its first argument is, but not strict.
+    //
+    // Note: This strategy happens to works for all current group functions
+    // (HOP, TUMBLE, SESSION). When there are exceptions to this rule, we'll
+    // make the method abstract.
+    return call.getOperandMonotonicity(0).unstrict();
+  }
+}
+
+// End SqlGroupFunction.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
index dfbdfa0..8e1983e 100644
--- a/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
+++ b/core/src/main/java/org/apache/calcite/sql/fun/SqlStdOperatorTable.java
@@ -1843,6 +1843,19 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
         }
       };
 
+  public static final SqlGroupFunction TUMBLE =
+      new SqlGroupFunction(SqlKind.TUMBLE, null,
+          OperandTypes.or(OperandTypes.DATETIME_INTERVAL,
+              OperandTypes.DATETIME_INTERVAL_TIME));
+
+  /** The TUMBLE_START auxiliary function of the TUMBLE group function. */
+  public static final SqlFunction TUMBLE_START =
+      TUMBLE.auxiliary(SqlKind.TUMBLE_START);
+
+  /** The TUMBLE_END auxiliary function of the TUMBLE group function. */
+  public static final SqlFunction TUMBLE_END =
+      TUMBLE.auxiliary(SqlKind.TUMBLE_END);
+
   //~ Methods ----------------------------------------------------------------
 
   /**
@@ -1858,6 +1871,18 @@ public class SqlStdOperatorTable extends ReflectiveSqlOperatorTable {
     }
     return instance;
   }
+
+  /** Returns the group function for which a given kind is an auxiliary
+   * function, or null if it is not an auxiliary function. */
+  public static SqlGroupFunction auxiliaryToGroup(SqlKind kind) {
+    switch (kind) {
+    case TUMBLE_START:
+    case TUMBLE_END:
+      return TUMBLE;
+    default:
+      return null;
+    }
+  }
 }
 
 // End SqlStdOperatorTable.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
index 9a5e351..e27e9db 100644
--- a/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
+++ b/core/src/main/java/org/apache/calcite/sql/type/OperandTypes.java
@@ -424,6 +424,19 @@ public abstract class OperandTypes {
   public static final SqlSingleOperandTypeChecker DATETIME_INTERVAL =
       family(SqlTypeFamily.DATETIME, SqlTypeFamily.DATETIME_INTERVAL);
 
+  public static final SqlSingleOperandTypeChecker DATETIME_INTERVAL_INTERVAL =
+      family(SqlTypeFamily.DATETIME, SqlTypeFamily.DATETIME_INTERVAL,
+          SqlTypeFamily.DATETIME_INTERVAL);
+
+  public static final SqlSingleOperandTypeChecker
+  DATETIME_INTERVAL_INTERVAL_TIME =
+      family(SqlTypeFamily.DATETIME, SqlTypeFamily.DATETIME_INTERVAL,
+          SqlTypeFamily.DATETIME_INTERVAL, SqlTypeFamily.TIME);
+
+  public static final SqlSingleOperandTypeChecker DATETIME_INTERVAL_TIME =
+      family(SqlTypeFamily.DATETIME, SqlTypeFamily.DATETIME_INTERVAL,
+          SqlTypeFamily.TIME);
+
   public static final SqlSingleOperandTypeChecker INTERVAL_DATETIME =
       family(SqlTypeFamily.DATETIME_INTERVAL, SqlTypeFamily.DATETIME);
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java b/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
index 88c0585..bb5622f 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggChecker.java
@@ -16,14 +16,17 @@
  */
 package org.apache.calcite.sql.validate;
 
+import org.apache.calcite.sql.SqlBasicCall;
 import org.apache.calcite.sql.SqlCall;
 import org.apache.calcite.sql.SqlIdentifier;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlNode;
 import org.apache.calcite.sql.SqlNodeList;
+import org.apache.calcite.sql.SqlOperator;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.sql.SqlUtil;
 import org.apache.calcite.sql.SqlWindow;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.util.SqlBasicVisitor;
 import org.apache.calcite.util.Litmus;
 
@@ -41,6 +44,7 @@ class AggChecker extends SqlBasicVisitor<Void> {
   //~ Instance fields --------------------------------------------------------
 
   private final Deque<SqlValidatorScope> scopes = new ArrayDeque<>();
+  private final List<SqlNode> extraExprs;
   private final List<SqlNode> groupExprs;
   private boolean distinct;
   private SqlValidatorImpl validator;
@@ -60,9 +64,11 @@ class AggChecker extends SqlBasicVisitor<Void> {
   AggChecker(
       SqlValidatorImpl validator,
       AggregatingScope scope,
+      List<SqlNode> extraExprs,
       List<SqlNode> groupExprs,
       boolean distinct) {
     this.validator = validator;
+    this.extraExprs = extraExprs;
     this.groupExprs = groupExprs;
     this.distinct = distinct;
     this.scopes.push(scope);
@@ -76,6 +82,12 @@ class AggChecker extends SqlBasicVisitor<Void> {
         return true;
       }
     }
+
+    for (SqlNode extraExpr : extraExprs) {
+      if (extraExpr.equalsDeep(expr, Litmus.IGNORE)) {
+        return true;
+      }
+    }
     return false;
   }
 
@@ -167,6 +179,25 @@ class AggChecker extends SqlBasicVisitor<Void> {
       // This call matches an expression in the GROUP BY clause.
       return null;
     }
+
+    final SqlCall groupCall = convertAuxiliaryToGroupCall(call);
+    if (groupCall != null) {
+      if (isGroupExpr(groupCall)) {
+        // This call is an auxiliary function that matches a group call in the
+        // GROUP BY clause.
+        //
+        // For example TUMBLE_START is an auxiliary of the TUMBLE
+        // group function, and
+        //   TUMBLE_START(rowtime, INTERVAL '1' HOUR)
+        // matches
+        //   TUMBLE(rowtime, INTERVAL '1' HOUR')
+        return null;
+      }
+      throw validator.newValidationError(groupCall,
+          RESOURCE.auxiliaryWithoutMatchingGroupCall(
+              call.getOperator().getName(), groupCall.getOperator().getName()));
+    }
+
     if (call.isA(SqlKind.QUERY)) {
       // Allow queries for now, even though they may contain
       // references to forbidden columns.
@@ -185,6 +216,16 @@ class AggChecker extends SqlBasicVisitor<Void> {
     scopes.pop();
     return null;
   }
+
+  private SqlCall convertAuxiliaryToGroupCall(SqlCall call) {
+    SqlOperator op = SqlStdOperatorTable.auxiliaryToGroup(call.getKind());
+    if (op == null) {
+      return null;
+    }
+    final List<SqlNode> list = call.getOperandList();
+    return new SqlBasicCall(op, list.toArray(new SqlNode[list.size()]),
+        call.getParserPosition());
+  }
 }
 
 // End AggChecker.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/validate/AggFinder.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggFinder.java b/core/src/main/java/org/apache/calcite/sql/validate/AggFinder.java
index 64fd133..d8d51f0 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggFinder.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggFinder.java
@@ -45,6 +45,10 @@ class AggFinder extends SqlBasicVisitor<Void> {
   /** Whether to find regular (non-windowed) aggregates. */
   private boolean aggregate;
 
+  /** Whether to find group functions (e.g. {@code TUMBLE})
+   * or group auxiliary functions (e.g. {@code TUMBLE_START}). */
+  private boolean group;
+
   private final AggFinder delegate;
 
   //~ Constructors -----------------------------------------------------------
@@ -56,14 +60,15 @@ class AggFinder extends SqlBasicVisitor<Void> {
    * @param over Whether to find windowed function calls {@code agg(x) OVER
    *             windowSpec}
    * @param aggregate Whether to find non-windowed aggregate calls
+   * @param group Whether to find group functions (e.g. {@code TUMBLE})
    * @param delegate Finder to which to delegate when processing the arguments
-   *                  to a non-windowed aggregate
    */
   AggFinder(SqlOperatorTable opTab, boolean over, boolean aggregate,
-      AggFinder delegate) {
+      boolean group, AggFinder delegate) {
     this.opTab = opTab;
     this.over = over;
     this.aggregate = aggregate;
+    this.group = group;
     this.delegate = delegate;
   }
 
@@ -75,17 +80,17 @@ class AggFinder extends SqlBasicVisitor<Void> {
    * @param node Parse tree to search
    * @return First aggregate function in parse tree, or null if not found
    */
-  public SqlNode findAgg(SqlNode node) {
+  public SqlCall findAgg(SqlNode node) {
     try {
       node.accept(this);
       return null;
     } catch (Util.FoundOne e) {
       Util.swallow(e, null);
-      return (SqlNode) e.getNode();
+      return (SqlCall) e.getNode();
     }
   }
 
-  public SqlNode findAgg(List<SqlNode> nodes) {
+  public SqlCall findAgg(List<SqlNode> nodes) {
     try {
       for (SqlNode node : nodes) {
         node.accept(this);
@@ -93,7 +98,7 @@ class AggFinder extends SqlBasicVisitor<Void> {
       return null;
     } catch (Util.FoundOne e) {
       Util.swallow(e, null);
-      return (SqlNode) e.getNode();
+      return (SqlCall) e.getNode();
     }
   }
 
@@ -108,6 +113,9 @@ class AggFinder extends SqlBasicVisitor<Void> {
         throw new Util.FoundOne(call);
       }
     }
+    if (group && operator.isGroup()) {
+      throw new Util.FoundOne(call);
+    }
     // User-defined function may not be resolved yet.
     if (operator instanceof SqlFunction) {
       final SqlFunction sqlFunction = (SqlFunction) operator;

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java b/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
index 29514ac..656f8d6 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/AggregatingSelectScope.java
@@ -25,6 +25,7 @@ import org.apache.calcite.sql.SqlNodeList;
 import org.apache.calcite.sql.SqlSelect;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.Litmus;
+import org.apache.calcite.util.Pair;
 
 import com.google.common.base.Supplier;
 import com.google.common.base.Suppliers;
@@ -33,7 +34,6 @@ import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Sets;
 
 import java.util.ArrayList;
-import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -95,18 +95,20 @@ public class AggregatingSelectScope
   //~ Methods ----------------------------------------------------------------
 
   private Resolved resolve() {
-    final Map<Integer, Integer> groupExprProjection = new HashMap<>();
     final ImmutableList.Builder<ImmutableList<ImmutableBitSet>> builder =
         ImmutableList.builder();
+    List<SqlNode> extraExprs = ImmutableList.of();
+    Map<Integer, Integer> groupExprProjection = ImmutableMap.of();
     if (select.getGroup() != null) {
-      // We deep-copy the group-list in case subsequent validation
-      // modifies it and makes it no longer equivalent. While copying,
-      // we fully qualify all identifiers.
       final SqlNodeList groupList = select.getGroup();
+      final SqlValidatorUtil.GroupAnalyzer groupAnalyzer =
+          new SqlValidatorUtil.GroupAnalyzer(temporaryGroupExprList);
       for (SqlNode groupExpr : groupList) {
-        SqlValidatorUtil.analyzeGroupItem(this, temporaryGroupExprList,
-            groupExprProjection, builder, groupExpr);
+        SqlValidatorUtil.analyzeGroupItem(this, groupAnalyzer, builder,
+            groupExpr);
       }
+      extraExprs = groupAnalyzer.extraExprs;
+      groupExprProjection = groupAnalyzer.groupExprProjection;
     }
 
     final Set<ImmutableBitSet> flatGroupSets =
@@ -120,7 +122,7 @@ public class AggregatingSelectScope
       flatGroupSets.add(ImmutableBitSet.of());
     }
 
-    return new Resolved(temporaryGroupExprList, flatGroupSets,
+    return new Resolved(extraExprs, temporaryGroupExprList, flatGroupSets,
         groupExprProjection);
   }
 
@@ -134,7 +136,7 @@ public class AggregatingSelectScope
    *
    * @return list of grouping expressions
    */
-  private ImmutableList<SqlNode> getGroupExprs() {
+  private Pair<ImmutableList<SqlNode>, ImmutableList<SqlNode>> getGroupExprs() {
     if (distinct) {
       // Cannot compute this in the constructor: select list has not been
       // expanded yet.
@@ -147,16 +149,18 @@ public class AggregatingSelectScope
       for (SqlNode selectItem : selectScope.getExpandedSelectList()) {
         groupExprs.add(stripAs(selectItem));
       }
-      return groupExprs.build();
+      return Pair.of(ImmutableList.<SqlNode>of(), groupExprs.build());
     } else if (select.getGroup() != null) {
       if (temporaryGroupExprList != null) {
         // we are in the middle of resolving
-        return ImmutableList.copyOf(temporaryGroupExprList);
+        return Pair.of(ImmutableList.<SqlNode>of(),
+            ImmutableList.copyOf(temporaryGroupExprList));
       } else {
-        return resolved.get().groupExprList;
+        final Resolved resolved = this.resolved.get();
+        return Pair.of(resolved.extraExprList, resolved.groupExprList);
       }
     } else {
-      return ImmutableList.of();
+      return Pair.of(ImmutableList.<SqlNode>of(), ImmutableList.<SqlNode>of());
     }
   }
 
@@ -220,13 +224,9 @@ public class AggregatingSelectScope
     }
 
     // Make sure expression is valid, throws if not.
-    List<SqlNode> groupExprs = getGroupExprs();
+    Pair<ImmutableList<SqlNode>, ImmutableList<SqlNode>> pair = getGroupExprs();
     final AggChecker aggChecker =
-        new AggChecker(
-            validator,
-            this,
-            groupExprs,
-            distinct);
+        new AggChecker(validator, this, pair.left, pair.right, distinct);
     if (deep) {
       expr.accept(aggChecker);
     }
@@ -244,14 +244,17 @@ public class AggregatingSelectScope
    * after validation has occurred. Therefore it cannot be populated when
    * the scope is created. */
   public class Resolved {
+    public final ImmutableList<SqlNode> extraExprList;
     public final ImmutableList<SqlNode> groupExprList;
     public final ImmutableBitSet groupSet;
     public final ImmutableList<ImmutableBitSet> groupSets;
     public final boolean indicator;
     public final Map<Integer, Integer> groupExprProjection;
 
-    Resolved(List<SqlNode> groupExprList, Iterable<ImmutableBitSet> groupSets,
+    Resolved(List<SqlNode> extraExprList, List<SqlNode> groupExprList,
+        Iterable<ImmutableBitSet> groupSets,
         Map<Integer, Integer> groupExprProjection) {
+      this.extraExprList = ImmutableList.copyOf(extraExprList);
       this.groupExprList = ImmutableList.copyOf(groupExprList);
       this.groupSet = ImmutableBitSet.range(groupExprList.size());
       this.groupSets = ImmutableList.copyOf(groupSets);

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
index 0d0a608..f4a6631 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorImpl.java
@@ -229,6 +229,8 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       new IdentityHashMap<>();
   private final AggFinder aggFinder;
   private final AggFinder aggOrOverFinder;
+  private final AggFinder aggOrOverOrGroupFinder;
+  private final AggFinder groupFinder;
   private final AggFinder overFinder;
   private final SqlConformance conformance;
   private final Map<SqlNode, SqlNode> originalExprs = new HashMap<>();
@@ -280,9 +282,11 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
 
     rewriteCalls = true;
     expandColumnReferences = true;
-    aggFinder = new AggFinder(opTab, false, true, null);
-    aggOrOverFinder = new AggFinder(opTab, true, true, null);
-    overFinder = new AggFinder(opTab, true, false, aggOrOverFinder);
+    aggFinder = new AggFinder(opTab, false, true, false, null);
+    aggOrOverFinder = new AggFinder(opTab, true, true, false, null);
+    overFinder = new AggFinder(opTab, true, false, false, aggOrOverFinder);
+    groupFinder = new AggFinder(opTab, false, false, true, null);
+    aggOrOverOrGroupFinder = new AggFinder(opTab, true, true, true, null);
   }
 
   //~ Methods ----------------------------------------------------------------
@@ -2574,7 +2578,8 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
   }
 
   protected boolean isNestedAggregateWindow(SqlCall windowFunction) {
-    AggFinder nestedAggFinder = new AggFinder(opTab, false, false, aggFinder);
+    AggFinder nestedAggFinder =
+        new AggFinder(opTab, false, false, false, aggFinder);
     return nestedAggFinder.findAgg(windowFunction) != null;
   }
 
@@ -2976,19 +2981,26 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
    * Throws an error if there is an aggregate or windowed aggregate in the
    * given clause.
    *
-   * @param condition Parse tree
+   * @param aggFinder Finder for the particular kind(s) of aggregate function
+   * @param node      Parse tree
    * @param clause    Name of clause: "WHERE", "GROUP BY", "ON"
    */
-  private void validateNoAggs(SqlNode condition, String clause) {
-    final SqlNode agg = aggOrOverFinder.findAgg(condition);
-    if (agg != null) {
-      if (SqlUtil.isCallTo(agg, SqlStdOperatorTable.OVER)) {
-        throw newValidationError(agg,
-            RESOURCE.windowedAggregateIllegalInClause(clause));
-      } else {
-        throw newValidationError(agg,
-            RESOURCE.aggregateIllegalInClause(clause));
-      }
+  private void validateNoAggs(AggFinder aggFinder, SqlNode node,
+                              String clause) {
+    final SqlCall agg = aggFinder.findAgg(node);
+    if (agg == null) {
+      return;
+    }
+    final SqlOperator op = agg.getOperator();
+    if (op == SqlStdOperatorTable.OVER) {
+      throw newValidationError(agg,
+          RESOURCE.windowedAggregateIllegalInClause(clause));
+    } else if (op.isGroup() || op.isGroupAuxiliary()) {
+      throw newValidationError(agg,
+          RESOURCE.groupFunctionMustAppearInGroupByClause(op.getName()));
+    } else {
+      throw newValidationError(agg,
+          RESOURCE.aggregateIllegalInClause(clause));
     }
   }
 
@@ -3432,7 +3444,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     if (groupList == null) {
       return;
     }
-    validateNoAggs(groupList, "GROUP BY");
+    validateNoAggs(aggOrOverFinder, groupList, "GROUP BY");
     final SqlValidatorScope groupScope = getGroupScope(select);
     inferUnknownTypes(unknownType, groupScope, groupList);
 
@@ -3523,7 +3535,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
       SqlValidatorScope scope,
       SqlNode condition,
       String keyword) {
-    validateNoAggs(condition, keyword);
+    validateNoAggs(aggOrOverOrGroupFinder, condition, keyword);
     inferUnknownTypes(
         booleanType,
         scope,
@@ -3612,6 +3624,7 @@ public class SqlValidatorImpl implements SqlValidatorWithHints {
     inferUnknownTypes(targetRowType, selectScope, newSelectList);
 
     for (SqlNode selectItem : expandedSelectItems) {
+      validateNoAggs(groupFinder, selectItem, "SELECT");
       validateExpr(selectItem, selectScope);
     }
 

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
index 34149f9..315c41f 100644
--- a/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
+++ b/core/src/main/java/org/apache/calcite/sql/validate/SqlValidatorUtil.java
@@ -54,6 +54,7 @@ import java.nio.charset.Charset;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
+import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.List;
@@ -563,13 +564,13 @@ public class SqlValidatorUtil {
   /** Analyzes an expression in a GROUP BY clause.
    *
    * <p>It may be an expression, an empty list (), or a call to
-   * {@code GROUPING SETS}, {@code CUBE} or {@code ROLLUP}.
+   * {@code GROUPING SETS}, {@code CUBE}, {@code ROLLUP} or {@code TUMBLE}.
    *
    * <p>Each group item produces a list of group sets, which are written to
    * {@code topBuilder}. To find the grouping sets of the query, we will take
    * the cartesian product of the group sets. */
   public static void analyzeGroupItem(SqlValidatorScope scope,
-      List<SqlNode> groupExprs, Map<Integer, Integer> groupExprProjection,
+                                      GroupAnalyzer groupAnalyzer,
       ImmutableList.Builder<ImmutableList<ImmutableBitSet>> topBuilder,
       SqlNode groupExpr) {
     final ImmutableList.Builder<ImmutableBitSet> builder;
@@ -579,8 +580,8 @@ public class SqlValidatorUtil {
       // E.g. ROLLUP(a, (b, c)) becomes [{0}, {1, 2}]
       // then we roll up to [(0, 1, 2), (0), ()]  -- note no (0, 1)
       List<ImmutableBitSet> bitSets =
-          analyzeGroupTuple(scope, groupExprs,
-              groupExprProjection, ((SqlCall) groupExpr).getOperandList());
+          analyzeGroupTuple(scope, groupAnalyzer,
+              ((SqlCall) groupExpr).getOperandList());
       switch (groupExpr.getKind()) {
       case ROLLUP:
         topBuilder.add(rollup(bitSets));
@@ -593,16 +594,17 @@ public class SqlValidatorUtil {
       if (groupExpr instanceof SqlNodeList) {
         SqlNodeList list = (SqlNodeList) groupExpr;
         for (SqlNode node : list) {
-          analyzeGroupItem(scope, groupExprs, groupExprProjection, topBuilder,
+          analyzeGroupItem(scope, groupAnalyzer, topBuilder,
               node);
         }
         return;
       }
       // fall through
+    case TUMBLE:
     case GROUPING_SETS:
     default:
       builder = ImmutableList.builder();
-      convertGroupSet(scope, groupExprs, groupExprProjection, builder,
+      convertGroupSet(scope, groupAnalyzer, builder,
           groupExpr);
       topBuilder.add(builder.build());
     }
@@ -610,24 +612,24 @@ public class SqlValidatorUtil {
 
   /** Analyzes a GROUPING SETS item in a GROUP BY clause. */
   private static void convertGroupSet(SqlValidatorScope scope,
-      List<SqlNode> groupExprs, Map<Integer, Integer> groupExprProjection,
+      GroupAnalyzer groupAnalyzer,
       ImmutableList.Builder<ImmutableBitSet> builder, SqlNode groupExpr) {
     switch (groupExpr.getKind()) {
     case GROUPING_SETS:
       final SqlCall call = (SqlCall) groupExpr;
       for (SqlNode node : call.getOperandList()) {
-        convertGroupSet(scope, groupExprs, groupExprProjection, builder, node);
+        convertGroupSet(scope, groupAnalyzer, builder, node);
       }
       return;
     case ROW:
       final List<ImmutableBitSet> bitSets =
-          analyzeGroupTuple(scope, groupExprs, groupExprProjection,
+          analyzeGroupTuple(scope, groupAnalyzer,
               ((SqlCall) groupExpr).getOperandList());
       builder.add(ImmutableBitSet.union(bitSets));
       return;
     default:
       builder.add(
-          analyzeGroupExpr(scope, groupExprs, groupExprProjection, groupExpr));
+          analyzeGroupExpr(scope, groupAnalyzer, groupExpr));
       return;
     }
   }
@@ -641,19 +643,19 @@ public class SqlValidatorUtil {
    * grouped, and returns a bitmap indicating which expressions this tuple
    * is grouping. */
   private static List<ImmutableBitSet>
-  analyzeGroupTuple(SqlValidatorScope scope, List<SqlNode> groupExprs,
-      Map<Integer, Integer> groupExprProjection, List<SqlNode> operandList) {
+  analyzeGroupTuple(SqlValidatorScope scope, GroupAnalyzer groupAnalyzer,
+                    List<SqlNode> operandList) {
     List<ImmutableBitSet> list = Lists.newArrayList();
     for (SqlNode operand : operandList) {
       list.add(
-          analyzeGroupExpr(scope, groupExprs, groupExprProjection, operand));
+          analyzeGroupExpr(scope, groupAnalyzer, operand));
     }
     return list;
   }
 
   /** Analyzes a component of a tuple in a GROUPING SETS clause. */
   private static ImmutableBitSet analyzeGroupExpr(SqlValidatorScope scope,
-      List<SqlNode> groupExprs, Map<Integer, Integer> groupExprProjection,
+      GroupAnalyzer groupAnalyzer,
       SqlNode groupExpr) {
     final SqlNode expandedGroupExpr =
         scope.getValidator().expand(groupExpr, scope);
@@ -661,7 +663,7 @@ public class SqlValidatorUtil {
     switch (expandedGroupExpr.getKind()) {
     case ROW:
       return ImmutableBitSet.union(
-          analyzeGroupTuple(scope, groupExprs, groupExprProjection,
+          analyzeGroupTuple(scope, groupAnalyzer,
               ((SqlCall) expandedGroupExpr).getOperandList()));
     case OTHER:
       if (expandedGroupExpr instanceof SqlNodeList
@@ -670,7 +672,7 @@ public class SqlValidatorUtil {
       }
     }
 
-    final int ref = lookupGroupExpr(groupExprs, groupExpr);
+    final int ref = lookupGroupExpr(groupAnalyzer, groupExpr);
     if (expandedGroupExpr instanceof SqlIdentifier) {
       // SQL 2003 does not allow expressions of column references
       SqlIdentifier expr = (SqlIdentifier) expandedGroupExpr;
@@ -711,20 +713,27 @@ public class SqlValidatorUtil {
       RelDataTypeField field = nameMatcher.field(rowType, originalFieldName);
       int origPos = namespaceOffset + field.getIndex();
 
-      groupExprProjection.put(origPos, ref);
+      groupAnalyzer.groupExprProjection.put(origPos, ref);
     }
 
     return ImmutableBitSet.of(ref);
   }
 
-  private static int lookupGroupExpr(List<SqlNode> groupExprs, SqlNode expr) {
-    for (Ord<SqlNode> node : Ord.zip(groupExprs)) {
+  private static int lookupGroupExpr(GroupAnalyzer groupAnalyzer,
+      SqlNode expr) {
+    for (Ord<SqlNode> node : Ord.zip(groupAnalyzer.groupExprs)) {
       if (node.e.equalsDeep(expr, Litmus.IGNORE)) {
         return node.i;
       }
     }
-    groupExprs.add(expr);
-    return groupExprs.size() - 1;
+
+    switch (expr.getKind()) {
+    case TUMBLE:
+      groupAnalyzer.extraExprs.add(expr);
+      break;
+    }
+    groupAnalyzer.groupExprs.add(expr);
+    return groupAnalyzer.groupExprs.size() - 1;
   }
 
   /** Computes the rollup of bit sets.
@@ -895,6 +904,26 @@ public class SqlValidatorUtil {
           return Util.first(original, "$f") + Math.max(size, attempt);
         }
       };
+
+  /** Builds a list of GROUP BY expressions. */
+  static class GroupAnalyzer {
+    /** Extra expressions, computed from the input as extra GROUP BY
+     * expressions. For example, calls to the {@code TUMBLE} functions. */
+    final List<SqlNode> extraExprs = new ArrayList<>();
+    final List<SqlNode> groupExprs;
+    final Map<Integer, Integer> groupExprProjection = new HashMap<>();
+    int groupCount;
+
+    GroupAnalyzer(List<SqlNode> groupExprs) {
+      this.groupExprs = groupExprs;
+    }
+
+    SqlNode createGroupExpr() {
+      // TODO: create an expression that could have no other source
+      return SqlLiteral.createCharString("xyz" + groupCount++,
+          SqlParserPos.ZERO);
+    }
+  }
 }
 
 // End SqlValidatorUtil.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
----------------------------------------------------------------------
diff --git a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
index b6df686..eca1456 100644
--- a/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
+++ b/core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
@@ -2528,17 +2528,14 @@ public class SqlToRelConverter {
       }
 
       // compute inputs to the aggregator
-      List<RexNode> preExprs = aggConverter.getPreExprs();
-      List<String> preNames = aggConverter.getPreNames();
+      List<Pair<RexNode, String>> preExprs = aggConverter.getPreExprs();
 
       if (preExprs.size() == 0) {
         // Special case for COUNT(*), where we can end up with no inputs
         // at all.  The rest of the system doesn't like 0-tuples, so we
         // select a dummy constant here.
-        preExprs =
-            ImmutableList.<RexNode>of(
-                rexBuilder.makeExactLiteral(BigDecimal.ZERO));
-        preNames = Collections.singletonList(null);
+        final RexNode zero = rexBuilder.makeExactLiteral(BigDecimal.ZERO);
+        preExprs = ImmutableList.of(Pair.of(zero, (String) null));
       }
 
       final RelNode inputRel = bb.root;
@@ -2548,7 +2545,6 @@ public class SqlToRelConverter {
           RelOptUtil.createProject(
               inputRel,
               preExprs,
-              preNames,
               true),
           false);
       bb.mapRootRelToFieldProjection.put(bb.root, r.groupExprProjection);
@@ -4417,20 +4413,21 @@ public class SqlToRelConverter {
      * Input expressions for the group columns and aggregates, in
      * {@link RexNode} format. The first elements of the list correspond to the
      * elements in {@link #groupExprs}; the remaining elements are for
-     * aggregates.
+     * aggregates. The right field of each pair is the name of the expression,
+     * where the expressions are simple mappings to input fields.
      */
-    private final List<RexNode> convertedInputExprs = Lists.newArrayList();
+    private final List<Pair<RexNode, String>> convertedInputExprs =
+        new ArrayList<>();
 
-    /**
-     * Names of {@link #convertedInputExprs}, where the expressions are
-     * simple mappings to input fields.
-     */
-    private final List<String> convertedInputExprNames = Lists.newArrayList();
+    /** Expressions to be evaluated as rows are being placed into the
+     * aggregate's hash table. This is when group functions such as TUMBLE
+     * cause rows to be expanded. */
+    private final List<RexNode> midExprs = new ArrayList<>();
 
-    private final List<AggregateCall> aggCalls = Lists.newArrayList();
-    private final Map<SqlNode, RexNode> aggMapping = Maps.newHashMap();
+    private final List<AggregateCall> aggCalls = new ArrayList<>();
+    private final Map<SqlNode, RexNode> aggMapping = new HashMap<>();
     private final Map<AggregateCall, RexNode> aggCallMapping =
-        Maps.newHashMap();
+        new HashMap<>();
 
     /** Are we directly inside a windowed aggregate? */
     private boolean inOver = false;
@@ -4470,7 +4467,6 @@ public class SqlToRelConverter {
     }
 
     public int addGroupExpr(SqlNode expr) {
-      RexNode convExpr = bb.convertExpression(expr);
       int ref = lookupGroupExpr(expr);
       if (ref >= 0) {
         return ref;
@@ -4478,6 +4474,7 @@ public class SqlToRelConverter {
       final int index = groupExprs.size();
       groupExprs.add(expr);
       String name = nameMap.get(expr.toString());
+      RexNode convExpr = bb.convertExpression(expr);
       addExpr(convExpr, name);
       return index;
     }
@@ -4489,17 +4486,16 @@ public class SqlToRelConverter {
      * @param name Suggested name
      */
     private void addExpr(RexNode expr, String name) {
-      convertedInputExprs.add(expr);
       if ((name == null) && (expr instanceof RexInputRef)) {
         final int i = ((RexInputRef) expr).getIndex();
         name = bb.root.getRowType().getFieldList().get(i).getName();
       }
-      if (convertedInputExprNames.contains(name)) {
+      if (Pair.right(convertedInputExprs).contains(name)) {
         // In case like 'SELECT ... GROUP BY x, y, x', don't add
         // name 'x' twice.
         name = null;
       }
-      convertedInputExprNames.add(name);
+      convertedInputExprs.add(Pair.of(expr, name));
     }
 
     public Void visit(SqlIdentifier id) {
@@ -4645,15 +4641,15 @@ public class SqlToRelConverter {
     }
 
     private int lookupOrCreateGroupExpr(RexNode expr) {
-      for (int i = 0; i < convertedInputExprs.size(); i++) {
-        RexNode convertedInputExpr = convertedInputExprs.get(i);
+      int index = 0;
+      for (RexNode convertedInputExpr : Pair.left(convertedInputExprs)) {
         if (expr.toString().equals(convertedInputExpr.toString())) {
-          return i;
+          return index;
         }
+        ++index;
       }
 
       // not found -- add it
-      int index = convertedInputExprs.size();
       addExpr(expr, null);
       return index;
     }
@@ -4741,14 +4737,10 @@ public class SqlToRelConverter {
       return node;
     }
 
-    public List<RexNode> getPreExprs() {
+    public List<Pair<RexNode, String>> getPreExprs() {
       return convertedInputExprs;
     }
 
-    public List<String> getPreNames() {
-      return convertedInputExprNames;
-    }
-
     public List<AggregateCall> getAggCalls() {
       return aggCalls;
     }

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
----------------------------------------------------------------------
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 6993cbe..153889b 100644
--- a/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
+++ b/core/src/main/java/org/apache/calcite/tools/RelBuilder.java
@@ -64,7 +64,6 @@ import org.apache.calcite.util.ImmutableIntList;
 import org.apache.calcite.util.Litmus;
 import org.apache.calcite.util.NlsString;
 import org.apache.calcite.util.Pair;
-import org.apache.calcite.util.Static;
 import org.apache.calcite.util.Util;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
@@ -91,6 +90,8 @@ import java.util.Set;
 import java.util.SortedSet;
 import java.util.TreeSet;
 
+import static org.apache.calcite.util.Static.RESOURCE;
+
 /**
  * Builder for relational expressions.
  *
@@ -700,7 +701,7 @@ public class RelBuilder {
       RexNode filter, String alias, Iterable<? extends RexNode> operands) {
     if (filter != null) {
       if (filter.getType().getSqlTypeName() != SqlTypeName.BOOLEAN) {
-        throw Static.RESOURCE.filterMustBeBoolean().ex();
+        throw RESOURCE.filterMustBeBoolean().ex();
       }
       if (filter.getType().isNullable()) {
         filter = call(SqlStdOperatorTable.IS_TRUE, filter);
@@ -758,7 +759,7 @@ public class RelBuilder {
     final List<String> names = ImmutableList.copyOf(tableNames);
     final RelOptTable relOptTable = relOptSchema.getTableForMember(names);
     if (relOptTable == null) {
-      throw Static.RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex();
+      throw RESOURCE.tableNotFound(Joiner.on(".").join(names)).ex();
     }
     final RelNode scan = scanFactory.createScan(cluster, relOptTable);
     push(scan);

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
----------------------------------------------------------------------
diff --git a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
index 7be1266..83aeb7f 100644
--- a/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
+++ b/core/src/main/resources/org/apache/calcite/runtime/CalciteResource.properties
@@ -212,4 +212,6 @@ FilterMustBeBoolean=FILTER expression must be of type BOOLEAN
 CannotStreamResultsForNonStreamingInputs=Cannot stream results of a query with no streaming inputs: ''{0}''. At least one input should be convertible to a stream
 MinusNotAllowed=MINUS is not allowed under the current SQL conformance level
 SelectMissingFrom=SELECT must have a FROM clause
+GroupFunctionMustAppearInGroupByClause=Group function ''{0}'' can only appear in GROUP BY clause
+AuxiliaryWithoutMatchingGroupCall=Call to auxiliary group function ''{0}'' must have matching call to group function ''{1}'' in GROUP BY clause
 # End CalciteResource.properties

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
----------------------------------------------------------------------
diff --git a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
index 6c7ccd7..65e760f 100644
--- a/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
+++ b/core/src/test/java/org/apache/calcite/test/SqlValidatorTest.java
@@ -8576,6 +8576,53 @@ public class SqlValidatorTest extends SqlValidatorTestCase {
         + "  from \"DYNAMIC\".NATION, \"DYNAMIC\".CUSTOMER)";
     sql(sql).type("RecordType(ANY NEWID) NOT NULL");
   }
+
+  @Test public void testStreamTumble() {
+    // TUMBLE
+    sql("select stream tumble_end(rowtime, interval '2' hour) as rowtime\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour), productId").ok();
+    sql("select stream ^tumble(rowtime, interval '2' hour)^ as rowtime\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour), productId")
+        .fails("Group function 'TUMBLE' can only appear in GROUP BY clause");
+    // TUMBLE with align argument
+    sql("select stream\n"
+        + "  tumble_end(rowtime, interval '2' hour, time '00:12:00') as rowtime\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour, time '00:12:00')").ok();
+    // TUMBLE_END without corresponding TUMBLE
+    sql("select stream\n"
+        + "  ^tumble_end(rowtime, interval '2' hour, time '00:13:00')^ as rowtime\n"
+        + "from orders\n"
+        + "group by floor(rowtime to hour)")
+        .fails("Call to auxiliary group function 'TUMBLE_END' must have "
+            + "matching call to group function 'TUMBLE' in GROUP BY clause");
+    // Arguments to TUMBLE_END are slightly different to arguments to TUMBLE
+    sql("select stream\n"
+        + "  ^tumble_start(rowtime, interval '2' hour, time '00:13:00')^ as rowtime\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour, time '00:12:00')")
+        .fails("Call to auxiliary group function 'TUMBLE_START' must have "
+            + "matching call to group function 'TUMBLE' in GROUP BY clause");
+    // Even though align defaults to TIME '00:00:00', we need structural
+    // equivalence, not semantic equivalence.
+    sql("select stream\n"
+        + "  ^tumble_end(rowtime, interval '2' hour, time '00:00:00')^ as rowtime\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour)")
+        .fails("Call to auxiliary group function 'TUMBLE_END' must have "
+            + "matching call to group function 'TUMBLE' in GROUP BY clause");
+    // TUMBLE query produces no monotonic column - OK
+    sql("select stream productId\n"
+        + "from orders\n"
+        + "group by tumble(rowtime, interval '2' hour), productId").ok();
+    sql("select stream productId\n"
+        + "from orders\n"
+        + "^group by productId,\n"
+        + "  tumble(timestamp '1990-03-04 12:34:56', interval '2' hour)^")
+        .fails(STR_AGG_REQUIRES_MONO);
+  }
 }
 
 // End SqlValidatorTest.java

http://git-wip-us.apache.org/repos/asf/calcite/blob/bc232c26/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
----------------------------------------------------------------------
diff --git a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
index 10c1650..5da57fd 100644
--- a/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
+++ b/core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
@@ -2399,6 +2399,22 @@ LogicalDelta
 ]]>
         </Resource>
     </TestCase>
+    <TestCase name="testTumbleTable">
+        <Resource name="sql">
+            <![CDATA[select stream tumble_end(rowtime, interval '2' hour) as rowtime, productId
+from orders
+group by tumble(rowtime, interval '2' hour), productId]]>
+        </Resource>
+        <Resource name="plan">
+            <![CDATA[
+LogicalDelta
+  LogicalProject(ROWTIME=[TUMBLE_END($0, 7200000)], PRODUCTID=[$1])
+    LogicalAggregate(group=[{0, 1}])
+      LogicalProject($f0=[TUMBLE($0, 7200000)], PRODUCTID=[$2])
+        LogicalTableScan(table=[[STREAMS, ORDERS]])
+]]>
+        </Resource>
+    </TestCase>
     <TestCase name="testGroupByCaseIn">
         <Resource name="sql">
             <![CDATA[select