You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by jc...@apache.org on 2017/10/16 23:48:48 UTC

[4/4] hive git commit: HIVE-17672: Upgrade Calcite version to 1.14 (Jesus Camacho Rodriguez, reviewed by Ashutosh Chauhan)

HIVE-17672: Upgrade Calcite version to 1.14 (Jesus Camacho Rodriguez, reviewed by Ashutosh Chauhan)


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

Branch: refs/heads/master
Commit: 9975131cce0b6af71f3ae77e20de294adc1b3466
Parents: 45b9b8d
Author: Jesus Camacho Rodriguez <jc...@apache.org>
Authored: Tue Oct 3 16:08:46 2017 -0700
Committer: Jesus Camacho Rodriguez <jc...@apache.org>
Committed: Mon Oct 16 16:48:37 2017 -0700

----------------------------------------------------------------------
 .../hadoop/hive/druid/io/DruidOutputFormat.java |  12 +-
 .../hadoop/hive/druid/serde/DruidSerDe.java     |  34 ++-
 .../hive/druid/serde/DruidSerDeUtils.java       |   2 +-
 .../hadoop/hive/druid/serde/TestDruidSerDe.java |  87 ++++---
 pom.xml                                         |   2 +-
 .../hadoop/hive/ql/exec/FunctionRegistry.java   |   2 +
 .../apache/hadoop/hive/ql/metadata/Hive.java    |   2 +-
 .../metadata/HiveMaterializedViewsRegistry.java |   8 +-
 ...tedDynPartitionTimeGranularityOptimizer.java |  46 +++-
 .../ql/optimizer/calcite/HiveCalciteUtil.java   |   2 +-
 .../calcite/HiveConfPlannerContext.java         |   4 -
 .../ql/optimizer/calcite/HiveRelFactories.java  |   8 +-
 .../hive/ql/optimizer/calcite/HiveType.java     |  48 ----
 .../optimizer/calcite/HiveTypeSystemImpl.java   |   4 +
 .../functions/HiveSqlCountAggFunction.java      |  46 +++-
 .../HiveSqlSumEmptyIsZeroAggFunction.java       |  59 +++++
 .../calcite/reloperators/HiveAggregate.java     |  16 +-
 .../calcite/reloperators/HiveGroupingID.java    |   8 +-
 .../rules/HiveAggregateJoinTransposeRule.java   | 120 ++++-----
 .../rules/HiveAggregateProjectMergeRule.java    |  31 +--
 .../calcite/rules/HiveExceptRewriteRule.java    |  16 +-
 .../rules/HiveExpandDistinctAggregatesRule.java |   4 +-
 .../calcite/rules/HiveIntersectRewriteRule.java |  16 +-
 .../calcite/rules/HiveRelColumnsAlignment.java  |   3 +-
 .../calcite/rules/HiveRelDecorrelator.java      |  41 ++-
 .../calcite/translator/ASTBuilder.java          |   7 +
 .../calcite/translator/ASTConverter.java        |  41 ++-
 .../calcite/translator/ExprNodeConverter.java   |  35 ++-
 .../calcite/translator/HiveGBOpConvUtil.java    |   3 +-
 .../calcite/translator/HiveOpConverter.java     |  15 +-
 .../calcite/translator/RexNodeConverter.java    |  18 +-
 .../translator/SqlFunctionConverter.java        |   5 +-
 .../calcite/translator/TypeConverter.java       |  32 +--
 .../hadoop/hive/ql/parse/CalcitePlanner.java    |  35 +--
 .../apache/hadoop/hive/ql/parse/HiveParser.g    |   1 +
 .../hadoop/hive/ql/parse/IdentifiersParser.g    |   9 +
 .../hive/ql/parse/TypeCheckProcFactory.java     |  15 +-
 .../apache/hadoop/hive/ql/udf/UDFDateFloor.java |  31 ++-
 .../ql/udf/generic/GenericUDFEpochMilli.java    |  62 +++++
 .../ql/udf/TestUDFDateFormatGranularity.java    |  78 ++++++
 .../queries/clientpositive/druid_timeseries.q   |   8 +-
 ql/src/test/queries/clientpositive/druid_topn.q |   4 +-
 .../test/queries/clientpositive/timestamptz_3.q |  15 ++
 .../cbo_rp_annotate_stats_groupby.q.out         | 256 +++++++------------
 .../results/clientpositive/druid_basic1.q.out   |   4 +-
 .../results/clientpositive/druid_basic2.q.out   | 106 ++++----
 .../clientpositive/druid_intervals.q.out        |  42 +--
 .../clientpositive/druid_timeseries.q.out       |  68 ++---
 .../results/clientpositive/druid_topn.q.out     |  56 ++--
 .../clientpositive/groupby_grouping_sets1.q.out |  46 ++--
 .../groupby_grouping_sets_limit.q.out           |  50 ++--
 .../llap/vector_groupby_grouping_id2.q.out      |  12 +-
 .../llap/vector_groupby_grouping_sets1.q.out    |  46 ++--
 .../vector_groupby_grouping_sets_limit.q.out    |  44 ++--
 .../clientpositive/perf/spark/query36.q.out     |  20 +-
 .../clientpositive/perf/spark/query67.q.out     |  14 +-
 .../clientpositive/perf/spark/query70.q.out     |  20 +-
 .../clientpositive/perf/spark/query86.q.out     |  20 +-
 .../clientpositive/perf/tez/query14.q.out       |   2 +-
 .../clientpositive/perf/tez/query22.q.out       |  22 +-
 .../clientpositive/perf/tez/query36.q.out       |   8 +-
 .../clientpositive/perf/tez/query67.q.out       |   6 +-
 .../clientpositive/perf/tez/query70.q.out       |   8 +-
 .../clientpositive/perf/tez/query86.q.out       |   8 +-
 .../results/clientpositive/show_functions.q.out |   1 +
 .../results/clientpositive/timestamptz_3.q.out  |  57 +++++
 66 files changed, 1113 insertions(+), 838 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/druid-handler/src/java/org/apache/hadoop/hive/druid/io/DruidOutputFormat.java
----------------------------------------------------------------------
diff --git a/druid-handler/src/java/org/apache/hadoop/hive/druid/io/DruidOutputFormat.java b/druid-handler/src/java/org/apache/hadoop/hive/druid/io/DruidOutputFormat.java
index 664e02f..0888ff2 100644
--- a/druid-handler/src/java/org/apache/hadoop/hive/druid/io/DruidOutputFormat.java
+++ b/druid-handler/src/java/org/apache/hadoop/hive/druid/io/DruidOutputFormat.java
@@ -149,13 +149,21 @@ public class DruidOutputFormat<K, V> implements HiveOutputFormat<K, DruidWritabl
           af = new DoubleSumAggregatorFactory(columnNames.get(i), columnNames.get(i));
           break;
         case TIMESTAMP:
+          // Granularity column
           String tColumnName = columnNames.get(i);
-          if (!tColumnName.equals(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN) && !tColumnName
-                  .equals(Constants.DRUID_TIMESTAMP_GRANULARITY_COL_NAME)) {
+          if (!tColumnName.equals(Constants.DRUID_TIMESTAMP_GRANULARITY_COL_NAME)) {
             throw new IOException("Dimension " + tColumnName + " does not have STRING type: " +
                     primitiveCategory);
           }
           continue;
+        case TIMESTAMPLOCALTZ:
+          // Druid timestamp column
+          String tLocalTZColumnName = columnNames.get(i);
+          if (!tLocalTZColumnName.equals(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN)) {
+            throw new IOException("Dimension " + tLocalTZColumnName + " does not have STRING type: " +
+                    primitiveCategory);
+          }
+          continue;
         default:
           // Dimension
           String dColumnName = columnNames.get(i);

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDe.java
----------------------------------------------------------------------
diff --git a/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDe.java b/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDe.java
index a43f62e..4a7952e 100644
--- a/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDe.java
+++ b/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDe.java
@@ -19,7 +19,8 @@ package org.apache.hadoop.hive.druid.serde;
 
 import java.io.IOException;
 import java.io.InputStream;
-import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.ZonedDateTime;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
@@ -31,6 +32,7 @@ import org.apache.hadoop.conf.Configuration;
 import org.apache.hadoop.hive.common.type.HiveChar;
 import org.apache.hadoop.hive.common.type.HiveDecimal;
 import org.apache.hadoop.hive.common.type.HiveVarchar;
+import org.apache.hadoop.hive.common.type.TimestampTZ;
 import org.apache.hadoop.hive.conf.Constants;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.druid.DruidStorageHandler;
@@ -47,7 +49,7 @@ import org.apache.hadoop.hive.serde2.io.HiveCharWritable;
 import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
 import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable;
 import org.apache.hadoop.hive.serde2.io.ShortWritable;
-import org.apache.hadoop.hive.serde2.io.TimestampWritable;
+import org.apache.hadoop.hive.serde2.io.TimestampLocalTZWritable;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
 import org.apache.hadoop.hive.serde2.objectinspector.StructField;
@@ -64,9 +66,11 @@ import org.apache.hadoop.hive.serde2.objectinspector.primitive.LongObjectInspect
 import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
 import org.apache.hadoop.hive.serde2.objectinspector.primitive.ShortObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.primitive.StringObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampLocalTZObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.primitive.TimestampObjectInspector;
 import org.apache.hadoop.hive.serde2.typeinfo.CharTypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TimestampLocalTZTypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
 import org.apache.hadoop.hive.serde2.typeinfo.VarcharTypeInfo;
 import org.apache.hadoop.io.BooleanWritable;
@@ -175,7 +179,7 @@ public class DruidSerDe extends AbstractSerDe {
           if (columnInfo.getKey().equals(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN)) {
             // Special handling for timestamp column
             columnNames.add(columnInfo.getKey()); // field name
-            PrimitiveTypeInfo type = TypeInfoFactory.timestampTypeInfo; // field type
+            PrimitiveTypeInfo type = TypeInfoFactory.timestampLocalTZTypeInfo; // field type
             columnTypes.add(type);
             inspectors
                     .add(PrimitiveObjectInspectorFactory.getPrimitiveWritableObjectInspector(type));
@@ -300,7 +304,7 @@ public class DruidSerDe extends AbstractSerDe {
           Map<String, PrimitiveTypeInfo> mapColumnNamesTypes) {
     // Timestamp column
     columnNames.add(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN);
-    columnTypes.add(TypeInfoFactory.timestampTypeInfo);
+    columnTypes.add(TypeInfoFactory.timestampLocalTZTypeInfo);
     // Aggregator columns
     for (AggregatorFactory af : query.getAggregatorSpecs()) {
       columnNames.add(af.getName());
@@ -328,7 +332,7 @@ public class DruidSerDe extends AbstractSerDe {
           Map<String, PrimitiveTypeInfo> mapColumnNamesTypes) {
     // Timestamp column
     columnNames.add(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN);
-    columnTypes.add(TypeInfoFactory.timestampTypeInfo);
+    columnTypes.add(TypeInfoFactory.timestampLocalTZTypeInfo);
     // Dimension column
     columnNames.add(query.getDimensionSpec().getOutputName());
     columnTypes.add(TypeInfoFactory.stringTypeInfo);
@@ -360,7 +364,7 @@ public class DruidSerDe extends AbstractSerDe {
                   throws SerDeException {
     // Timestamp column
     columnNames.add(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN);
-    columnTypes.add(TypeInfoFactory.timestampTypeInfo);
+    columnTypes.add(TypeInfoFactory.timestampLocalTZTypeInfo);
     // Dimension columns
     for (DimensionSpec ds : query.getDimensions()) {
       columnNames.add(ds.getOutputName());
@@ -402,7 +406,7 @@ public class DruidSerDe extends AbstractSerDe {
           Map<String, PrimitiveTypeInfo> mapColumnNamesTypes) {
     // Timestamp column
     columnNames.add(DruidStorageHandlerUtils.DEFAULT_TIMESTAMP_COLUMN);
-    columnTypes.add(TypeInfoFactory.timestampTypeInfo);
+    columnTypes.add(TypeInfoFactory.timestampLocalTZTypeInfo);
     // Dimension columns
     for (DimensionSpec ds : query.getDimensions()) {
       columnNames.add(ds.getOutputName());
@@ -456,10 +460,9 @@ public class DruidSerDe extends AbstractSerDe {
       }
       final Object res;
       switch (types[i].getPrimitiveCategory()) {
-        case TIMESTAMP:
-          res = ((TimestampObjectInspector) fields.get(i).getFieldObjectInspector())
-                  .getPrimitiveJavaObject(
-                          values.get(i)).getTime();
+        case TIMESTAMPLOCALTZ:
+          res = ((TimestampLocalTZObjectInspector) fields.get(i).getFieldObjectInspector())
+                  .getPrimitiveJavaObject(values.get(i)).getZonedDateTime().toInstant().toEpochMilli();
           break;
         case BYTE:
           res = ((ByteObjectInspector) fields.get(i).getFieldObjectInspector()).get(values.get(i));
@@ -529,8 +532,13 @@ public class DruidSerDe extends AbstractSerDe {
         continue;
       }
       switch (types[i].getPrimitiveCategory()) {
-        case TIMESTAMP:
-          output.add(new TimestampWritable(new Timestamp((Long) value)));
+        case TIMESTAMPLOCALTZ:
+          output.add(
+              new TimestampLocalTZWritable(
+                  new TimestampTZ(
+                      ZonedDateTime.ofInstant(
+                          Instant.ofEpochMilli((Long) value),
+                          ((TimestampLocalTZTypeInfo) types[i]).timeZone()))));
           break;
         case BYTE:
           output.add(new ByteWritable(((Number) value).byteValue()));

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDeUtils.java
----------------------------------------------------------------------
diff --git a/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDeUtils.java b/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDeUtils.java
index 86c325b..bf55308 100644
--- a/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDeUtils.java
+++ b/druid-handler/src/java/org/apache/hadoop/hive/druid/serde/DruidSerDeUtils.java
@@ -73,7 +73,7 @@ public final class DruidSerDeUtils {
       TimeFormatExtractionFn tfe = (TimeFormatExtractionFn) eds.getExtractionFn();
       if (tfe.getFormat() == null || tfe.getFormat().equals(ISO_TIME_FORMAT)) {
         // Timestamp (null or default used by FLOOR)
-        return TypeInfoFactory.timestampTypeInfo;
+        return TypeInfoFactory.timestampLocalTZTypeInfo;
       } else {
         // EXTRACT from timestamp
         return TypeInfoFactory.intTypeInfo;

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/druid-handler/src/test/org/apache/hadoop/hive/druid/serde/TestDruidSerDe.java
----------------------------------------------------------------------
diff --git a/druid-handler/src/test/org/apache/hadoop/hive/druid/serde/TestDruidSerDe.java b/druid-handler/src/test/org/apache/hadoop/hive/druid/serde/TestDruidSerDe.java
index 655a96a..2d351e4 100644
--- a/druid-handler/src/test/org/apache/hadoop/hive/druid/serde/TestDruidSerDe.java
+++ b/druid-handler/src/test/org/apache/hadoop/hive/druid/serde/TestDruidSerDe.java
@@ -28,6 +28,8 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.lang.reflect.InvocationTargetException;
 import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.ZoneOffset;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Map.Entry;
@@ -47,6 +49,7 @@ import org.apache.hadoop.fs.Path;
 import org.apache.hadoop.hive.common.type.HiveChar;
 import org.apache.hadoop.hive.common.type.HiveDecimal;
 import org.apache.hadoop.hive.common.type.HiveVarchar;
+import org.apache.hadoop.hive.common.type.TimestampTZ;
 import org.apache.hadoop.hive.conf.Constants;
 import org.apache.hadoop.hive.druid.DruidStorageHandlerUtils;
 import org.apache.hadoop.hive.druid.QTestDruidSerDe;
@@ -62,6 +65,7 @@ import org.apache.hadoop.hive.serde2.io.HiveCharWritable;
 import org.apache.hadoop.hive.serde2.io.HiveDecimalWritable;
 import org.apache.hadoop.hive.serde2.io.HiveVarcharWritable;
 import org.apache.hadoop.hive.serde2.io.ShortWritable;
+import org.apache.hadoop.hive.serde2.io.TimestampLocalTZWritable;
 import org.apache.hadoop.hive.serde2.io.TimestampWritable;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorFactory;
@@ -148,19 +152,19 @@ public class TestDruidSerDe {
 
   // Timeseries query results as records
   private static final Object[][] TIMESERIES_QUERY_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1325376000000L)), new LongWritable(0),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))), new LongWritable(0),
                   new FloatWritable(1.0F), new FloatWritable(2.2222F) },
-          new Object[] { new TimestampWritable(new Timestamp(1325462400000L)), new LongWritable(2),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325462400000L).atZone(ZoneOffset.UTC))), new LongWritable(2),
                   new FloatWritable(3.32F), new FloatWritable(4F) }
   };
 
   // Timeseries query results as records (types defined by metastore)
   private static final String TIMESERIES_COLUMN_NAMES = "__time,sample_name1,sample_name2,sample_divide";
-  private static final String TIMESERIES_COLUMN_TYPES = "timestamp,smallint,double,float";
+  private static final String TIMESERIES_COLUMN_TYPES = "timestamp with local time zone,smallint,double,float";
   private static final Object[][] TIMESERIES_QUERY_RESULTS_RECORDS_2 = new Object[][] {
-    new Object[] { new TimestampWritable(new Timestamp(1325376000000L)), new ShortWritable((short) 0),
+    new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))), new ShortWritable((short) 0),
         new DoubleWritable(1.0d), new FloatWritable(2.2222F) },
-    new Object[] { new TimestampWritable(new Timestamp(1325462400000L)), new ShortWritable((short) 2),
+    new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325462400000L).atZone(ZoneOffset.UTC))), new ShortWritable((short) 2),
         new DoubleWritable(3.32d), new FloatWritable(4F) }
   };
 
@@ -263,40 +267,40 @@ public class TestDruidSerDe {
 
   // TopN query results as records
   private static final Object[][] TOPN_QUERY_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)), new Text("dim1_val"),
-                  new LongWritable(111), new FloatWritable(10669F),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
+                  new Text("dim1_val"), new LongWritable(111), new FloatWritable(10669F),
                   new FloatWritable(96.11711711711712F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("another_dim1_val"), new LongWritable(88), new FloatWritable(28344F),
                   new FloatWritable(322.09090909090907F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val3"), new LongWritable(70), new FloatWritable(871F),
                   new FloatWritable(12.442857142857143F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val4"), new LongWritable(62), new FloatWritable(815F),
                   new FloatWritable(13.14516129032258F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val5"), new LongWritable(60), new FloatWritable(2787F),
                   new FloatWritable(46.45F) }
   };
 
   // TopN query results as records (types defined by metastore)
   private static final String TOPN_COLUMN_NAMES = "__time,sample_dim,count,some_metric,sample_divide";
-  private static final String TOPN_COLUMN_TYPES = "timestamp,string,bigint,double,float";
+  private static final String TOPN_COLUMN_TYPES = "timestamp with local time zone,string,bigint,double,float";
   private static final Object[][] TOPN_QUERY_RESULTS_RECORDS_2 = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val"), new LongWritable(111), new DoubleWritable(10669d),
                   new FloatWritable(96.11711711711712F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("another_dim1_val"), new LongWritable(88), new DoubleWritable(28344d),
                   new FloatWritable(322.09090909090907F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val3"), new LongWritable(70), new DoubleWritable(871d),
                   new FloatWritable(12.442857142857143F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val4"), new LongWritable(62), new DoubleWritable(815d),
                   new FloatWritable(13.14516129032258F) },
-          new Object[] { new TimestampWritable(new Timestamp(1377907200000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
                   new Text("dim1_val5"), new LongWritable(60), new DoubleWritable(2787d),
                   new FloatWritable(46.45F) }
   };
@@ -425,38 +429,39 @@ public class TestDruidSerDe {
 
   // GroupBy query results as records
   private static final Object[][] GROUP_BY_QUERY_EXTRACTION_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1325376000000L)),
-                  new TimestampWritable(new Timestamp(1325376000000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))),
+              new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))),
                   new LongWritable(200) },
-          new Object[] { new TimestampWritable(new Timestamp(1325376012000L)), new TimestampWritable(new Timestamp(1325376012000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376012000L).atZone(ZoneOffset.UTC))),
+              new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376012000L).atZone(ZoneOffset.UTC))),
                   new LongWritable(400) }
   };
 
   private static final Object[][] GROUP_BY_QUERY_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1325376000000L)), new Text("India"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))), new Text("India"),
                   new Text("phone"), new LongWritable(88), new FloatWritable(29.91233453F),
                   new FloatWritable(60.32F) },
-          new Object[] { new TimestampWritable(new Timestamp(1325376012000L)), new Text("Spain"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376012000L).atZone(ZoneOffset.UTC))), new Text("Spain"),
                   new Text("pc"), new LongWritable(16), new FloatWritable(172.93494959F),
                   new FloatWritable(6.333333F) }
   };
 
   private static final Object[][] GB_MONTH_EXTRACTION_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1325376000000L)),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))),
                   new IntWritable(1),
                   new LongWritable(200) },
-          new Object[] { new TimestampWritable(new Timestamp(1325376012000L)), new IntWritable(1),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376012000L).atZone(ZoneOffset.UTC))), new IntWritable(1),
                   new LongWritable(400) }
   };
 
   // GroupBy query results as records (types defined by metastore)
   private static final String GROUP_BY_COLUMN_NAMES = "__time,country,device,total_usage,data_transfer,avg_usage";
-  private static final String GROUP_BY_COLUMN_TYPES = "timestamp,string,string,int,double,float";
+  private static final String GROUP_BY_COLUMN_TYPES = "timestamp with local time zone,string,string,int,double,float";
   private static final Object[][] GROUP_BY_QUERY_RESULTS_RECORDS_2 = new Object[][] {
-    new Object[] { new TimestampWritable(new Timestamp(1325376000000L)), new Text("India"),
+    new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376000000L).atZone(ZoneOffset.UTC))), new Text("India"),
             new Text("phone"), new IntWritable(88), new DoubleWritable(29.91233453),
             new FloatWritable(60.32F) },
-    new Object[] { new TimestampWritable(new Timestamp(1325376012000L)), new Text("Spain"),
+    new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1325376012000L).atZone(ZoneOffset.UTC))), new Text("Spain"),
             new Text("pc"), new IntWritable(16), new DoubleWritable(172.93494959),
             new FloatWritable(6.333333F) }
   };
@@ -577,28 +582,28 @@ public class TestDruidSerDe {
 
   // Select query results as records
   private static final Object[][] SELECT_QUERY_RESULTS_RECORDS = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1356998400000L)), new Text("1"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998400000L).atZone(ZoneOffset.UTC))), new Text("1"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("11._korpus_(NOVJ)"), new Text("sl"), new Text("0"),
                   new Text("EmausBot"),
                   new FloatWritable(1.0F), new FloatWritable(39.0F), new FloatWritable(39.0F),
                   new FloatWritable(39.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998400000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998400000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("112_U.S._580"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new FloatWritable(1.0F), new FloatWritable(70.0F), new FloatWritable(70.0F),
                   new FloatWritable(70.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._243"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new FloatWritable(1.0F), new FloatWritable(77.0F), new FloatWritable(77.0F),
                   new FloatWritable(77.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._73"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new FloatWritable(1.0F), new FloatWritable(70.0F), new FloatWritable(70.0F),
                   new FloatWritable(70.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._756"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new FloatWritable(1.0F), new FloatWritable(68.0F), new FloatWritable(68.0F),
@@ -607,30 +612,30 @@ public class TestDruidSerDe {
 
   // Select query results as records (types defined by metastore)
   private static final String SELECT_COLUMN_NAMES = "__time,robot,namespace,anonymous,unpatrolled,page,language,newpage,user,count,added,delta,variation,deleted";
-  private static final String SELECT_COLUMN_TYPES = "timestamp,string,string,string,string,string,string,string,string,double,double,float,float,float";
+  private static final String SELECT_COLUMN_TYPES = "timestamp with local time zone,string,string,string,string,string,string,string,string,double,double,float,float,float";
   private static final Object[][] SELECT_QUERY_RESULTS_RECORDS_2 = new Object[][] {
-          new Object[] { new TimestampWritable(new Timestamp(1356998400000L)), new Text("1"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998400000L).atZone(ZoneOffset.UTC))), new Text("1"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("11._korpus_(NOVJ)"), new Text("sl"), new Text("0"),
                   new Text("EmausBot"),
                   new DoubleWritable(1.0d), new DoubleWritable(39.0d), new FloatWritable(39.0F),
                   new FloatWritable(39.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998400000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998400000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("112_U.S._580"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new DoubleWritable(1.0d), new DoubleWritable(70.0d), new FloatWritable(70.0F),
                   new FloatWritable(70.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._243"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new DoubleWritable(1.0d), new DoubleWritable(77.0d), new FloatWritable(77.0F),
                   new FloatWritable(77.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._73"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new DoubleWritable(1.0d), new DoubleWritable(70.0d), new FloatWritable(70.0F),
                   new FloatWritable(70.0F), new FloatWritable(0.0F) },
-          new Object[] { new TimestampWritable(new Timestamp(1356998412000L)), new Text("0"),
+          new Object[] { new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1356998412000L).atZone(ZoneOffset.UTC))), new Text("0"),
                   new Text("article"), new Text("0"), new Text("0"),
                   new Text("113_U.S._756"), new Text("en"), new Text("1"), new Text("MZMcBride"),
                   new DoubleWritable(1.0d), new DoubleWritable(68.0d), new FloatWritable(68.0F),
@@ -827,9 +832,9 @@ public class TestDruidSerDe {
 
 
   private static final String COLUMN_NAMES = "__time,c0,c1,c2,c3,c4,c5,c6,c7,c8,c9";
-  private static final String COLUMN_TYPES = "timestamp,string,char(6),varchar(8),double,float,decimal(38,18),bigint,int,smallint,tinyint";
+  private static final String COLUMN_TYPES = "timestamp with local time zone,string,char(6),varchar(8),double,float,decimal(38,18),bigint,int,smallint,tinyint";
   private static final Object[] ROW_OBJECT = new Object[] {
-      new TimestampWritable(new Timestamp(1377907200000L)),
+      new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
       new Text("dim1_val"),
       new HiveCharWritable(new HiveChar("dim2_v", 6)),
       new HiveVarcharWritable(new HiveVarchar("dim3_val", 8)),
@@ -933,7 +938,7 @@ public class TestDruidSerDe {
   }
 
   private static final Object[] ROW_OBJECT_2 = new Object[] {
-      new TimestampWritable(new Timestamp(1377907200000L)),
+      new TimestampLocalTZWritable(new TimestampTZ(Instant.ofEpochMilli(1377907200000L).atZone(ZoneOffset.UTC))),
       new Text("dim1_val"),
       new HiveCharWritable(new HiveChar("dim2_v", 6)),
       new HiveVarcharWritable(new HiveVarchar("dim3_val", 8)),

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/pom.xml
----------------------------------------------------------------------
diff --git a/pom.xml b/pom.xml
index 32b09ef..b521cc4 100644
--- a/pom.xml
+++ b/pom.xml
@@ -119,7 +119,7 @@
     <avatica.version>1.10.0</avatica.version>
     <avro.version>1.7.7</avro.version>
     <bonecp.version>0.8.0.RELEASE</bonecp.version>
-    <calcite.version>1.13.0</calcite.version>
+    <calcite.version>1.14.0</calcite.version>
     <datanucleus-api-jdo.version>4.2.4</datanucleus-api-jdo.version>
     <datanucleus-core.version>4.1.17</datanucleus-core.version>
     <datanucleus-rdbms.version>4.1.19</datanucleus-rdbms.version>

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
index 1d1d2a3..2308bf4 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/FunctionRegistry.java
@@ -497,6 +497,8 @@ public final class FunctionRegistry {
     system.registerGenericUDF("to_unix_timestamp", GenericUDFToUnixTimeStamp.class);
 
     system.registerGenericUDF("internal_interval", GenericUDFInternalInterval.class);
+
+    system.registerGenericUDF("to_epoch_milli", GenericUDFEpochMilli.class);
     // Generic UDTF's
     system.registerGenericUDTF("explode", GenericUDTFExplode.class);
     system.registerGenericUDTF("replicate_rows", GenericUDTFReplicateRows.class);

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
index 68c9482..793ce9e 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
@@ -1509,7 +1509,7 @@ public class Hive {
         Map<String, RelOptMaterialization> qualifiedNameToView =
             new HashMap<String, RelOptMaterialization>();
         for (RelOptMaterialization materialization : cachedViews) {
-          qualifiedNameToView.put(materialization.table.getQualifiedName().get(0), materialization);
+          qualifiedNameToView.put(materialization.qualifiedTableName.get(0), materialization);
         }
         for (String table : tables) {
           // Compose qualified name

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveMaterializedViewsRegistry.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveMaterializedViewsRegistry.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveMaterializedViewsRegistry.java
index 154ea68..ba46ff7 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveMaterializedViewsRegistry.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/HiveMaterializedViewsRegistry.java
@@ -188,7 +188,8 @@ public final class HiveMaterializedViewsRegistry {
               " ignored; error parsing original query");
       return null;
     }
-    RelOptMaterialization materialization = new RelOptMaterialization(tableRel, queryRel, null);
+    RelOptMaterialization materialization = new RelOptMaterialization(tableRel, queryRel,
+        null, tableRel.getTable().getQualifiedName());
     cq.put(vk, materialization);
     if (LOG.isDebugEnabled()) {
       LOG.debug("Cached materialized view for rewriting: " + tableRel.getTable().getQualifiedName());
@@ -314,10 +315,13 @@ public final class HiveMaterializedViewsRegistry {
         }
         metrics.add(field.getName());
       }
+      // TODO: Default interval will be an Interval once Calcite 1.15.0 is released.
+      // We will need to update the type of this list.
       List<LocalInterval> intervals = Arrays.asList(DruidTable.DEFAULT_INTERVAL);
 
       DruidTable druidTable = new DruidTable(new DruidSchema(address, address, false),
-          dataSource, RelDataTypeImpl.proto(rowType), metrics, DruidTable.DEFAULT_TIMESTAMP_COLUMN, intervals);
+          dataSource, RelDataTypeImpl.proto(rowType), metrics, DruidTable.DEFAULT_TIMESTAMP_COLUMN,
+          intervals, null, null);
       final TableScan scan = new HiveTableScan(cluster, cluster.traitSetOf(HiveRelNode.CONVENTION),
           optTable, viewTable.getTableName(), null, false, false);
       tableRel = DruidQuery.create(cluster, cluster.traitSetOf(HiveRelNode.CONVENTION),

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionTimeGranularityOptimizer.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionTimeGranularityOptimizer.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionTimeGranularityOptimizer.java
index 4a248d6..8c4b690 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionTimeGranularityOptimizer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/SortedDynPartitionTimeGranularityOptimizer.java
@@ -62,6 +62,8 @@ import org.apache.hadoop.hive.ql.udf.UDFDateFloorSecond;
 import org.apache.hadoop.hive.ql.udf.UDFDateFloorWeek;
 import org.apache.hadoop.hive.ql.udf.UDFDateFloorYear;
 import org.apache.hadoop.hive.ql.udf.generic.GenericUDFBridge;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFEpochMilli;
+import org.apache.hadoop.hive.ql.udf.generic.GenericUDFTimestamp;
 import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
 import org.apache.hadoop.hive.serde2.objectinspector.PrimitiveObjectInspector.PrimitiveCategory;
 import org.apache.hadoop.hive.serde2.typeinfo.PrimitiveTypeInfo;
@@ -158,9 +160,7 @@ public class SortedDynPartitionTimeGranularityOptimizer extends Transform {
       fsParent.getChildOperators().clear();
 
       // Create SelectOp with granularity column
-      Operator<? extends OperatorDesc> granularitySelOp = getGranularitySelOp(fsParent,
-              segmentGranularity
-      );
+      Operator<? extends OperatorDesc> granularitySelOp = getGranularitySelOp(fsParent, segmentGranularity);
 
       // Create ReduceSinkOp operator
       ArrayList<ColumnInfo> parentCols = Lists.newArrayList(granularitySelOp.getSchema().getSignature());
@@ -230,17 +230,17 @@ public class SortedDynPartitionTimeGranularityOptimizer extends Transform {
         descs.add(columnDesc);
         colNames.add(columnDesc.getExprString());
         if (columnDesc.getTypeInfo().getCategory() == ObjectInspector.Category.PRIMITIVE
-                && ((PrimitiveTypeInfo) columnDesc.getTypeInfo()).getPrimitiveCategory() == PrimitiveCategory.TIMESTAMP) {
+                && ((PrimitiveTypeInfo) columnDesc.getTypeInfo()).getPrimitiveCategory() == PrimitiveCategory.TIMESTAMPLOCALTZ) {
           if (timestampPos != -1) {
-            throw new SemanticException("Multiple columns with timestamp type on query result; "
-                    + "could not resolve which one is the timestamp column");
+            throw new SemanticException("Multiple columns with timestamp with local time-zone type on query result; "
+                    + "could not resolve which one is the timestamp with local time-zone column");
           }
           timestampPos = i;
         }
       }
       if (timestampPos == -1) {
-        throw new SemanticException("No column with timestamp type on query result; "
-                + "one column should be of timestamp type");
+        throw new SemanticException("No column with timestamp with local time-zone type on query result; "
+                + "one column should be of timestamp with local time-zone type");
       }
       RowSchema selRS = new RowSchema(fsParent.getSchema());
       // Granularity (partition) column
@@ -279,11 +279,33 @@ public class SortedDynPartitionTimeGranularityOptimizer extends Transform {
         default:
           throw new SemanticException("Granularity for Druid segment not recognized");
       }
+
+      // Timestamp column type in Druid is timestamp with local time-zone, as it represents
+      // a specific instant in time. Thus, we have this value and we need to extract the
+      // granularity to split the data when we are storing it in Druid. However, Druid stores
+      // the data in UTC. Thus, we need to apply the following logic on the data to extract
+      // the granularity correctly:
+      // 1) Read the timestamp with local time-zone value.
+      // 2) Extract UTC epoch (millis) from timestamp with local time-zone.
+      // 3) Cast the long to a timestamp.
+      // 4) Apply the granularity function on the timestamp value.
+      // That way, '2010-01-01 00:00:00 UTC' and '2009-12-31 16:00:00 PST' (same instant)
+      // will end up in the same Druid segment.
+
+      // #1 - Read the column value
       ExprNodeDesc expr = new ExprNodeColumnDesc(parentCols.get(timestampPos));
-      descs.add(new ExprNodeGenericFuncDesc(
-              TypeInfoFactory.timestampTypeInfo,
-              new GenericUDFBridge(udfName, false, udfClass.getName()),
-              Lists.newArrayList(expr)));
+      // #2 - UTC epoch for instant
+      ExprNodeGenericFuncDesc f1 = new ExprNodeGenericFuncDesc(
+          TypeInfoFactory.longTypeInfo, new GenericUDFEpochMilli(), Lists.newArrayList(expr));
+      // #3 - Cast to timestamp
+      ExprNodeGenericFuncDesc f2 = new ExprNodeGenericFuncDesc(
+          TypeInfoFactory.timestampTypeInfo, new GenericUDFTimestamp(), Lists.newArrayList(f1));
+      // #4 - We apply the granularity function
+      ExprNodeGenericFuncDesc f3 = new ExprNodeGenericFuncDesc(
+          TypeInfoFactory.timestampTypeInfo,
+          new GenericUDFBridge(udfName, false, udfClass.getName()),
+          Lists.newArrayList(f2));
+      descs.add(f3);
       colNames.add(Constants.DRUID_TIMESTAMP_GRANULARITY_COL_NAME);
       // Add granularity to the row schema
       ColumnInfo ci = new ColumnInfo(Constants.DRUID_TIMESTAMP_GRANULARITY_COL_NAME, TypeInfoFactory.timestampTypeInfo,

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveCalciteUtil.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveCalciteUtil.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveCalciteUtil.java
index f70aa75..692d7a6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveCalciteUtil.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveCalciteUtil.java
@@ -964,7 +964,7 @@ public class HiveCalciteUtil {
         aggArgRelDTBldr.build(), aggFnRetType);
     List<Integer> argList = new ArrayList<Integer>();
     argList.add(pos);
-    return new AggregateCall(aggFunction, false, argList, aggFnRetType, null);
+    return AggregateCall.create(aggFunction, false, argList, -1, aggFnRetType, null);
   }
 
   public static HiveTableFunctionScan createUDTFForSetOp(RelOptCluster cluster, RelNode input)

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveConfPlannerContext.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveConfPlannerContext.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveConfPlannerContext.java
index 756b671..60c3bdd 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveConfPlannerContext.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveConfPlannerContext.java
@@ -17,10 +17,6 @@
  */
 package org.apache.hadoop.hive.ql.optimizer.calcite;
 
-import org.apache.calcite.rel.RelNode;
-
-import java.util.Set;
-
 public class HiveConfPlannerContext{
 
   private boolean isCorrelatedColumns;

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveRelFactories.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveRelFactories.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveRelFactories.java
index 823b099..afebad3 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveRelFactories.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveRelFactories.java
@@ -44,10 +44,10 @@ import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveAggregate;
+import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveExcept;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveIntersect;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveJoin;
-import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveExcept;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveProject;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveSemiJoin;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveSortLimit;
@@ -193,7 +193,11 @@ public class HiveRelFactories {
     public RelNode createAggregate(RelNode child, boolean indicator,
             ImmutableBitSet groupSet, ImmutableList<ImmutableBitSet> groupSets,
             List<AggregateCall> aggCalls) {
-        return new HiveAggregate(child.getCluster(), child.getTraitSet(), child, indicator,
+        if (indicator) {
+          throw new IllegalStateException("Hive does not support indicator columns but Calcite "
+                  + "created an Aggregate operator containing them");
+        }
+        return new HiveAggregate(child.getCluster(), child.getTraitSet(), child,
                 groupSet, groupSets, aggCalls);
     }
   }

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveType.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveType.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveType.java
deleted file mode 100644
index 31a628b..0000000
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveType.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/**
- * 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.hadoop.hive.ql.optimizer.calcite;
-
-import org.apache.calcite.sql.type.AbstractSqlType;
-import org.apache.calcite.sql.type.SqlTypeName;
-
-/**
- * Hive-specific type.
- *
- * TODO: Created to represent timestamp with time-zone type.
- * It can be removed once the type exists in Calcite.
- */
-public class HiveType extends AbstractSqlType {
-  private final Class clazz;
-
-  public HiveType(Class clazz) {
-    super(SqlTypeName.NULL, true, null);
-    this.clazz = clazz;
-    computeDigest();
-  }
-
-  protected void generateTypeString(StringBuilder sb, boolean withDetail) {
-    sb.append("HiveType(");
-    sb.append(clazz);
-    sb.append(")");
-  }
-
-  public Class getTypeClass() {
-    return clazz;
-  }
-
-}

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveTypeSystemImpl.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveTypeSystemImpl.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveTypeSystemImpl.java
index dad783d..bbc26bc 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveTypeSystemImpl.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/HiveTypeSystemImpl.java
@@ -36,6 +36,7 @@ public class HiveTypeSystemImpl extends RelDataTypeSystemImpl {
   private static final int DEFAULT_CHAR_PRECISION    = 255;
   private static final int MAX_BINARY_PRECISION      = Integer.MAX_VALUE;
   private static final int MAX_TIMESTAMP_PRECISION   = 9;
+  private static final int MAX_TIMESTAMP_WITH_LOCAL_TIME_ZONE_PRECISION = 15; // Up to nanos
 
   @Override
   public int getMaxScale(SqlTypeName typeName) {
@@ -70,6 +71,7 @@ public class HiveTypeSystemImpl extends RelDataTypeSystemImpl {
     case VARBINARY:
     case TIME:
     case TIMESTAMP:
+    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
       return getMaxPrecision(typeName);
     case CHAR:
       return DEFAULT_CHAR_PRECISION;
@@ -110,6 +112,8 @@ public class HiveTypeSystemImpl extends RelDataTypeSystemImpl {
     case TIME:
     case TIMESTAMP:
       return MAX_TIMESTAMP_PRECISION;
+    case TIMESTAMP_WITH_LOCAL_TIME_ZONE:
+      return MAX_TIMESTAMP_WITH_LOCAL_TIME_ZONE_PRECISION;
     case INTERVAL_YEAR:
     case INTERVAL_MONTH:
     case INTERVAL_YEAR_MONTH:

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlCountAggFunction.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlCountAggFunction.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlCountAggFunction.java
index 75b7ad2..661427e 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlCountAggFunction.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlCountAggFunction.java
@@ -17,19 +17,29 @@
  */
 package org.apache.hadoop.hive.ql.optimizer.calcite.functions;
 
+import java.util.ArrayList;
+import java.util.List;
+
 import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.rex.RexBuilder;
+import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
 import org.apache.calcite.sql.SqlSplittableAggFunction;
 import org.apache.calcite.sql.SqlSplittableAggFunction.CountSplitter;
+import org.apache.calcite.sql.SqlSplittableAggFunction.Registry;
+import org.apache.calcite.sql.fun.SqlStdOperatorTable;
 import org.apache.calcite.sql.type.SqlOperandTypeChecker;
 import org.apache.calcite.sql.type.SqlOperandTypeInference;
 import org.apache.calcite.sql.type.SqlReturnTypeInference;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.ImmutableIntList;
 
+import com.google.common.collect.ImmutableList;
+
 public class HiveSqlCountAggFunction extends SqlAggFunction implements CanAggregateDistinct {
 
   final boolean                isDistinct;
@@ -65,15 +75,49 @@ public class HiveSqlCountAggFunction extends SqlAggFunction implements CanAggreg
     return super.unwrap(clazz);
   }
 
+  // We need to override these methods due to difference in nullability between Hive and
+  // Calcite for the return types of the aggregation  (in particular, for COUNT and SUM0).
+  // TODO: We should close the semantics gaps between Hive and Calcite for nullability of
+  // aggregation calls return types. This might be useful to trigger some additional
+  // rewriting rules that would remove unnecessary predicates, etc.
   class HiveCountSplitter extends CountSplitter {
 
     @Override
     public AggregateCall other(RelDataTypeFactory typeFactory, AggregateCall e) {
-
       return AggregateCall.create(
           new HiveSqlCountAggFunction(isDistinct, returnTypeInference, operandTypeInference, operandTypeChecker),
           false, ImmutableIntList.of(), -1,
           typeFactory.createTypeWithNullability(typeFactory.createSqlType(SqlTypeName.BIGINT), true), "count");
     }
+
+    @Override
+    public AggregateCall topSplit(RexBuilder rexBuilder,
+        Registry<RexNode> extra, int offset, RelDataType inputRowType,
+        AggregateCall aggregateCall, int leftSubTotal, int rightSubTotal) {
+      final List<RexNode> merges = new ArrayList<>();
+      if (leftSubTotal >= 0) {
+        merges.add(
+            rexBuilder.makeInputRef(aggregateCall.type, leftSubTotal));
+      }
+      if (rightSubTotal >= 0) {
+        merges.add(
+            rexBuilder.makeInputRef(aggregateCall.type, rightSubTotal));
+      }
+      RexNode node;
+      switch (merges.size()) {
+      case 1:
+        node = merges.get(0);
+        break;
+      case 2:
+        node = rexBuilder.makeCall(SqlStdOperatorTable.MULTIPLY, merges);
+        break;
+      default:
+        throw new AssertionError("unexpected count " + merges);
+      }
+      int ordinal = extra.register(node);
+      return AggregateCall.create(
+          new HiveSqlSumEmptyIsZeroAggFunction(isDistinct, returnTypeInference, operandTypeInference, operandTypeChecker),
+          false, ImmutableList.of(ordinal), -1, aggregateCall.type, aggregateCall.name);
+    }
   }
 }

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlSumEmptyIsZeroAggFunction.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlSumEmptyIsZeroAggFunction.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlSumEmptyIsZeroAggFunction.java
new file mode 100644
index 0000000..31f6022
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/functions/HiveSqlSumEmptyIsZeroAggFunction.java
@@ -0,0 +1,59 @@
+package org.apache.hadoop.hive.ql.optimizer.calcite.functions;
+
+import java.util.List;
+
+import org.apache.calcite.rel.type.RelDataType;
+import org.apache.calcite.rel.type.RelDataTypeFactory;
+import org.apache.calcite.sql.SqlAggFunction;
+import org.apache.calcite.sql.SqlFunctionCategory;
+import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.SqlSplittableAggFunction;
+import org.apache.calcite.sql.type.SqlOperandTypeChecker;
+import org.apache.calcite.sql.type.SqlOperandTypeInference;
+import org.apache.calcite.sql.type.SqlReturnTypeInference;
+import org.apache.calcite.sql.type.SqlTypeName;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * <code>Sum0</code> is an aggregator which returns the sum of the values which
+ * go into it like <code>Sum</code>. It differs in that when no non null values
+ * are applied zero is returned instead of null. Can be used along with <code>
+ * Count</code> to implement <code>Sum</code>.
+ */
+public class HiveSqlSumEmptyIsZeroAggFunction extends SqlAggFunction {
+  //~ Constructors -----------------------------------------------------------
+
+  public HiveSqlSumEmptyIsZeroAggFunction(boolean isDistinct, SqlReturnTypeInference returnTypeInference,
+          SqlOperandTypeInference operandTypeInference, SqlOperandTypeChecker operandTypeChecker) {
+    super("$SUM0",
+        null,
+        SqlKind.SUM0,
+        returnTypeInference,
+        operandTypeInference,
+        operandTypeChecker,
+        SqlFunctionCategory.NUMERIC,
+        false,
+        false);
+  }
+
+  //~ Methods ----------------------------------------------------------------
+
+  public List<RelDataType> getParameterTypes(RelDataTypeFactory typeFactory) {
+    return ImmutableList.of(
+        typeFactory.createTypeWithNullability(
+            typeFactory.createSqlType(SqlTypeName.ANY), true));
+  }
+
+  public RelDataType getReturnType(RelDataTypeFactory typeFactory) {
+    return typeFactory.createTypeWithNullability(
+        typeFactory.createSqlType(SqlTypeName.ANY), true);
+  }
+
+  @Override public <T> T unwrap(Class<T> clazz) {
+    if (clazz == SqlSplittableAggFunction.class) {
+      return clazz.cast(SqlSplittableAggFunction.SumSplitter.INSTANCE);
+    }
+    return super.unwrap(clazz);
+  }
+}

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveAggregate.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveAggregate.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveAggregate.java
index fa51b4e..1be15bc 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveAggregate.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveAggregate.java
@@ -34,8 +34,8 @@ import org.apache.calcite.rel.type.RelDataTypeFactory;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.sql.type.SqlTypeName;
 import org.apache.calcite.util.ImmutableBitSet;
-import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil;
 import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelShuttle;
+import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil;
 
 import com.google.common.collect.Sets;
 
@@ -45,18 +45,22 @@ public class HiveAggregate extends Aggregate implements HiveRelNode {
 
 
   public HiveAggregate(RelOptCluster cluster, RelTraitSet traitSet, RelNode child,
-      boolean indicator, ImmutableBitSet groupSet, List<ImmutableBitSet> groupSets,
+      ImmutableBitSet groupSet, List<ImmutableBitSet> groupSets,
       List<AggregateCall> aggCalls) {
-    super(cluster, TraitsUtil.getDefaultTraitSet(cluster), child, indicator, groupSet,
-            groupSets, aggCalls);
+    super(cluster, TraitsUtil.getDefaultTraitSet(cluster), child, false,
+            groupSet, groupSets, aggCalls);
   }
 
   @Override
   public Aggregate copy(RelTraitSet traitSet, RelNode input,
           boolean indicator, ImmutableBitSet groupSet,
           List<ImmutableBitSet> groupSets, List<AggregateCall> aggCalls) {
-      return new HiveAggregate(getCluster(), traitSet, input, indicator, groupSet,
-              groupSets, aggCalls);
+      if (indicator) {
+        throw new IllegalStateException("Hive does not support indicator columns but tried "
+                + "to create an Aggregate operator containing them");
+      }
+      return new HiveAggregate(getCluster(), traitSet, input,
+              groupSet, groupSets, aggCalls);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveGroupingID.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveGroupingID.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveGroupingID.java
index 2fb9508..adcda26 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveGroupingID.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/reloperators/HiveGroupingID.java
@@ -17,17 +17,17 @@
  */
 package org.apache.hadoop.hive.ql.optimizer.calcite.reloperators;
 
-import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlFunctionCategory;
 import org.apache.calcite.sql.SqlKind;
+import org.apache.calcite.sql.fun.SqlAbstractGroupFunction;
 import org.apache.calcite.sql.type.InferTypes;
 import org.apache.calcite.sql.type.OperandTypes;
 import org.apache.calcite.sql.type.ReturnTypes;
 import org.apache.hadoop.hive.ql.metadata.VirtualColumn;
 
-public class HiveGroupingID extends SqlAggFunction {
+public class HiveGroupingID extends SqlAbstractGroupFunction {
 
-  public static final SqlAggFunction INSTANCE =
+  public static final HiveGroupingID INSTANCE =
           new HiveGroupingID();
 
   private HiveGroupingID() {
@@ -36,7 +36,7 @@ public class HiveGroupingID extends SqlAggFunction {
             ReturnTypes.INTEGER,
             InferTypes.BOOLEAN,
             OperandTypes.NILADIC,
-            SqlFunctionCategory.USER_DEFINED_FUNCTION);
+            SqlFunctionCategory.SYSTEM);
   }
 
 }

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateJoinTransposeRule.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateJoinTransposeRule.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateJoinTransposeRule.java
index 21b46cf..a09e7f6 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateJoinTransposeRule.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateJoinTransposeRule.java
@@ -33,9 +33,9 @@ import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.core.Join;
 import org.apache.calcite.rel.core.JoinRelType;
-import org.apache.calcite.rel.core.RelFactories;
 import org.apache.calcite.rel.metadata.RelMetadataQuery;
 import org.apache.calcite.rel.rules.AggregateJoinTransposeRule;
+import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexCall;
 import org.apache.calcite.rex.RexInputRef;
@@ -43,6 +43,8 @@ import org.apache.calcite.rex.RexNode;
 import org.apache.calcite.rex.RexUtil;
 import org.apache.calcite.sql.SqlAggFunction;
 import org.apache.calcite.sql.SqlSplittableAggFunction;
+import org.apache.calcite.tools.RelBuilder;
+import org.apache.calcite.tools.RelBuilderFactory;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.calcite.util.mapping.Mapping;
 import org.apache.calcite.util.mapping.Mappings;
@@ -64,29 +66,17 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
 
   /** Extended instance of the rule that can push down aggregate functions. */
   public static final HiveAggregateJoinTransposeRule INSTANCE =
-      new HiveAggregateJoinTransposeRule(HiveAggregate.class, HiveRelFactories.HIVE_AGGREGATE_FACTORY,
-          HiveJoin.class, HiveRelFactories.HIVE_JOIN_FACTORY, HiveRelFactories.HIVE_PROJECT_FACTORY,
-          true);
-
-  private final RelFactories.AggregateFactory aggregateFactory;
-
-  private final RelFactories.JoinFactory joinFactory;
-
-  private final RelFactories.ProjectFactory projectFactory;
+      new HiveAggregateJoinTransposeRule(HiveAggregate.class, HiveJoin.class,
+          HiveRelFactories.HIVE_BUILDER, true);
 
   private final boolean allowFunctions;
 
   /** Creates an AggregateJoinTransposeRule that may push down functions. */
   private HiveAggregateJoinTransposeRule(Class<? extends Aggregate> aggregateClass,
-      RelFactories.AggregateFactory aggregateFactory,
       Class<? extends Join> joinClass,
-      RelFactories.JoinFactory joinFactory,
-      RelFactories.ProjectFactory projectFactory,
+      RelBuilderFactory relBuilderFactory,
       boolean allowFunctions) {
-    super(aggregateClass, aggregateFactory, joinClass, joinFactory, projectFactory, true);
-    this.aggregateFactory = aggregateFactory;
-    this.joinFactory = joinFactory;
-    this.projectFactory = projectFactory;
+    super(aggregateClass, joinClass, relBuilderFactory, true);
     this.allowFunctions = allowFunctions;
   }
 
@@ -95,6 +85,7 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
     final Aggregate aggregate = call.rel(0);
     final Join join = call.rel(1);
     final RexBuilder rexBuilder = aggregate.getCluster().getRexBuilder();
+    final RelBuilder relBuilder = call.builder();
 
     // If any aggregate functions do not support splitting, bail out
     // If any aggregate call has a filter, bail out
@@ -119,8 +110,8 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
     }
 
     // Do the columns used by the join appear in the output of the aggregate?
-    final RelMetadataQuery mq = call.getMetadataQuery();
     final ImmutableBitSet aggregateColumns = aggregate.getGroupSet();
+    final RelMetadataQuery mq = call.getMetadataQuery();
     final ImmutableBitSet keyColumns = keyColumns(aggregateColumns,
         mq.getPulledUpPredicates(join).pulledUpPredicates);
     final ImmutableBitSet joinColumns =
@@ -171,8 +162,8 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
         // any functions experiencing a cartesian product effect.
         //
         // But finding out whether the input is already unique requires a call
-        // to areColumnsUnique that currently (until [CALCITE-794] "Detect
-        // cycles when computing statistics" is fixed) places a heavy load on
+        // to areColumnsUnique that currently (until [CALCITE-1048] "Make
+        // metadata more robust" is fixed) places a heavy load on
         // the metadata system.
         //
         // So we choose to imagine the the input is already unique, which is
@@ -213,8 +204,10 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
                     + belowAggCallRegistry.register(call1));
           }
         }
-        side.newInput = aggregateFactory.createAggregate(joinInput, false,
-            belowAggregateKey, null, belowAggCalls);
+        side.newInput = relBuilder.push(joinInput)
+            .aggregate(relBuilder.groupKey(belowAggregateKey, null),
+                belowAggCalls)
+            .build();
       }
       offset += fieldCount;
       belowOffset += side.newInput.getRowType().getFieldCount();
@@ -231,7 +224,6 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
     // Update condition
     final Mapping mapping = (Mapping) Mappings.target(
         new Function<Integer, Integer>() {
-          @Override
           public Integer apply(Integer a0) {
             return map.get(a0);
           }
@@ -242,9 +234,9 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
         RexUtil.apply(mapping, join.getCondition());
 
     // Create new join
-    RelNode newJoin = joinFactory.createJoin(sides.get(0).newInput,
-        sides.get(1).newInput, newCondition, join.getJoinType(),
-        join.getVariablesStopped(), join.isSemiJoinDone());
+    relBuilder.push(sides.get(0).newInput)
+        .push(sides.get(1).newInput)
+        .join(join.getJoinType(), newCondition);
 
     // Aggregate above to sum up the sub-totals
     final List<AggregateCall> newAggCalls = new ArrayList<>();
@@ -252,7 +244,8 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
         aggregate.getGroupCount() + aggregate.getIndicatorCount();
     final int newLeftWidth = sides.get(0).newInput.getRowType().getFieldCount();
     final List<RexNode> projects =
-        new ArrayList<>(rexBuilder.identityProjects(newJoin.getRowType()));
+        new ArrayList<>(
+            rexBuilder.identityProjects(relBuilder.peek().getRowType()));
     for (Ord<AggregateCall> aggCall : Ord.zip(aggregate.getAggCallList())) {
       final SqlAggFunction aggregation = aggCall.e.getAggregation();
       final SqlSplittableAggFunction splitter =
@@ -262,47 +255,45 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
       final Integer rightSubTotal = sides.get(1).split.get(aggCall.i);
       newAggCalls.add(
           splitter.topSplit(rexBuilder, registry(projects),
-              groupIndicatorCount, newJoin.getRowType(), aggCall.e,
+              groupIndicatorCount, relBuilder.peek().getRowType(), aggCall.e,
               leftSubTotal == null ? -1 : leftSubTotal,
               rightSubTotal == null ? -1 : rightSubTotal + newLeftWidth));
     }
-    RelNode r = newJoin;
-  b:
-    if (allColumnsInAggregate && newAggCalls.isEmpty() &&
-      RelOptUtil.areRowTypesEqual(r.getRowType(), aggregate.getRowType(), false)) {
-      // no need to aggregate
-    } else {
-      r = RelOptUtil.createProject(r, projects, null, true,
-              relBuilderFactory.create(aggregate.getCluster(), null));
-      if (allColumnsInAggregate) {
-        // let's see if we can convert
-        List<RexNode> projects2 = new ArrayList<>();
-        for (int key : Mappings.apply(mapping, aggregate.getGroupSet())) {
-          projects2.add(rexBuilder.makeInputRef(r, key));
-        }
-        for (AggregateCall newAggCall : newAggCalls) {
-          final SqlSplittableAggFunction splitter =
-              newAggCall.getAggregation()
-                  .unwrap(SqlSplittableAggFunction.class);
-          if (splitter != null) {
-            projects2.add(
-                splitter.singleton(rexBuilder, r.getRowType(), newAggCall));
-          }
-        }
-        if (projects2.size()
-            == aggregate.getGroupSet().cardinality() + newAggCalls.size()) {
-          // We successfully converted agg calls into projects.
-          r = RelOptUtil.createProject(r, projects2, null, true,
-                  relBuilderFactory.create(aggregate.getCluster(), null));
-          break b;
+
+    relBuilder.project(projects);
+
+    boolean aggConvertedToProjects = false;
+    if (allColumnsInAggregate) {
+      // let's see if we can convert aggregate into projects
+      List<RexNode> projects2 = new ArrayList<>();
+      for (int key : Mappings.apply(mapping, aggregate.getGroupSet())) {
+        projects2.add(relBuilder.field(key));
+      }
+      for (AggregateCall newAggCall : newAggCalls) {
+        final SqlSplittableAggFunction splitter =
+            newAggCall.getAggregation().unwrap(SqlSplittableAggFunction.class);
+        if (splitter != null) {
+          final RelDataType rowType = relBuilder.peek().getRowType();
+          projects2.add(splitter.singleton(rexBuilder, rowType, newAggCall));
         }
       }
-      r = aggregateFactory.createAggregate(r, aggregate.indicator,
-          Mappings.apply(mapping, aggregate.getGroupSet()),
-          Mappings.apply2(mapping, aggregate.getGroupSets()), newAggCalls);
+      if (projects2.size()
+          == aggregate.getGroupSet().cardinality() + newAggCalls.size()) {
+        // We successfully converted agg calls into projects.
+        relBuilder.project(projects2);
+        aggConvertedToProjects = true;
+      }
+    }
+
+    if (!aggConvertedToProjects) {
+      relBuilder.aggregate(
+          relBuilder.groupKey(Mappings.apply(mapping, aggregate.getGroupSet()),
+              Mappings.apply2(mapping, aggregate.getGroupSets())),
+          newAggCalls);
     }
 
     // Make a cost based decision to pick cheaper plan
+    RelNode r = relBuilder.build();
     RelOptCost afterCost = mq.getCumulativeCost(r);
     RelOptCost beforeCost = mq.getCumulativeCost(aggregate);
     if (afterCost.isLt(beforeCost)) {
@@ -316,8 +307,8 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
   private static ImmutableBitSet keyColumns(ImmutableBitSet aggregateColumns,
       ImmutableList<RexNode> predicates) {
     SortedMap<Integer, BitSet> equivalence = new TreeMap<>();
-    for (RexNode pred : predicates) {
-      populateEquivalences(equivalence, pred);
+    for (RexNode predicate : predicates) {
+      populateEquivalences(equivalence, predicate);
     }
     ImmutableBitSet keyColumns = aggregateColumns;
     for (Integer aggregateColumn : aggregateColumns) {
@@ -358,10 +349,9 @@ public class HiveAggregateJoinTransposeRule extends AggregateJoinTransposeRule {
 
   /** Creates a {@link org.apache.calcite.sql.SqlSplittableAggFunction.Registry}
    * that is a view of a list. */
-  private static <E> SqlSplittableAggFunction.Registry<E>
-  registry(final List<E> list) {
+  private static <E> SqlSplittableAggFunction.Registry<E> registry(
+      final List<E> list) {
     return new SqlSplittableAggFunction.Registry<E>() {
-      @Override
       public int register(E e) {
         int i = list.indexOf(e);
         if (i < 0) {

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateProjectMergeRule.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateProjectMergeRule.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateProjectMergeRule.java
index 7c3b4b0..b5f1775 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateProjectMergeRule.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveAggregateProjectMergeRule.java
@@ -20,16 +20,17 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 
-import org.apache.calcite.plan.RelOptRule;
 import org.apache.calcite.plan.RelOptRuleCall;
 import org.apache.calcite.rel.RelNode;
 import org.apache.calcite.rel.core.Aggregate;
+import org.apache.calcite.rel.core.Aggregate.Group;
 import org.apache.calcite.rel.core.AggregateCall;
+import org.apache.calcite.rel.rules.AggregateProjectMergeRule;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexNode;
+import org.apache.calcite.tools.RelBuilder;
 import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelFactories;
-import org.apache.hadoop.hive.ql.optimizer.calcite.HiveRelOptUtil;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveAggregate;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveGroupingID;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveProject;
@@ -48,15 +49,13 @@ import com.google.common.collect.Lists;
  * <p>In some cases, this rule has the effect of trimming: the aggregate will
  * use fewer columns than the project did.
  */
-public class HiveAggregateProjectMergeRule extends RelOptRule {
+public class HiveAggregateProjectMergeRule extends AggregateProjectMergeRule {
   public static final HiveAggregateProjectMergeRule INSTANCE =
       new HiveAggregateProjectMergeRule();
 
   /** Private constructor. */
   private HiveAggregateProjectMergeRule() {
-    super(
-        operand(HiveAggregate.class,
-            operand(HiveProject.class, any())));
+    super(HiveAggregate.class, HiveProject.class, HiveRelFactories.HIVE_BUILDER);
   }
 
   @Override
@@ -72,17 +71,16 @@ public class HiveAggregateProjectMergeRule extends RelOptRule {
     return super.matches(call);
   }
 
-  @Override
   public void onMatch(RelOptRuleCall call) {
     final HiveAggregate aggregate = call.rel(0);
     final HiveProject project = call.rel(1);
-    RelNode x = apply(aggregate, project);
+    RelNode x = apply(call, aggregate, project);
     if (x != null) {
       call.transformTo(x);
     }
   }
 
-  public static RelNode apply(HiveAggregate aggregate,
+  public static RelNode apply(RelOptRuleCall call, HiveAggregate aggregate,
       HiveProject project) {
     final List<Integer> newKeys = Lists.newArrayList();
     final Map<Integer, Integer> map = new HashMap<>();
@@ -100,7 +98,7 @@ public class HiveAggregateProjectMergeRule extends RelOptRule {
 
     final ImmutableBitSet newGroupSet = aggregate.getGroupSet().permute(map);
     ImmutableList<ImmutableBitSet> newGroupingSets = null;
-    if (aggregate.indicator) {
+    if (aggregate.getGroupType() != Group.SIMPLE) {
       newGroupingSets =
           ImmutableBitSet.ORDERING.immutableSortedCopy(
               ImmutableBitSet.permute(aggregate.getGroupSets(), map));
@@ -139,7 +137,8 @@ public class HiveAggregateProjectMergeRule extends RelOptRule {
 
     // Add a project if the group set is not in the same order or
     // contains duplicates.
-    RelNode rel = newAggregate;
+    final RelBuilder relBuilder = call.builder();
+    relBuilder.push(newAggregate);
     if (!newKeys.equals(newGroupSet.asList())) {
       final List<Integer> posList = Lists.newArrayList();
       for (int newKey : newKeys) {
@@ -155,14 +154,12 @@ public class HiveAggregateProjectMergeRule extends RelOptRule {
            i < newAggregate.getRowType().getFieldCount(); i++) {
         posList.add(i);
       }
-      rel = HiveRelOptUtil.createProject(
-          HiveRelFactories.HIVE_BUILDER.create(aggregate.getCluster(), null),
-          rel, posList);
-
+      relBuilder.project(relBuilder.fields(posList));
     }
 
-    return rel;
+    return relBuilder.build();
   }
+
 }
 
-// End AggregateProjectMergeRule.java
+// End HiveAggregateProjectMergeRule.java

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExceptRewriteRule.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExceptRewriteRule.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExceptRewriteRule.java
index b63ea02..5b72dbd 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExceptRewriteRule.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExceptRewriteRule.java
@@ -27,7 +27,6 @@ import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptRule;
 import org.apache.calcite.plan.RelOptRuleCall;
 import org.apache.calcite.rel.RelNode;
-import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
@@ -35,17 +34,13 @@ import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.sql.SqlAggFunction;
-import org.apache.calcite.sql.SqlKind;
-import org.apache.calcite.sql.SqlOperator;
-import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException;
 import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
 import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveAggregate;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveExcept;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveFilter;
-import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveIntersect;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveProject;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveRelNode;
 import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveTableFunctionScan;
@@ -53,12 +48,7 @@ import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveUnion;
 import org.apache.hadoop.hive.ql.optimizer.calcite.translator.SqlFunctionConverter;
 import org.apache.hadoop.hive.ql.optimizer.calcite.translator.TypeConverter;
 import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
-import org.apache.calcite.tools.RelBuilder;
-import org.apache.calcite.util.ImmutableBitSet;
-import org.apache.calcite.util.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -169,7 +159,7 @@ public class HiveExceptRewriteRule extends RelOptRule {
 
     final ImmutableBitSet groupSet = ImmutableBitSet.of(groupSetPositions);
     HiveRelNode aggregateRel = new HiveAggregate(cluster,
-        cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel, false, groupSet, null,
+        cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel, groupSet, null,
         aggregateCalls);
 
     // the schema after GB is like this
@@ -270,7 +260,7 @@ public class HiveExceptRewriteRule extends RelOptRule {
         TypeInfoFactory.longTypeInfo, input.getRowType().getFieldList().size(), aggFnRetType);
     aggregateCalls.add(aggregateCall);
     return new HiveAggregate(cluster, cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel,
-        false, groupSet, null, aggregateCalls);
+        groupSet, null, aggregateCalls);
   }
 
   private RexNode multiply(RexNode r1, RexNode r2, RelOptCluster cluster, RexBuilder rexBuilder)

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExpandDistinctAggregatesRule.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExpandDistinctAggregatesRule.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExpandDistinctAggregatesRule.java
index 81bb730..89c5c23 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExpandDistinctAggregatesRule.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveExpandDistinctAggregatesRule.java
@@ -268,7 +268,7 @@ public final class HiveExpandDistinctAggregatesRule extends RelOptRule {
       aggregateCalls.add(aggregateCall);
     }
     Aggregate aggregate = new HiveAggregate(cluster, cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel,
-        false, ImmutableBitSet.of(), null, aggregateCalls);
+        ImmutableBitSet.of(), null, aggregateCalls);
 
     // create the project after GB. For those repeated values, e.g., select
     // count(distinct x, y), count(distinct y, x), we find the correct mapping.
@@ -330,7 +330,7 @@ public final class HiveExpandDistinctAggregatesRule extends RelOptRule {
             .createSqlType(SqlTypeName.INTEGER), HiveGroupingID.INSTANCE.getName());
     aggregateCalls.add(aggCall);
     return new HiveAggregate(cluster, cluster.traitSetOf(HiveRelNode.CONVENTION),
-        aggregate.getInput(), true, groupSet, origGroupSets, aggregateCalls);
+        aggregate.getInput(), groupSet, origGroupSets, aggregateCalls);
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/hive/blob/9975131c/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveIntersectRewriteRule.java
----------------------------------------------------------------------
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveIntersectRewriteRule.java b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveIntersectRewriteRule.java
index 5b0a7d7..a5d950a 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveIntersectRewriteRule.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/optimizer/calcite/rules/HiveIntersectRewriteRule.java
@@ -27,18 +27,14 @@ import org.apache.calcite.plan.RelOptCluster;
 import org.apache.calcite.plan.RelOptRule;
 import org.apache.calcite.plan.RelOptRuleCall;
 import org.apache.calcite.rel.RelNode;
-import org.apache.calcite.rel.core.Aggregate;
 import org.apache.calcite.rel.core.AggregateCall;
-import org.apache.calcite.rel.core.Intersect;
 import org.apache.calcite.rel.type.RelDataType;
 import org.apache.calcite.rel.type.RelDataTypeField;
 import org.apache.calcite.rex.RexBuilder;
 import org.apache.calcite.rex.RexInputRef;
 import org.apache.calcite.rex.RexLiteral;
 import org.apache.calcite.rex.RexNode;
-import org.apache.calcite.sql.SqlAggFunction;
-import org.apache.calcite.sql.SqlKind;
-import org.apache.calcite.sql.SqlOperator;
+import org.apache.calcite.util.ImmutableBitSet;
 import org.apache.hadoop.hive.ql.optimizer.calcite.CalciteSemanticException;
 import org.apache.hadoop.hive.ql.optimizer.calcite.HiveCalciteUtil;
 import org.apache.hadoop.hive.ql.optimizer.calcite.TraitsUtil;
@@ -52,16 +48,10 @@ import org.apache.hadoop.hive.ql.optimizer.calcite.reloperators.HiveUnion;
 import org.apache.hadoop.hive.ql.optimizer.calcite.translator.SqlFunctionConverter;
 import org.apache.hadoop.hive.ql.optimizer.calcite.translator.TypeConverter;
 import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
 import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
-import org.apache.calcite.tools.RelBuilder;
-import org.apache.calcite.util.ImmutableBitSet;
-import org.apache.calcite.util.Util;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import com.esotericsoftware.minlog.Log;
 import com.google.common.base.Function;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.ImmutableList.Builder;
@@ -140,7 +130,7 @@ public class HiveIntersectRewriteRule extends RelOptRule {
       aggregateCalls.add(aggregateCall);
       
       HiveRelNode aggregateRel = new HiveAggregate(cluster,
-          cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel, false, groupSet, null,
+          cluster.traitSetOf(HiveRelNode.CONVENTION), gbInputRel, groupSet, null,
           aggregateCalls);
       bldr.add(aggregateRel);
     }
@@ -173,7 +163,7 @@ public class HiveIntersectRewriteRule extends RelOptRule {
     
     final ImmutableBitSet groupSet = ImmutableBitSet.of(groupSetPositions);
     HiveRelNode aggregateRel = new HiveAggregate(cluster,
-        cluster.traitSetOf(HiveRelNode.CONVENTION), union, false, groupSet, null, aggregateCalls);
+        cluster.traitSetOf(HiveRelNode.CONVENTION), union, groupSet, null, aggregateCalls);
 
     // add a filter count(c) = #branches
     int countInd = cInd;