You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@impala.apache.org by ta...@apache.org on 2016/11/03 20:36:00 UTC

[1/6] incubator-impala git commit: IMPALA-4374: Use new syntax for creating TPC-DS/H tables in Kudu stress test

Repository: incubator-impala
Updated Branches:
  refs/heads/master 81c5b8150 -> 9755ea63b


IMPALA-4374: Use new syntax for creating TPC-DS/H tables in Kudu
stress test

This commit modifies the DDL statements for creating TPC-DS/H tables in
Kudu. The DDL statements now use the new syntax for creating Kudu tables
(see IMPALA-3719).

Change-Id: I2d501fb9c3cba00b1fb0f7b5941db49cbbda5a53
Reviewed-on: http://gerrit.cloudera.org:8080/4860
Reviewed-by: Dimitris Tsirogiannis <dt...@cloudera.com>
Tested-by: Internal Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/2990696e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/2990696e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/2990696e

Branch: refs/heads/master
Commit: 2990696e08f39795b9a05c98f7753abafb89c02f
Parents: 81c5b81
Author: Dimitris Tsirogiannis <dt...@cloudera.com>
Authored: Wed Oct 26 18:46:36 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 2 23:34:27 2016 +0000

----------------------------------------------------------------------
 testdata/datasets/tpcds/tpcds_kudu_template.sql | 205 ++++++-------------
 testdata/datasets/tpch/tpch_kudu_template.sql   |  77 ++-----
 2 files changed, 77 insertions(+), 205 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/2990696e/testdata/datasets/tpcds/tpcds_kudu_template.sql
----------------------------------------------------------------------
diff --git a/testdata/datasets/tpcds/tpcds_kudu_template.sql b/testdata/datasets/tpcds/tpcds_kudu_template.sql
index dd65fef..430d513 100644
--- a/testdata/datasets/tpcds/tpcds_kudu_template.sql
+++ b/testdata/datasets/tpcds/tpcds_kudu_template.sql
@@ -1,6 +1,7 @@
 ---- Template SQL statements to create and load TPCDS tables in KUDU.
----- TODO: Change to the new syntax for CREATE TABLE statements (IMPALA-3719)
 ---- TODO: Use range partitioning for some tables
+---- TODO: Remove the 'kudu.master_addresses' from TBLPROPERTIES once CM properly sets
+---- the 'kudu_masters' startup option in Impala.
 ---- TODO: Fix the primary key column order
 ---- TODO: Use different number of buckets for fact and dimension tables
 
@@ -28,15 +29,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.store_sales (
   ss_coupon_amt DOUBLE,
   ss_net_paid DOUBLE,
   ss_net_paid_inc_tax DOUBLE,
-  ss_net_profit DOUBLE
+  ss_net_profit DOUBLE,
+  PRIMARY KEY (ss_ticket_number, ss_item_sk)
 )
 DISTRIBUTE BY HASH (ss_ticket_number,ss_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES(
-'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-'kudu.table_name' = '{target_db_name}_store_sales',
-'kudu.master_addresses' = '{kudu_master}:7051',
-'kudu.key_columns' = 'ss_ticket_number, ss_item_sk'
-);
+TBLPROPERTIES ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.store_sales
 SELECT
@@ -99,15 +96,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.web_sales (
   ws_net_paid_inc_tax DOUBLE,
   ws_net_paid_inc_ship DOUBLE,
   ws_net_paid_inc_ship_tax DOUBLE,
-  ws_net_profit DOUBLE
+  ws_net_profit DOUBLE,
+  PRIMARY KEY (wd_order_number, ws_item_sk)
 )
 DISTRIBUTE BY HASH (ws_order_number,ws_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES(
-'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-'kudu.table_name' = '{target_db_name}_web_sales',
-'kudu.master_addresses' = '{kudu_master}:7051',
-'kudu.key_columns' = 'ws_order_number, ws_item_sk'
-);
+TBLPROPERTIES ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.web_sales
 SELECT
@@ -182,15 +175,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.catalog_sales (
   cs_net_paid_inc_tax DOUBLE,
   cs_net_paid_inc_ship DOUBLE,
   cs_net_paid_inc_ship_tax DOUBLE,
-  cs_net_profit DOUBLE
+  cs_net_profit DOUBLE,
+  PRIMARY KEY (cs_order_number, cs_item_sk)
 )
 DISTRIBUTE BY HASH (cs_order_number,cs_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES(
-'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-'kudu.table_name' = '{target_db_name}_catalog_sales',
-'kudu.master_addresses' = '{kudu_master}:7051',
-'kudu.key_columns' = 'cs_order_number, cs_item_sk'
-);
+TBLPROPERTIES ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.catalog_sales
 SELECT
@@ -251,14 +240,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.store_returns (
   sr_refunded_cash DOUBLE,
   sr_reversed_charge DOUBLE,
   sr_store_credit DOUBLE,
-  sr_net_loss DOUBLE
+  sr_net_loss DOUBLE,
+  PRIMARY KEY (sr_ticket_number, sr_item_sk)
 )
 DISTRIBUTE BY HASH (sr_ticket_number,sr_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='sr_ticket_number, sr_item_sk',
-'kudu.table_name'='{target_db_name}_store_returns',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.store_returns
 SELECT
@@ -309,14 +295,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.web_returns (
   wr_refunded_cash DOUBLE,
   wr_reversed_charge DOUBLE,
   wr_account_credit DOUBLE,
-  wr_net_loss DOUBLE
+  wr_net_loss DOUBLE,
+  PRIMARY KEY (wr_order_number, wr_item_sk)
 )
 DISTRIBUTE BY HASH (wr_order_number,wr_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='wr_order_number, wr_item_sk',
-'kudu.table_name'='{target_db_name}_web_returns',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.web_returns
 SELECT
@@ -374,14 +357,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.catalog_returns (
   cr_refunded_cash DOUBLE,
   cr_reversed_charge DOUBLE,
   cr_store_credit DOUBLE,
-  cr_net_loss DOUBLE
+  cr_net_loss DOUBLE,
+  PRIMARY KEY (cr_order_number, cr_item_sk)
 )
 DISTRIBUTE BY HASH (cr_order_number,cr_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='cr_order_number, cr_item_sk',
-'kudu.table_name'='{target_db_name}_catalog_returns',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.catalog_returns
 SELECT
@@ -419,21 +399,18 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.inventory (
   inv_date_sk BIGINT,
   inv_item_sk BIGINT,
   inv_warehouse_sk BIGINT,
-  inv_quantity_on_hand BIGINT
+  inv_quantity_on_hand BIGINT,
+  PRIMARY KEY (inv_date_sk, inv_item_sk, inv_warehouse_sk)
 )
 DISTRIBUTE BY HASH (inv_item_sk,inv_date_sk,inv_warehouse_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='inv_date_sk,inv_item_sk,inv_warehouse_sk',
-'kudu.table_name'='{target_db_name}_inventory',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.inventory SELECT * FROM {source_db_name}.inventory;
 
 ---- CUSTOMER
 
 CREATE TABLE {target_db_name}.customer (
-  c_customer_sk BIGINT,
+  c_customer_sk BIGINT PRIMARY KEY,
   c_customer_id STRING,
   c_current_cdemo_sk BIGINT,
   c_current_hdemo_sk BIGINT,
@@ -453,17 +430,13 @@ CREATE TABLE {target_db_name}.customer (
   c_last_review_date BIGINT
 )
 DISTRIBUTE BY HASH (c_customer_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='c_customer_sk',
-'kudu.table_name'='{target_db_name}_customer',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.customer SELECT * FROM {source_db_name}.customer;
 
 ---- CUSTOMER_ADDRESS
 CREATE TABLE IF NOT EXISTS {target_db_name}.customer_address (
-  ca_address_sk BIGINT,
+  ca_address_sk BIGINT PRIMARY KEY,
   ca_address_id STRING,
   ca_street_number STRING,
   ca_street_name STRING,
@@ -478,18 +451,14 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.customer_address (
   ca_location_type STRING
 )
 DISTRIBUTE BY HASH (ca_address_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='ca_address_sk',
-'kudu.table_name'='{target_db_name}_customer_address',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.customer_address
 SELECT * FROM {source_db_name}.customer_address;
 
 ---- CUSTOMER_DEMOGRAPHICS
 CREATE TABLE IF NOT EXISTS {target_db_name}.customer_demographics (
-  cd_demo_sk BIGINT,
+  cd_demo_sk BIGINT PRIMARY KEY,
   cd_gender STRING,
   cd_marital_status STRING,
   cd_education_status STRING,
@@ -500,18 +469,14 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.customer_demographics (
   cd_dep_college_count BIGINT
 )
 DISTRIBUTE BY HASH (cd_demo_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='cd_demo_sk',
-'kudu.table_name'='{target_db_name}_customer_demographics',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.customer_demographics
 SELECT * FROM {source_db_name}.customer_demographics;
 
 ---- DATE_DIM
 CREATE TABLE IF NOT EXISTS {target_db_name}.date_dim (
-  d_date_sk BIGINT,
+  d_date_sk BIGINT PRIMARY KEY,
   d_date_id STRING,
   d_date STRING,
   d_month_seq BIGINT,
@@ -541,35 +506,27 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.date_dim (
   d_current_year STRING
 )
 DISTRIBUTE BY HASH (d_date_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='d_date_sk',
-'kudu.table_name'='{target_db_name}_date_dim',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.date_dim SELECT * FROM {source_db_name}.date_dim;
 
 ---- HOUSEHOLD_DEMOGRAPHICS
 CREATE TABLE IF NOT EXISTS {target_db_name}.household_demographics (
-  hd_demo_sk BIGINT,
+  hd_demo_sk BIGINT PRIMARY KEY,
   hd_income_band_sk BIGINT,
   hd_buy_potential STRING,
   hd_dep_count BIGINT,
   hd_vehicle_count BIGINT
 )
 DISTRIBUTE BY HASH (hd_demo_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='hd_demo_sk',
-'kudu.table_name'='{target_db_name}_household_demographics',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.household_demographics
 SELECT * FROM {source_db_name}.household_demographics;
 
 ---- ITEM
 CREATE TABLE IF NOT EXISTS {target_db_name}.item (
-  i_item_sk BIGINT,
+  i_item_sk BIGINT PRIMARY KEY,
   i_item_id STRING,
   i_rec_start_date STRING,
   i_rec_end_date STRING,
@@ -593,17 +550,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.item (
   i_product_name STRING
 )
 DISTRIBUTE BY HASH (i_item_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='i_item_sk',
-'kudu.table_name'='{target_db_name}_item',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.item SELECT * FROM {source_db_name}.item;
 
 ---- PROMOTION
 CREATE TABLE IF NOT EXISTS {target_db_name}.promotion (
-  p_promo_sk BIGINT,
+  p_promo_sk BIGINT PRIMARY KEY,
   p_item_sk BIGINT,
   p_start_date_sk BIGINT,
   p_end_date_sk BIGINT,
@@ -624,11 +577,7 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.promotion (
   p_discount_active STRING
 )
 DISTRIBUTE BY HASH (p_promo_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='p_promo_sk',
-'kudu.table_name'='{target_db_name}_promotion',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.promotion
 SELECT
@@ -655,7 +604,7 @@ FROM {source_db_name}.promotion;
 
 ---- STORE
 CREATE TABLE IF NOT EXISTS {target_db_name}.store (
-  s_store_sk BIGINT,
+  s_store_sk BIGINT PRIMARY KEY,
   s_store_id STRING,
   s_rec_start_date STRING,
   s_rec_end_date STRING,
@@ -686,17 +635,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.store (
   s_tax_precentage DOUBLE
 )
 DISTRIBUTE BY HASH (s_store_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='s_store_sk',
-'kudu.table_name'='{target_db_name}_store',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.store SELECT * FROM {source_db_name}.store;
 
 ---- TIME_DIM
 CREATE TABLE IF NOT EXISTS {target_db_name}.time_dim (
-  t_time_sk BIGINT,
+  t_time_sk BIGINT PRIMARY KEY,
   t_time_id STRING,
   t_time BIGINT,
   t_hour BIGINT,
@@ -708,17 +653,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.time_dim (
   t_meal_time STRING
 )
 DISTRIBUTE BY HASH (t_time_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='t_time_sk',
-'kudu.table_name'='{target_db_name}_time_dim',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.time_dim SELECT * FROM {source_db_name}.time_dim;
 
 ---- CALL_CENTER
 CREATE TABLE IF NOT EXISTS {target_db_name}.call_center (
-  cc_call_center_sk BIGINT,
+  cc_call_center_sk BIGINT PRIMARY KEY,
   cc_call_center_id STRING,
   cc_rec_start_date STRING,
   cc_rec_end_date STRING,
@@ -751,17 +692,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.call_center (
   cc_tax_percentage DOUBLE
 )
 DISTRIBUTE BY HASH (cc_call_center_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='cc_call_center_sk',
-'kudu.table_name'='{target_db_name}_call_center',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.call_center SELECT * FROM {source_db_name}.call_center;
 
 ---- CATALOG_PAGE
 CREATE TABLE IF NOT EXISTS {target_db_name}.catalog_page (
-  cp_catalog_page_sk BIGINT,
+  cp_catalog_page_sk BIGINT PRIMARY KEY,
   cp_catalog_page_id STRING,
   cp_start_date_sk BIGINT,
   cp_end_date_sk BIGINT,
@@ -772,47 +709,35 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.catalog_page (
   cp_type STRING
 )
 DISTRIBUTE BY HASH (cp_catalog_page_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='cp_catalog_page_sk',
-'kudu.table_name'='{target_db_name}_catalog_page',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.catalog_page SELECT * FROM {source_db_name}.catalog_page;
 
 ---- INCOME_BANDS
 CREATE TABLE IF NOT EXISTS {target_db_name}.income_band (
-  ib_income_band_sk BIGINT,
+  ib_income_band_sk BIGINT PRIMARY KEY,
   ib_lower_bound BIGINT,
   ib_upper_bound BIGINT
 )
 DISTRIBUTE BY HASH (ib_income_band_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='ib_income_band_sk',
-'kudu.table_name'='{target_db_name}_income_band',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.income_band SELECT * FROM {source_db_name}.income_band;
 
 ---- REASON
 CREATE TABLE IF NOT EXISTS {target_db_name}.reason (
-  r_reason_sk BIGINT,
+  r_reason_sk BIGINT PRIMARY KEY,
   r_reason_id STRING,
   r_reason_desc STRING
 )
 DISTRIBUTE BY HASH (r_reason_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='r_reason_sk',
-'kudu.table_name'='{target_db_name}_reason',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.reason SELECT * FROM {source_db_name}.reason;
 
 ---- SHIP_MODE
 CREATE TABLE IF NOT EXISTS {target_db_name}.ship_mode (
-  sm_ship_mode_sk BIGINT,
+  sm_ship_mode_sk BIGINT PRIMARY KEY,
   sm_ship_mode_id STRING,
   sm_type STRING,
   sm_code STRING,
@@ -820,17 +745,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.ship_mode (
   sm_contract STRING
 )
 DISTRIBUTE BY HASH (sm_ship_mode_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='sm_ship_mode_sk',
-'kudu.table_name'='{target_db_name}_ship_mode',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.ship_mode SELECT * FROM {source_db_name}.ship_mode;
 
 ---- WAREHOUSE
 CREATE TABLE IF NOT EXISTS {target_db_name}.warehouse (
-  w_warehouse_sk BIGINT,
+  w_warehouse_sk BIGINT PRIMARY KEY,
   w_warehouse_id STRING,
   w_warehouse_name STRING,
   w_warehouse_sq_ft BIGINT,
@@ -846,17 +767,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.warehouse (
   w_gmt_offset DOUBLE
 )
 DISTRIBUTE BY HASH (w_warehouse_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='w_warehouse_sk',
-'kudu.table_name'='{target_db_name}_warehouse',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.warehouse SELECT * FROM {source_db_name}.warehouse;
 
 ---- WEB_PAGE
 CREATE TABLE IF NOT EXISTS {target_db_name}.web_page (
-  wp_web_page_sk BIGINT,
+  wp_web_page_sk BIGINT PRIMARY KEY,
   wp_web_page_id STRING,
   wp_rec_start_date STRING,
   wp_rec_end_date STRING,
@@ -872,17 +789,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.web_page (
   wp_max_ad_count BIGINT
 )
 DISTRIBUTE BY HASH (wp_web_page_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='wp_web_page_sk',
-'kudu.table_name'='{target_db_name}_web_page',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.web_page SELECT * FROM {source_db_name}.web_page;
 
 ---- WEB_SITE
 CREATE TABLE IF NOT EXISTS {target_db_name}.web_site (
-  web_site_sk BIGINT,
+  web_site_sk BIGINT PRIMARY KEY,
   web_site_id STRING,
   web_rec_start_date STRING,
   web_rec_end_date STRING,
@@ -910,11 +823,7 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.web_site (
   web_tax_percentage DOUBLE
 )
 DISTRIBUTE BY HASH (web_site_sk) INTO {buckets} BUCKETS
-TBLPROPERTIES (
-'kudu.master_addresses'='{kudu_master}:7051',
-'kudu.key_columns'='web_site_sk',
-'kudu.table_name'='{target_db_name}_web_site',
-'storage_handler'='com.cloudera.kudu.hive.KuduStorageHandler');
+TBLPROPERTIES ('kudu.master_addresses'='{kudu_master}:7051');
 
 INSERT INTO {target_db_name}.web_site SELECT * FROM {source_db_name}.web_site;
 

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/2990696e/testdata/datasets/tpch/tpch_kudu_template.sql
----------------------------------------------------------------------
diff --git a/testdata/datasets/tpch/tpch_kudu_template.sql b/testdata/datasets/tpch/tpch_kudu_template.sql
index 5abde0b..eb64349 100644
--- a/testdata/datasets/tpch/tpch_kudu_template.sql
+++ b/testdata/datasets/tpch/tpch_kudu_template.sql
@@ -1,6 +1,7 @@
 ---- Template SQL statements to create and load TPCH tables in KUDU.
----- TODO: Change to the new syntax for CREATE TABLE statements (IMPALA-3719)
 ---- TODO: Fix the primary key column order
+---- TODO: Remove the 'kudu.master_addresses' from TBLPROPERTIES once CM properly sets
+---- the 'kudu_masters' startup option in Impala.
 ---- TODO: Remove the CREATE_KUDU sections from tpch_schema_template.sql and use
 ---- this file instead for loading TPC-H data in Kudu.
 
@@ -21,15 +22,11 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.lineitem (
   L_RECEIPTDATE STRING,
   L_SHIPINSTRUCT STRING,
   L_SHIPMODE STRING,
-  L_COMMENT STRING
+  L_COMMENT STRING,
+  PRIMARY KEY (L_ORDERKEY, L_LINENUMBER)
 )
 distribute by hash (l_orderkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_lineitem',
-  'kudu.key_columns' = 'l_orderkey, l_linenumber'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.lineitem
 SELECT
@@ -53,7 +50,7 @@ FROM {source_db_name}.lineitem;
 
 ---- PART
 CREATE TABLE IF NOT EXISTS {target_db_name}.part (
-  P_PARTKEY BIGINT,
+  P_PARTKEY BIGINT PRIMARY KEY,
   P_NAME STRING,
   P_MFGR STRING,
   P_BRAND STRING,
@@ -64,12 +61,7 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.part (
   P_COMMENT STRING
 )
 distribute by hash (p_partkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_part',
-  'kudu.key_columns' = 'p_partkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.part SELECT * FROM {source_db_name}.part;
 
@@ -79,21 +71,17 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.partsupp (
   PS_SUPPKEY BIGINT,
   PS_AVAILQTY BIGINT,
   PS_SUPPLYCOST DOUBLE,
-  PS_COMMENT STRING
+  PS_COMMENT STRING,
+  PRIMARY KEY (PS_PARTKEY, PS_SUPPKEY)
 )
 distribute by hash (ps_partkey, ps_suppkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_partsupp',
-  'kudu.key_columns' = 'ps_partkey, ps_suppkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.partsupp SELECT * FROM {source_db_name}.partsupp;
 
 ---- SUPPLIER
 CREATE TABLE IF NOT EXISTS {target_db_name}.supplier (
-  S_SUPPKEY BIGINT,
+  S_SUPPKEY BIGINT PRIMARY KEY,
   S_NAME STRING,
   S_ADDRESS STRING,
   S_NATIONKEY BIGINT,
@@ -102,51 +90,36 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.supplier (
   S_COMMENT STRING
 )
 distribute by hash (s_suppkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_supplier',
-  'kudu.key_columns' = 's_suppkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.supplier SELECT * FROM {source_db_name}.supplier;
 
 ---- NATION
 CREATE TABLE IF NOT EXISTS {target_db_name}.nation (
-  N_NATIONKEY BIGINT,
+  N_NATIONKEY BIGINT PRIMARY KEY,
   N_NAME STRING,
   N_REGIONKEY BIGINT,
   N_COMMENT STRING
 )
 distribute by hash (n_nationkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_nation',
-  'kudu.key_columns' = 'n_nationkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.nation SELECT * FROM {source_db_name}.nation;
 
 ---- REGION
 CREATE TABLE IF NOT EXISTS {target_db_name}.region (
-  R_REGIONKEY BIGINT,
+  R_REGIONKEY BIGINT PRIMARY KEY,
   R_NAME STRING,
   R_COMMENT STRING
 )
 distribute by hash (r_regionkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_region',
-  'kudu.key_columns' = 'r_regionkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.region SELECT * FROM {source_db_name}.region;
 
 ---- ORDERS
 CREATE TABLE IF NOT EXISTS {target_db_name}.orders (
-  O_ORDERKEY BIGINT,
+  O_ORDERKEY BIGINT PRIMARY KEY,
   O_CUSTKEY BIGINT,
   O_ORDERSTATUS STRING,
   O_TOTALPRICE DOUBLE,
@@ -157,18 +130,13 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.orders (
   O_COMMENT STRING
 )
 distribute by hash (o_orderkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_orders',
-  'kudu.key_columns' = 'o_orderkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.orders SELECT * FROM {source_db_name}.orders;
 
 ---- CUSTOMER
 CREATE TABLE IF NOT EXISTS {target_db_name}.customer (
-  C_CUSTKEY BIGINT,
+  C_CUSTKEY BIGINT PRIMARY KEY,
   C_NAME STRING,
   C_ADDRESS STRING,
   C_NATIONKEY BIGINT,
@@ -178,12 +146,7 @@ CREATE TABLE IF NOT EXISTS {target_db_name}.customer (
   C_COMMENT STRING
 )
 distribute by hash (c_custkey) into {buckets} buckets
-tblproperties(
-  'storage_handler' = 'com.cloudera.kudu.hive.KuduStorageHandler',
-  'kudu.master_addresses' = '{kudu_master}:7051',
-  'kudu.table_name' = '{target_db_name}_customer',
-  'kudu.key_columns' = 'c_custkey'
-);
+tblproperties ('kudu.master_addresses' = '{kudu_master}:7051');
 
 INSERT INTO TABLE {target_db_name}.customer SELECT * FROM {source_db_name}.customer;
 


[2/6] incubator-impala git commit: IMPALA-4336: Cast exprs after unnesting union operands.

Posted by ta...@apache.org.
IMPALA-4336: Cast exprs after unnesting union operands.

The bug was that we cast the result exprs of operands before
unnesting them. If we unnested an operands, casts were missing
on those unnested operands' result exprs.

The fix is to first unnest operands and then cast result exprs.

Also clarifies the use of resultExprs vs. baseTblResultExprs.

Change-Id: I5e3ab7349df7d67d0d9c2baf4a56342d3f04e76d
Reviewed-on: http://gerrit.cloudera.org:8080/4815
Reviewed-by: Alex Behm <al...@cloudera.com>
Tested-by: Internal Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/795c085f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/795c085f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/795c085f

Branch: refs/heads/master
Commit: 795c085fa38980085e830ce46ee8ccf298849dcb
Parents: 2990696
Author: Alex Behm <al...@cloudera.com>
Authored: Fri Oct 21 18:58:36 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Thu Nov 3 08:59:45 2016 +0000

----------------------------------------------------------------------
 .../java/org/apache/impala/analysis/Expr.java   |  21 ++-
 .../org/apache/impala/analysis/UnionStmt.java   | 171 ++++++++++---------
 .../impala/planner/SingleNodePlanner.java       |   4 +-
 .../org/apache/impala/planner/UnionNode.java    |  17 +-
 .../queries/QueryTest/union.test                |  28 +++
 5 files changed, 137 insertions(+), 104 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/795c085f/fe/src/main/java/org/apache/impala/analysis/Expr.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/Expr.java b/fe/src/main/java/org/apache/impala/analysis/Expr.java
index 23ae65f..fd7f86f 100644
--- a/fe/src/main/java/org/apache/impala/analysis/Expr.java
+++ b/fe/src/main/java/org/apache/impala/analysis/Expr.java
@@ -1110,15 +1110,20 @@ abstract public class Expr extends TreeNode<Expr> implements ParseNode, Cloneabl
    * Otherwise returns null.
    */
   public SlotRef unwrapSlotRef(boolean implicitOnly) {
-    if (this instanceof SlotRef) {
-      return (SlotRef) this;
-    } else if (this instanceof CastExpr
-        && (!implicitOnly || ((CastExpr) this).isImplicit())
-        && getChild(0) instanceof SlotRef) {
-      return (SlotRef) getChild(0);
-    } else {
-      return null;
+    Expr unwrappedExpr = unwrapExpr(implicitOnly);
+    if (unwrappedExpr instanceof SlotRef) return (SlotRef) unwrappedExpr;
+    return null;
+  }
+
+  /**
+   * Returns the first child if this Expr is a CastExpr. Otherwise, returns 'this'.
+   */
+  public Expr unwrapExpr(boolean implicitOnly) {
+    if (this instanceof CastExpr
+        && (!implicitOnly || ((CastExpr) this).isImplicit())) {
+      return children_.get(0);
     }
+    return this;
   }
 
   /**

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/795c085f/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java b/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
index 4f65e0f..fffb72c 100644
--- a/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
@@ -20,21 +20,27 @@ package org.apache.impala.analysis;
 import java.util.ArrayList;
 import java.util.List;
 
+import org.apache.impala.catalog.ColumnStats;
+import org.apache.impala.common.AnalysisException;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import org.apache.impala.catalog.ColumnStats;
-import org.apache.impala.common.AnalysisException;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
 /**
  * Representation of a union with its list of operands, and optional order by and limit.
- * A union materializes its results, and its resultExprs are slotrefs into the
+ * A union materializes its results, and its resultExprs are SlotRefs into a new
  * materialized tuple.
  * During analysis, the operands are normalized (separated into a single sequence of
  * DISTINCT followed by a single sequence of ALL operands) and unnested to the extent
  * possible. This also creates the AggregationInfo for DISTINCT operands.
+ *
+ * Use of resultExprs vs. baseTblResultExprs:
+ * We consistently use/cast the resultExprs of union operands because the final expr
+ * substitution happens during planning. The only place where baseTblResultExprs are
+ * used is in materializeRequiredSlots() because that is called before plan generation
+ * and we need to mark the slots of resolved exprs as materialized.
  */
 public class UnionStmt extends QueryStmt {
   private final static Logger LOG = LoggerFactory.getLogger(UnionStmt.class);
@@ -198,10 +204,6 @@ public class UnionStmt extends QueryStmt {
     allOperands_.clear();
   }
 
-  /**
-   * Propagates DISTINCT from left to right, and checks that all
-   * union operands are union compatible, adding implicit casts if necessary.
-   */
   @Override
   public void analyze(Analyzer analyzer) throws AnalysisException {
     if (isAnalyzed()) return;
@@ -212,43 +214,21 @@ public class UnionStmt extends QueryStmt {
     }
     Preconditions.checkState(operands_.size() > 0);
 
-    // Propagates DISTINCT from right to left
+    // Propagates DISTINCT from right to left.
     propagateDistinct();
 
-    // Make sure all operands return an equal number of exprs.
-    QueryStmt firstQuery = operands_.get(0).getQueryStmt();
-
-    try {
-      operands_.get(0).analyze(analyzer);
-    } catch (AnalysisException e) {
-      if (analyzer.getMissingTbls().isEmpty()) throw e;
-    }
+    // Analyze all operands and make sure they return an equal number of exprs.
+    analyzeOperands(analyzer);
 
-    List<List<Expr>> resultExprLists = Lists.newArrayList();
-    List<Expr> firstQueryExprs = firstQuery.getBaseTblResultExprs();
-    resultExprLists.add(firstQueryExprs);
-    for (int i = 1; i < operands_.size(); ++i) {
-      QueryStmt query = operands_.get(i).getQueryStmt();
-      try {
-        operands_.get(i).analyze(analyzer);
-        List<Expr> exprs = query.getBaseTblResultExprs();
-        if (firstQueryExprs.size() != exprs.size()) {
-          throw new AnalysisException("Operands have unequal number of columns:\n" +
-              "'" + queryStmtToSql(firstQuery) + "' has " +
-              firstQueryExprs.size() + " column(s)\n" +
-              "'" + queryStmtToSql(query) + "' has " + exprs.size() + " column(s)");
-        }
-        resultExprLists.add(exprs);
-      } catch (AnalysisException e) {
-        if (analyzer.getMissingTbls().isEmpty()) throw e;
-      }
-    }
+    // Remember the SQL string before unnesting operands.
+    toSqlString_ = toSql();
 
-    if (!analyzer.getMissingTbls().isEmpty()) {
-      throw new AnalysisException("Found missing tables. Aborting analysis.");
-    }
+    // Unnest the operands before casting the result exprs. Unnesting may add
+    // additional entries to operands_ and the result exprs of those unnested
+    // operands must also be cast properly.
+    unnestOperands(analyzer);
 
-    // compute hasAnalyticExprs_
+    // Compute hasAnalyticExprs_
     hasAnalyticExprs_ = false;
     for (UnionOperand op: operands_) {
       if (op.hasAnalyticExprs()) {
@@ -257,20 +237,69 @@ public class UnionStmt extends QueryStmt {
       }
     }
 
+    // Collect all result expr lists and cast the exprs as necessary.
+    List<List<Expr>> resultExprLists = Lists.newArrayList();
+    for (UnionOperand op: operands_) {
+      resultExprLists.add(op.getQueryStmt().getResultExprs());
+    }
     analyzer.castToUnionCompatibleTypes(resultExprLists);
 
-    // Create tuple descriptor materialized by this UnionStmt,
-    // its resultExprs, and its sortInfo if necessary.
+    // Create tuple descriptor materialized by this UnionStmt, its resultExprs, and
+    // its sortInfo if necessary.
     createMetadata(analyzer);
     createSortInfo(analyzer);
-    toSqlString_ = toSql();
 
-    unnestOperands(analyzer);
+    // Create unnested operands' smaps.
+    for (UnionOperand operand: operands_) setOperandSmap(operand, analyzer);
+
+    // Create distinctAggInfo, if necessary.
+    if (!distinctOperands_.isEmpty()) {
+      // Aggregate produces exactly the same tuple as the original union stmt.
+      ArrayList<Expr> groupingExprs = Expr.cloneList(resultExprs_);
+      try {
+        distinctAggInfo_ =
+            AggregateInfo.create(groupingExprs, null,
+              analyzer.getDescTbl().getTupleDesc(tupleId_), analyzer);
+      } catch (AnalysisException e) {
+        // Should never happen.
+        throw new IllegalStateException(
+            "Error creating agg info in UnionStmt.analyze()", e);
+      }
+    }
+
     if (evaluateOrderBy_) createSortTupleInfo(analyzer);
     baseTblResultExprs_ = resultExprs_;
   }
 
   /**
+   * Analyzes all operands and checks that they return an equal number of exprs.
+   * Throws an AnalysisException if that is not the case, or if analyzing
+   * an operand fails.
+   */
+  private void analyzeOperands(Analyzer analyzer) throws AnalysisException {
+    for (int i = 0; i < operands_.size(); ++i) {
+      try {
+        operands_.get(i).analyze(analyzer);
+        QueryStmt firstQuery = operands_.get(0).getQueryStmt();
+        List<Expr> firstExprs = operands_.get(0).getQueryStmt().getResultExprs();
+        QueryStmt query = operands_.get(i).getQueryStmt();
+        List<Expr> exprs = query.getResultExprs();
+        if (firstExprs.size() != exprs.size()) {
+          throw new AnalysisException("Operands have unequal number of columns:\n" +
+              "'" + queryStmtToSql(firstQuery) + "' has " +
+              firstExprs.size() + " column(s)\n" +
+              "'" + queryStmtToSql(query) + "' has " + exprs.size() + " column(s)");
+        }
+      } catch (AnalysisException e) {
+        if (analyzer.getMissingTbls().isEmpty()) throw e;
+      }
+    }
+    if (!analyzer.getMissingTbls().isEmpty()) {
+      throw new AnalysisException("Found missing tables. Aborting analysis.");
+    }
+  }
+
+  /**
    * Marks the baseTblResultExprs of its operands as materialized, based on
    * which of the output slots have been marked.
    * Calls materializeRequiredSlots() on the operands themselves.
@@ -278,17 +307,11 @@ public class UnionStmt extends QueryStmt {
   @Override
   public void materializeRequiredSlots(Analyzer analyzer) {
     TupleDescriptor tupleDesc = analyzer.getDescTbl().getTupleDesc(tupleId_);
-    if (!distinctOperands_.isEmpty()) {
-      // to keep things simple we materialize all grouping exprs = output slots,
-      // regardless of what's being referenced externally
-      for (SlotDescriptor slotDesc: tupleDesc.getSlots()) {
-        slotDesc.setIsMaterialized(true);
-      }
-    }
+    // to keep things simple we materialize all grouping exprs = output slots,
+    // regardless of what's being referenced externally
+    if (!distinctOperands_.isEmpty()) tupleDesc.materializeSlots();
 
-    if (evaluateOrderBy_) {
-      sortInfo_.materializeRequiredSlots(analyzer, null);
-    }
+    if (evaluateOrderBy_) sortInfo_.materializeRequiredSlots(analyzer, null);
 
     // collect operands' result exprs
     List<SlotDescriptor> outputSlots = tupleDesc.getSlots();
@@ -320,7 +343,6 @@ public class UnionStmt extends QueryStmt {
     if (operands_.size() == 1) {
       // ValuesStmt for a single row.
       allOperands_.add(operands_.get(0));
-      setOperandSmap(operands_.get(0), analyzer);
       return;
     }
 
@@ -352,50 +374,33 @@ public class UnionStmt extends QueryStmt {
     operands_.clear();
     operands_.addAll(distinctOperands_);
     operands_.addAll(allOperands_);
-
-    // create unnested operands' smaps
-    for (UnionOperand operand: operands_) {
-      setOperandSmap(operand, analyzer);
-    }
-
-    // create distinctAggInfo, if necessary
-    if (!distinctOperands_.isEmpty()) {
-      // Aggregate produces exactly the same tuple as the original union stmt.
-      ArrayList<Expr> groupingExprs = Expr.cloneList(resultExprs_);
-      try {
-        distinctAggInfo_ =
-            AggregateInfo.create(groupingExprs, null,
-              analyzer.getDescTbl().getTupleDesc(tupleId_), analyzer);
-      } catch (AnalysisException e) {
-        // this should never happen
-        throw new AnalysisException("error creating agg info in UnionStmt.analyze()");
-      }
-    }
   }
 
   /**
    * Sets the smap for the given operand. It maps from the output slots this union's
-   * tuple to the corresponding base table exprs of the operand.
+   * tuple to the corresponding result exprs of the operand.
    */
   private void setOperandSmap(UnionOperand operand, Analyzer analyzer) {
     TupleDescriptor tupleDesc = analyzer.getDescTbl().getTupleDesc(tupleId_);
     // operands' smaps were already set in the operands' analyze()
     operand.getSmap().clear();
+    List<Expr> resultExprs = operand.getQueryStmt().getResultExprs();
+    Preconditions.checkState(resultExprs.size() == tupleDesc.getSlots().size());
     for (int i = 0; i < tupleDesc.getSlots().size(); ++i) {
       SlotDescriptor outputSlot = tupleDesc.getSlots().get(i);
-      operand.getSmap().put(
-          new SlotRef(outputSlot),
-          // TODO: baseTblResultExprs?
-          operand.getQueryStmt().getResultExprs().get(i).clone());
+      // Map to the original (uncast) result expr of the operand.
+      Expr origExpr = resultExprs.get(i).unwrapExpr(true).clone();
+      operand.getSmap().put(new SlotRef(outputSlot), origExpr);
     }
   }
 
   /**
-   * Add a single operand to the target list; if the operand itself is a UnionStmt,
-   * apply unnesting to the extent possible (possibly modifying 'operand' in the process).
+   * Add a single operand to the target list; if the operand itself is a UnionStmt, apply
+   * unnesting to the extent possible (possibly modifying 'operand' in the process).
    */
   private void unnestOperand(
       List<UnionOperand> target, Qualifier targetQualifier, UnionOperand operand) {
+    Preconditions.checkState(operand.isAnalyzed());
     QueryStmt queryStmt = operand.getQueryStmt();
     if (queryStmt instanceof SelectStmt) {
       target.add(operand);
@@ -462,12 +467,12 @@ public class UnionStmt extends QueryStmt {
     LOG.trace("UnionStmt.createMetadata: tupleId=" + tupleId_.toString());
 
     // One slot per expr in the select blocks. Use first select block as representative.
-    List<Expr> firstSelectExprs = operands_.get(0).getQueryStmt().getBaseTblResultExprs();
+    List<Expr> firstSelectExprs = operands_.get(0).getQueryStmt().getResultExprs();
 
     // Compute column stats for the materialized slots from the source exprs.
     List<ColumnStats> columnStats = Lists.newArrayList();
     for (int i = 0; i < operands_.size(); ++i) {
-      List<Expr> selectExprs = operands_.get(i).getQueryStmt().getBaseTblResultExprs();
+      List<Expr> selectExprs = operands_.get(i).getQueryStmt().getResultExprs();
       for (int j = 0; j < selectExprs.size(); ++j) {
         ColumnStats statsToAdd = ColumnStats.fromExpr(selectExprs.get(j));
         if (i == 0) {
@@ -503,7 +508,7 @@ public class UnionStmt extends QueryStmt {
       // don't do that if the operand computes analytic exprs
       // (see Planner.createInlineViewPlan() for the reasoning)
       for (UnionOperand op: operands_) {
-        Expr resultExpr = op.getQueryStmt().getBaseTblResultExprs().get(i);
+        Expr resultExpr = op.getQueryStmt().getResultExprs().get(i);
         slotDesc.addSourceExpr(resultExpr);
         if (op.hasAnalyticExprs()) continue;
         SlotRef slotRef = resultExpr.unwrapSlotRef(true);

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/795c085f/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
index 434e36d..9b0e376 100644
--- a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
@@ -1523,7 +1523,7 @@ public class SingleNodePlanner {
       if (queryStmt instanceof SelectStmt) {
         SelectStmt selectStmt = (SelectStmt) queryStmt;
         if (selectStmt.getTableRefs().isEmpty()) {
-          unionNode.addConstExprList(selectStmt.getBaseTblResultExprs());
+          unionNode.addConstExprList(selectStmt.getResultExprs());
           continue;
         }
       }
@@ -1532,7 +1532,7 @@ public class SingleNodePlanner {
       // Place them into a SelectNode on top of the operand's plan.
       opPlan = addUnassignedConjuncts(analyzer, opPlan.getTupleIds(), opPlan);
       if (opPlan instanceof EmptySetNode) continue;
-      unionNode.addChild(opPlan, op.getQueryStmt().getBaseTblResultExprs());
+      unionNode.addChild(opPlan, op.getQueryStmt().getResultExprs());
     }
 
     if (unionDistinctPlan != null) {

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/795c085f/fe/src/main/java/org/apache/impala/planner/UnionNode.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/UnionNode.java b/fe/src/main/java/org/apache/impala/planner/UnionNode.java
index a451ba0..a085973 100644
--- a/fe/src/main/java/org/apache/impala/planner/UnionNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/UnionNode.java
@@ -22,9 +22,6 @@ import java.util.Collections;
 import java.util.Comparator;
 import java.util.List;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.SlotDescriptor;
@@ -35,6 +32,9 @@ import org.apache.impala.thrift.TExpr;
 import org.apache.impala.thrift.TPlanNode;
 import org.apache.impala.thrift.TPlanNodeType;
 import org.apache.impala.thrift.TUnionNode;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
@@ -74,16 +74,11 @@ public class UnionNode extends PlanNode {
   public boolean isConstantUnion() { return resultExprLists_.isEmpty(); }
 
   /**
-   * Add a child tree plus its corresponding resolved resultExprs.
+   * Add a child tree plus its corresponding unresolved resultExprs.
    */
-  public void addChild(PlanNode node, List<Expr> baseTblResultExprs) {
+  public void addChild(PlanNode node, List<Expr> resultExprs) {
     super.addChild(node);
-    resultExprLists_.add(baseTblResultExprs);
-    if (baseTblResultExprs != null) {
-      // if we're materializing output, we can only do that into a single
-      // output tuple
-      Preconditions.checkState(tupleIds_.size() == 1, tupleIds_.size());
-    }
+    resultExprLists_.add(resultExprs);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/795c085f/testdata/workloads/functional-query/queries/QueryTest/union.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/union.test b/testdata/workloads/functional-query/queries/QueryTest/union.test
index 9212af3..3ccecd9 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/union.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/union.test
@@ -1009,6 +1009,34 @@ bigint
 1
 ====
 ---- QUERY
+# IMPALA-4336: Test proper result expr casting when unnesting union operands.
+select double_col from alltypestiny union all (select 80 union all select 90)
+---- RESULTS: VERIFY_IS_EQUAL_SORTED
+0
+0
+0
+0
+10.1
+10.1
+10.1
+10.1
+80
+90
+---- TYPES
+DOUBLE
+=====
+---- QUERY
+# IMPALA-4336: Test proper result expr casting when unnesting union operands.
+select double_col from alltypestiny union distinct (select 80 union all select 90)
+---- RESULTS: VERIFY_IS_EQUAL_SORTED
+0
+10.1
+80
+90
+---- TYPES
+DOUBLE
+=====
+---- QUERY
 # Regression test for IMPALA-2948. When fast partition key scan is enabled,
 # make sure union nodes formed contain correct constant expressions even if
 # there are unmaterialized slots.


[6/6] incubator-impala git commit: IMPALA-4409: respect lock order in QueryExecState::CancelInternal()

Posted by ta...@apache.org.
IMPALA-4409: respect lock order in QueryExecState::CancelInternal()

The code previously violated the (partially documented) lock order
in ImpalaServer. An example of a possible cycle in the dependency
graph is:

* SetQueryInFlight() holds SessionState::lock_ and waits for
  'query_expiration_lock_'
* ExpireQueries() holds 'query_expiration_lock_' and waits for
  'query_exec_state_map_lock_'
* GetQueryExecState() holds 'query_exec_state_map_lock_' and
  waits for QueryExecState::lock_
* QES::Cancel() holds QueryExecState::lock_
  and waits for SessionState::lock

It's not clear how likely the above scenario is, but it's hard to rule
it out.

We have not seen this hang in the wild but have seen similar ones.

Testing:
Ran local stress test on 3-node minicluster with TPC-H 20 and 50%
of queries being cancelled.

Change-Id: I785fea0163a90d0633fb6ed77ec7c6882ab5c110
Reviewed-on: http://gerrit.cloudera.org:8080/4896
Reviewed-by: Tim Armstrong <ta...@cloudera.com>
Tested-by: Internal Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/9755ea63
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/9755ea63
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/9755ea63

Branch: refs/heads/master
Commit: 9755ea63b50d23f323c84edb4307ce603ded4fe1
Parents: 1d8cdb0
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Mon Oct 31 16:40:53 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Thu Nov 3 20:10:02 2016 +0000

----------------------------------------------------------------------
 be/src/runtime/coordinator.h       |  2 ++
 be/src/service/impala-server.h     | 54 +++++++++++++++++++++++++--------
 be/src/service/query-exec-state.cc | 19 +++++++-----
 be/src/service/query-exec-state.h  | 23 +++++++-------
 4 files changed, 66 insertions(+), 32 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9755ea63/be/src/runtime/coordinator.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/coordinator.h b/be/src/runtime/coordinator.h
index 53f00eb..fab6b29 100644
--- a/be/src/runtime/coordinator.h
+++ b/be/src/runtime/coordinator.h
@@ -199,6 +199,7 @@ class Coordinator {
     return exec_summary_;
   }
 
+  /// See the ImpalaServer class comment for the required lock acquisition order.
   SpinLock& GetExecSummaryLock() const { return exec_summary_lock_; }
 
   /// Receive a local filter update from a fragment instance. Aggregate that filter update
@@ -351,6 +352,7 @@ class Coordinator {
   boost::scoped_ptr<ObjectPool> obj_pool_;
 
   /// Execution summary for this query.
+  /// See the ImpalaServer class comment for the required lock acquisition order.
   mutable SpinLock exec_summary_lock_;
   TExecSummary exec_summary_;
 

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9755ea63/be/src/service/impala-server.h
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.h b/be/src/service/impala-server.h
index 7d0f7c9..c40fcb4 100644
--- a/be/src/service/impala-server.h
+++ b/be/src/service/impala-server.h
@@ -72,9 +72,34 @@ class TGetExecSummaryReq;
 /// An ImpalaServer contains both frontend and backend functionality;
 /// it implements ImpalaService (Beeswax), ImpalaHiveServer2Service (HiveServer2)
 /// and ImpalaInternalService APIs.
-/// This class is partially thread-safe. To ensure freedom from deadlock,
-/// locks on the maps are obtained before locks on the items contained in the maps.
-//
+///
+/// Locking
+/// -------
+/// This class is partially thread-safe. To ensure freedom from deadlock, if multiple
+/// locks are acquired, lower-numbered locks must be acquired before higher-numbered
+/// locks:
+/// 1. connection_to_sessions_map_lock_
+/// 2. session_state_map_lock_
+/// 3. SessionState::lock
+/// 4. query_expiration_lock_
+/// 5. query_exec_state_map_lock_
+/// 6. QueryExecState::fetch_rows_lock
+/// 7. QueryExecState::lock
+/// 8. QueryExecState::expiration_data_lock_
+/// 9. Coordinator::exec_summary_lock
+///
+/// Coordinator::lock_ should not be acquired at the same time as the
+/// ImpalaServer/SessionState/QueryExecState locks. Aside from
+/// Coordinator::exec_summary_lock_ the Coordinator's lock ordering is independent of
+/// the above lock ordering.
+///
+/// The following locks are not held in conjunction with other locks:
+/// * query_log_lock_
+/// * session_timeout_lock_
+/// * query_locations_lock_
+/// * uuid_lock_
+/// * catalog_version_lock_
+///
 /// TODO: The state of a running query is currently not cleaned up if the
 /// query doesn't experience any errors at runtime and close() doesn't get called.
 /// The solution is to have a separate thread that cleans up orphaned
@@ -638,7 +663,10 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
   typedef boost::unordered_map<TUniqueId, std::shared_ptr<QueryExecState>>
       QueryExecStateMap;
   QueryExecStateMap query_exec_state_map_;
-  boost::mutex query_exec_state_map_lock_;  // protects query_exec_state_map_
+
+  /// Protects query_exec_state_map_. See "Locking" in the class comment for lock
+  /// acquisition order.
+  boost::mutex query_exec_state_map_lock_;
 
   /// Default query options in the form of TQueryOptions and beeswax::ConfigVariable
   TQueryOptions default_query_options_;
@@ -671,8 +699,8 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
     /// Client network address.
     TNetworkAddress network_address;
 
-    /// Protects all fields below.
-    /// If this lock has to be taken with query_exec_state_map_lock, take this lock first.
+    /// Protects all fields below. See "Locking" in the class comment for lock
+    /// acquisition order.
     boost::mutex lock;
 
     /// If true, the session has been closed.
@@ -765,16 +793,16 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
   /// For access to GetSessionState() / MarkSessionInactive()
   friend class ScopedSessionState;
 
-  /// Protects session_state_map_. Should be taken before any query exec-state locks,
-  /// including query_exec_state_map_lock_. Should be taken before individual
-  /// session-state locks.
+  /// Protects session_state_map_. See "Locking" in the class comment for lock
+  /// acquisition order.
   boost::mutex session_state_map_lock_;
 
   /// A map from session identifier to a structure containing per-session information
   typedef boost::unordered_map<TUniqueId, std::shared_ptr<SessionState>> SessionStateMap;
   SessionStateMap session_state_map_;
 
-  /// Protects connection_to_sessions_map_. May be taken before session_state_map_lock_.
+  /// Protects connection_to_sessions_map_. See "Locking" in the class comment for lock
+  /// acquisition order.
   boost::mutex connection_to_sessions_map_lock_;
 
   /// Map from a connection ID to the associated list of sessions so that all can be
@@ -801,8 +829,7 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
     session->last_accessed_ms = UnixMillis();
   }
 
-  /// protects query_locations_. Must always be taken after
-  /// query_exec_state_map_lock_ if both are required.
+  /// Protects query_locations_. Not held in conjunction with other locks.
   boost::mutex query_locations_lock_;
 
   /// A map from backend to the list of queries currently running there.
@@ -865,7 +892,8 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
       ProxyUserMap;
   ProxyUserMap authorized_proxy_user_config_;
 
-  /// Guards queries_by_timestamp_.  Must not be acquired before a session state lock.
+  /// Guards queries_by_timestamp_. See "Locking" in the class comment for lock
+  /// acquisition order.
   boost::mutex query_expiration_lock_;
 
   /// Describes a query expiration event (t, q) where t is the expiration deadline in

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9755ea63/be/src/service/query-exec-state.cc
----------------------------------------------------------------------
diff --git a/be/src/service/query-exec-state.cc b/be/src/service/query-exec-state.cc
index 5cd4c0c..f7a1254 100644
--- a/be/src/service/query-exec-state.cc
+++ b/be/src/service/query-exec-state.cc
@@ -822,17 +822,20 @@ Status ImpalaServer::QueryExecState::FetchRowsInternal(const int32_t max_rows,
 }
 
 Status ImpalaServer::QueryExecState::Cancel(bool check_inflight, const Status* cause) {
+  if (check_inflight) {
+    // If the query is in 'inflight_queries' it means that the query has actually started
+    // executing. It is ok if the query is removed from 'inflight_queries' during
+    // cancellation, so we can release the session lock before starting the cancellation
+    // work.
+    lock_guard<mutex> session_lock(session_->lock);
+    if (session_->inflight_queries.find(query_id()) == session_->inflight_queries.end()) {
+      return Status("Query not yet running");
+    }
+  }
+
   Coordinator* coord;
   {
     lock_guard<mutex> lock(lock_);
-    if (check_inflight) {
-      lock_guard<mutex> session_lock(session_->lock);
-      if (session_->inflight_queries.find(query_id()) ==
-          session_->inflight_queries.end()) {
-        return Status("Query not yet running");
-      }
-    }
-
     // If the query is completed or cancelled, no need to update state.
     bool already_done = eos_ || query_state_ == QueryState::EXCEPTION;
     if (!already_done && cause != NULL) {

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9755ea63/be/src/service/query-exec-state.h
----------------------------------------------------------------------
diff --git a/be/src/service/query-exec-state.h b/be/src/service/query-exec-state.h
index 54ee929..78c859c 100644
--- a/be/src/service/query-exec-state.h
+++ b/be/src/service/query-exec-state.h
@@ -49,9 +49,9 @@ class QueryExecStateCleaner;
 /// we can return to the client. It also captures all state required for
 /// servicing query-related requests from the client.
 /// Thread safety: this class is generally not thread-safe, callers need to
-/// synchronize access explicitly via lock().
-/// To avoid deadlocks, the caller must *not* acquire query_exec_state_map_lock_
-/// while holding the exec state's lock.
+/// synchronize access explicitly via lock(). See the ImpalaServer class comment for
+/// the required lock acquisition order.
+///
 /// TODO: Consider renaming to RequestExecState for consistency.
 /// TODO: Compute stats is the only stmt that requires child queries. Once the
 /// CatalogService performs background stats gathering the concept of child queries
@@ -207,11 +207,11 @@ class ImpalaServer::QueryExecState {
   /// responsible for acquiring this lock. To avoid deadlocks, callers must not hold lock_
   /// while acquiring this lock (since FetchRows() will release and re-acquire lock_ during
   /// its execution).
+  /// See "Locking" in the class comment for lock acquisition order.
   boost::mutex fetch_rows_lock_;
 
-  /// Protects last_active_time_ and ref_count_.
-  /// Must always be taken as the last lock, that is no other locks may be taken while
-  /// holding this lock.
+  /// Protects last_active_time_ and ref_count_. Only held during short function calls -
+  /// no other locks should be acquired while holding this lock.
   mutable boost::mutex expiration_data_lock_;
   int64_t last_active_time_;
 
@@ -223,11 +223,12 @@ class ImpalaServer::QueryExecState {
   /// Executor for any child queries (e.g. compute stats subqueries). Always non-NULL.
   const boost::scoped_ptr<ChildQueryExecutor> child_query_executor_;
 
-  // Protects all following fields. Acquirers should be careful not to hold it for too
-  // long, e.g. during RPCs because this lock is required to make progress on various
-  // ImpalaServer requests. If held for too long it can block progress of client
-  // requests for this query, e.g. query status and cancellation. Furthermore, until
-  // IMPALA-3882 is fixed, it can indirectly block progress on all other queries.
+  /// Protects all following fields. Acquirers should be careful not to hold it for too
+  /// long, e.g. during RPCs because this lock is required to make progress on various
+  /// ImpalaServer requests. If held for too long it can block progress of client
+  /// requests for this query, e.g. query status and cancellation. Furthermore, until
+  /// IMPALA-3882 is fixed, it can indirectly block progress on all other queries.
+  /// See "Locking" in the class comment for lock acquisition order.
   boost::mutex lock_;
 
   ExecEnv* exec_env_;


[3/6] incubator-impala git commit: Add functional tests for compute stats with mt_dop > 0.

Posted by ta...@apache.org.
Add functional tests for compute stats with mt_dop > 0.

Change-Id: Icd4e7e44f9f23f66e59ad1fb298e13da76ad817a
Reviewed-on: http://gerrit.cloudera.org:8080/4879
Reviewed-by: Alex Behm <al...@cloudera.com>
Tested-by: Internal Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/6a16e44a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/6a16e44a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/6a16e44a

Branch: refs/heads/master
Commit: 6a16e44a2ad0e055e0d45c8f66f554c9bcb477be
Parents: 795c085
Author: Alex Behm <al...@cloudera.com>
Authored: Fri Oct 28 10:30:18 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Thu Nov 3 11:59:07 2016 +0000

----------------------------------------------------------------------
 .../queries/QueryTest/mt-dop-compute-stats.test   |  8 ++++++++
 tests/query_test/test_mt_dop.py                   | 18 +++++++++++++++---
 2 files changed, 23 insertions(+), 3 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/6a16e44a/testdata/workloads/functional-query/queries/QueryTest/mt-dop-compute-stats.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/mt-dop-compute-stats.test b/testdata/workloads/functional-query/queries/QueryTest/mt-dop-compute-stats.test
new file mode 100644
index 0000000..774e3a8
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/mt-dop-compute-stats.test
@@ -0,0 +1,8 @@
+====
+---- QUERY
+compute stats mt_dop
+---- RESULTS
+'Updated 24 partition(s) and 11 column(s).'
+---- TYPES
+STRING
+====

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/6a16e44a/tests/query_test/test_mt_dop.py
----------------------------------------------------------------------
diff --git a/tests/query_test/test_mt_dop.py b/tests/query_test/test_mt_dop.py
index 515c5f8..4bc5179 100644
--- a/tests/query_test/test_mt_dop.py
+++ b/tests/query_test/test_mt_dop.py
@@ -42,9 +42,20 @@ class TestMtDop(ImpalaTestSuite):
     return 'functional-query'
 
   def test_mt_dop(self, vector):
-    new_vector = deepcopy(vector)
-    new_vector.get_value('exec_option')['mt_dop'] = vector.get_value('mt_dop')
-    self.run_test_case('QueryTest/mt-dop', new_vector)
+    vector.get_value('exec_option')['mt_dop'] = vector.get_value('mt_dop')
+    self.run_test_case('QueryTest/mt-dop', vector)
+
+  def test_compute_stats(self, unique_database, vector):
+    table_loc = self._get_table_location("alltypes", vector)
+    # Create a second table in the same format pointing to the same data files.
+    # This function switches to the format-specific DB in vector.
+    self.execute_query_using_client(self.client,
+      "create external table %s.mt_dop like alltypes location '%s'"
+      % (unique_database, table_loc), vector)
+    self.execute_query_using_client(self.client,
+      "alter table %s.mt_dop recover partitions" % unique_database, vector)
+    vector.get_value('exec_option')['mt_dop'] = vector.get_value('mt_dop')
+    self.run_test_case('QueryTest/mt-dop-compute-stats', vector, unique_database)
 
 class TestMtDopParquet(ImpalaTestSuite):
   @classmethod
@@ -59,4 +70,5 @@ class TestMtDopParquet(ImpalaTestSuite):
         lambda v: v.get_value('table_format').file_format == 'parquet')
 
   def test_parquet(self, vector):
+    vector.get_value('exec_option')['mt_dop'] = vector.get_value('mt_dop')
     self.run_test_case('QueryTest/mt-dop-parquet', vector)


[5/6] incubator-impala git commit: IMPALA-4309: Introduce Expr rewrite phase and supporting classes.

Posted by ta...@apache.org.
IMPALA-4309: Introduce Expr rewrite phase and supporting classes.

Introduces a new phase for rewriting Exprs after analysis and
before subquery rewriting. The transformed Exprs replace the
original ones in analyzed statements. If Exprs were changed,
the whole statement is reset() and re-analyzed, similar to how
subqueries are rewritten. If both Exprs and subqueries are
rewritten there is only one re-analysis of the changed statement.

The following new classes work together to perform transformations:
1. ExprRewriteRule
- base class for Expr transformation rules
2. ExprRewriter
- drives the transformation of Exprs using a list of
  ExprRewriteRules

Statements that have exprs to be rewritten need to implement
a new method rewriteExprs() that accepts an ExprRewriter.

As an example, this patch adds a rule for converting
BetweenPredicates into their equivalent CompoundPredicates.
The BetweenPredicate has been notoriously buggy due to a lack
of such a separate rewrite phase and is now cleaned up.

Testing:
1. Added a new test for checking that the rewrite framework
   covers all relevant statements, clauses and can properly
   handle nested statements and subqueries.
2. Added a new test for ExprRewriteRules and implemented
   tests for the BetweenPredicate rewrite.
2. There are many existing tests for BetweePredicates and
   they all exercise the new rewrite rule/phase.
3. Ran a private core/hdfs run and it passed.

Change-Id: I2279dc984bcf7742db4fa3b1aa67283ecbb05e6e
Reviewed-on: http://gerrit.cloudera.org:8080/4746
Reviewed-by: Alex Behm <al...@cloudera.com>
Tested-by: Internal Jenkins


Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/1d8cdb02
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/1d8cdb02
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/1d8cdb02

Branch: refs/heads/master
Commit: 1d8cdb02c67fad9279a899626f3cd56bce0b0eb3
Parents: 6a16e44
Author: Alex Behm <al...@cloudera.com>
Authored: Fri Oct 14 11:19:39 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Thu Nov 3 20:08:37 2016 +0000

----------------------------------------------------------------------
 .../apache/impala/analysis/AnalysisContext.java |  65 ++++---
 .../org/apache/impala/analysis/Analyzer.java    |   9 +
 .../impala/analysis/BetweenPredicate.java       | 111 ++----------
 .../analysis/CreateOrAlterViewStmtBase.java     |   8 +-
 .../analysis/CreateTableAsSelectStmt.java       |  10 +-
 .../apache/impala/analysis/InlineViewRef.java   |  14 +-
 .../org/apache/impala/analysis/InsertStmt.java  |  17 +-
 .../org/apache/impala/analysis/ModifyStmt.java  |  18 +-
 .../org/apache/impala/analysis/SelectList.java  |  11 ++
 .../apache/impala/analysis/SelectListItem.java  |   3 +-
 .../org/apache/impala/analysis/SelectStmt.java  |  32 +++-
 .../apache/impala/analysis/StatementBase.java   |  13 +-
 .../apache/impala/analysis/StmtRewriter.java    |  30 +---
 .../org/apache/impala/analysis/TableRef.java    |   8 +
 .../org/apache/impala/analysis/UnionStmt.java   |  16 +-
 .../impala/planner/HdfsPartitionPruner.java     |  39 +++--
 .../org/apache/impala/planner/PlanNode.java     |   8 +-
 .../impala/rewrite/BetweenToCompoundRule.java   |  63 +++++++
 .../apache/impala/rewrite/ExprRewriteRule.java  |  36 ++++
 .../org/apache/impala/rewrite/ExprRewriter.java |  97 ++++++++++
 .../impala/analysis/AnalyzeStmtsTest.java       |   8 +-
 .../impala/analysis/AnalyzeSubqueriesTest.java  |   2 +-
 .../impala/analysis/ExprRewriteRulesTest.java   | 109 ++++++++++++
 .../impala/analysis/ExprRewriterTest.java       | 175 +++++++++++++++++++
 .../apache/impala/common/FrontendTestBase.java  |  10 +-
 .../queries/PlannerTest/tpcds-all.test          |  12 +-
 .../queries/PlannerTest/tpch-all.test           |   6 +-
 .../queries/PlannerTest/tpch-kudu.test          |   2 +-
 .../queries/PlannerTest/tpch-nested.test        |   4 +-
 .../queries/PlannerTest/tpch-views.test         |   2 +-
 30 files changed, 724 insertions(+), 214 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java b/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
index 24d1f45..b22bccb 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
@@ -22,9 +22,6 @@ import java.util.List;
 import java.util.Map;
 import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.authorization.AuthorizationChecker;
 import org.apache.impala.authorization.AuthorizationConfig;
 import org.apache.impala.authorization.AuthorizeableColumn;
@@ -37,9 +34,15 @@ import org.apache.impala.catalog.ImpaladCatalog;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.common.InternalException;
 import org.apache.impala.common.Pair;
+import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.ExprRewriteRule;
+import org.apache.impala.rewrite.ExprRewriter;
 import org.apache.impala.thrift.TAccessEvent;
 import org.apache.impala.thrift.TLineageGraph;
 import org.apache.impala.thrift.TQueryCtx;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
@@ -52,6 +55,7 @@ public class AnalysisContext {
   private final ImpaladCatalog catalog_;
   private final TQueryCtx queryCtx_;
   private final AuthorizationConfig authzConfig_;
+  private final ExprRewriter rewriter_;
 
   // Set in analyze()
   private AnalysisResult analysisResult_;
@@ -61,12 +65,24 @@ public class AnalysisContext {
     catalog_ = catalog;
     queryCtx_ = queryCtx;
     authzConfig_ = authzConfig;
+    List<ExprRewriteRule> rules = Lists.newArrayList(BetweenToCompoundRule.INSTANCE);
+    rewriter_ = new ExprRewriter(rules);
+  }
+
+  /**
+   * C'tor with a custom ExprRewriter for testing.
+   */
+  protected AnalysisContext(ImpaladCatalog catalog, TQueryCtx queryCtx,
+      AuthorizationConfig authzConfig, ExprRewriter rewriter) {
+    catalog_ = catalog;
+    queryCtx_ = queryCtx;
+    authzConfig_ = authzConfig;
+    rewriter_ = rewriter;
   }
 
   static public class AnalysisResult {
     private StatementBase stmt_;
     private Analyzer analyzer_;
-    private CreateTableStmt tmpCreateTableStmt_;
 
     public boolean isAlterTableStmt() { return stmt_ instanceof AlterTableStmt; }
     public boolean isAlterViewStmt() { return stmt_ instanceof AlterViewStmt; }
@@ -190,10 +206,6 @@ public class AnalysisContext {
       return (CreateTableStmt) stmt_;
     }
 
-    public CreateTableStmt getTmpCreateTableStmt() {
-      return tmpCreateTableStmt_;
-    }
-
     public CreateDbStmt getCreateDbStmt() {
       Preconditions.checkState(isCreateDbStmt());
       return (CreateDbStmt) stmt_;
@@ -311,10 +323,14 @@ public class AnalysisContext {
     public StatementBase getStmt() { return stmt_; }
     public Analyzer getAnalyzer() { return analyzer_; }
     public Set<TAccessEvent> getAccessEvents() { return analyzer_.getAccessEvents(); }
-    public boolean requiresRewrite() {
+    public boolean requiresSubqueryRewrite() {
       return analyzer_.containsSubquery() && !(stmt_ instanceof CreateViewStmt)
           && !(stmt_ instanceof AlterViewStmt);
     }
+    public boolean requiresExprRewrite() {
+      return isQueryStmt() ||isInsertStmt() || isCreateTableAsSelectStmt()
+          || isUpdateStmt() || isDeleteStmt();
+    }
     public TLineageGraph getThriftLineageGraph() {
       return analyzer_.getThriftSerializedLineageGraph();
     }
@@ -352,28 +368,27 @@ public class AnalysisContext {
       analysisResult_.stmt_ = (StatementBase) parser.parse().value;
       if (analysisResult_.stmt_ == null) return;
 
-      // For CTAS, we copy the create statement in case we have to create a new CTAS
-      // statement after a query rewrite.
-      if (analysisResult_.stmt_ instanceof CreateTableAsSelectStmt) {
-        analysisResult_.tmpCreateTableStmt_ =
-            ((CreateTableAsSelectStmt)analysisResult_.stmt_).getCreateStmt().clone();
-      }
-
       analysisResult_.stmt_.analyze(analysisResult_.analyzer_);
       boolean isExplain = analysisResult_.isExplainStmt();
 
-      // Check if we need to rewrite the statement.
-      if (analysisResult_.requiresRewrite()) {
-        StatementBase rewrittenStmt = StmtRewriter.rewrite(analysisResult_);
-        // Re-analyze the rewritten statement.
-        Preconditions.checkNotNull(rewrittenStmt);
-        analysisResult_ = new AnalysisResult();
+      // Apply expr and subquery rewrites.
+      boolean reAnalyze = false;
+      if (analysisResult_.requiresExprRewrite()) {
+        rewriter_.reset();
+        analysisResult_.stmt_.rewriteExprs(rewriter_);
+        reAnalyze = rewriter_.changed();
+      }
+      if (analysisResult_.requiresSubqueryRewrite()) {
+        StmtRewriter.rewrite(analysisResult_);
+        reAnalyze = true;
+      }
+      if (reAnalyze) {
         analysisResult_.analyzer_ = new Analyzer(catalog_, queryCtx_, authzConfig_);
-        analysisResult_.stmt_ = rewrittenStmt;
+        analysisResult_.stmt_.reset();
         analysisResult_.stmt_.analyze(analysisResult_.analyzer_);
-        LOG.trace("rewrittenStmt: " + rewrittenStmt.toSql());
+        LOG.trace("rewrittenStmt: " + analysisResult_.stmt_.toSql());
         if (isExplain) analysisResult_.stmt_.setIsExplain();
-        Preconditions.checkState(!analysisResult_.requiresRewrite());
+        Preconditions.checkState(!analysisResult_.requiresSubqueryRewrite());
       }
     } catch (AnalysisException e) {
       // Don't wrap AnalysisExceptions in another AnalysisException

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/Analyzer.java b/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
index b630a6e..5a34fbc 100644
--- a/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
+++ b/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
@@ -58,6 +58,8 @@ import org.apache.impala.common.InternalException;
 import org.apache.impala.common.Pair;
 import org.apache.impala.common.PrintUtils;
 import org.apache.impala.planner.PlanNode;
+import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.ExprRewriter;
 import org.apache.impala.service.FeSupport;
 import org.apache.impala.thrift.TAccessEvent;
 import org.apache.impala.thrift.TCatalogObjectType;
@@ -1039,6 +1041,13 @@ public class Analyzer {
     if ((!fromHavingClause && !hasEmptySpjResultSet_)
         || (fromHavingClause && !hasEmptyResultSet_)) {
       try {
+        if (conjunct instanceof BetweenPredicate) {
+          // Rewrite the BetweenPredicate into a CompoundPredicate so we can evaluate it
+          // below (BetweenPredicates are not executable). We might be in the first
+          // analysis pass, so the conjunct may not have been rewritten yet.
+          ExprRewriter rewriter = new ExprRewriter(BetweenToCompoundRule.INSTANCE);
+          conjunct = rewriter.rewrite(conjunct, this);
+        }
         if (!FeSupport.EvalPredicate(conjunct, globalState_.queryCtx)) {
           if (fromHavingClause) {
             hasEmptyResultSet_ = true;

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java b/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
index 5e412f7..2459715 100644
--- a/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
+++ b/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
@@ -17,38 +17,25 @@
 
 package org.apache.impala.analysis;
 
-import java.util.ArrayList;
-import java.util.List;
-
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.thrift.TExprNode;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.Lists;
 
 /**
- * Class describing between predicates. After successful analysis, we rewrite
- * the between predicate to a conjunctive/disjunctive compound predicate
- * to be handed to the backend.
+ * Class describing a BETWEEN predicate. This predicate needs to be rewritten into a
+ * CompoundPredicate for it to be executable, i.e., it is illegal to call toThrift()
+ * on this predicate because there is no BE implementation.
  */
 public class BetweenPredicate extends Predicate {
 
   private final boolean isNotBetween_;
 
-  // After successful analysis, we rewrite this between predicate
-  // into a conjunctive/disjunctive compound predicate.
-  private CompoundPredicate rewrittenPredicate_;
-
-  // Children of the BetweenPredicate, since this.children should hold the children
-  // of the rewritten predicate to make sure toThrift() picks up the right ones.
-  private ArrayList<Expr> originalChildren_ = Lists.newArrayList();
-
   // First child is the comparison expr which should be in [lowerBound, upperBound].
   public BetweenPredicate(Expr compareExpr, Expr lowerBound, Expr upperBound,
       boolean isNotBetween) {
-    originalChildren_.add(compareExpr);
-    originalChildren_.add(lowerBound);
-    originalChildren_.add(upperBound);
-    this.isNotBetween_ = isNotBetween;
+    children_.add(compareExpr);
+    children_.add(lowerBound);
+    children_.add(upperBound);
+    isNotBetween_ = isNotBetween;
   }
 
   /**
@@ -57,102 +44,36 @@ public class BetweenPredicate extends Predicate {
   protected BetweenPredicate(BetweenPredicate other) {
     super(other);
     isNotBetween_ = other.isNotBetween_;
-    originalChildren_ = Expr.cloneList(other.originalChildren_);
-    if (other.rewrittenPredicate_ != null) {
-      rewrittenPredicate_ = (CompoundPredicate) other.rewrittenPredicate_.clone();
-    }
-  }
-
-  public CompoundPredicate getRewrittenPredicate() {
-    Preconditions.checkState(isAnalyzed_);
-    return rewrittenPredicate_;
   }
-  public ArrayList<Expr> getOriginalChildren() { return originalChildren_; }
 
   @Override
   public void analyze(Analyzer analyzer) throws AnalysisException {
     if (isAnalyzed_) return;
     super.analyze(analyzer);
-    if (originalChildren_.get(0) instanceof Subquery &&
-        (originalChildren_.get(1) instanceof Subquery ||
-         originalChildren_.get(2) instanceof Subquery)) {
+    if (children_.get(0) instanceof Subquery &&
+        (children_.get(1) instanceof Subquery || children_.get(2) instanceof Subquery)) {
       throw new AnalysisException("Comparison between subqueries is not " +
-          "supported in a between predicate: " + toSqlImpl());
+          "supported in a BETWEEN predicate: " + toSqlImpl());
     }
-    analyzer.castAllToCompatibleType(originalChildren_);
-
-    // Rewrite between predicate into a conjunctive/disjunctive compound predicate.
-    if (isNotBetween_) {
-      // Rewrite into disjunction.
-      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.LT,
-          originalChildren_.get(0), originalChildren_.get(1));
-      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.GT,
-          originalChildren_.get(0), originalChildren_.get(2));
-      rewrittenPredicate_ =
-          new CompoundPredicate(CompoundPredicate.Operator.OR, lower, upper);
-    } else {
-      // Rewrite into conjunction.
-      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.GE,
-          originalChildren_.get(0), originalChildren_.get(1));
-      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.LE,
-          originalChildren_.get(0), originalChildren_.get(2));
-      rewrittenPredicate_ =
-          new CompoundPredicate(CompoundPredicate.Operator.AND, lower, upper);
-    }
-
-    try {
-      rewrittenPredicate_.analyze(analyzer);
-      fn_ = rewrittenPredicate_.fn_;
-    } catch (AnalysisException e) {
-      // We should have already guaranteed that analysis will succeed.
-      Preconditions.checkState(false, "Analysis failed in rewritten between predicate");
-    }
-
-    // Make sure toThrift() picks up the children of the rewritten predicate.
-    children_ = rewrittenPredicate_.getChildren();
-    // Since the only child is a CompoundPredicate expressing the comparison,
-    // the cost of the comparison is fully captured by the children's cost.
-    evalCost_ = getChildCosts();
+    analyzer.castAllToCompatibleType(children_);
     isAnalyzed_ = true;
   }
 
-  @Override
-  public List<Expr> getConjuncts() {
-    return rewrittenPredicate_.getConjuncts();
-  }
+  public boolean isNotBetween() { return isNotBetween_; }
 
   @Override
   protected void toThrift(TExprNode msg) {
-    rewrittenPredicate_.toThrift(msg);
+    throw new IllegalStateException(
+        "BetweenPredicate needs to be rewritten into a CompoundPredicate.");
   }
 
   @Override
   public String toSqlImpl() {
     String notStr = (isNotBetween_) ? "NOT " : "";
-    return originalChildren_.get(0).toSql() + " " + notStr + "BETWEEN " +
-        originalChildren_.get(1).toSql() + " AND " + originalChildren_.get(2).toSql();
-  }
-
-  /**
-   * Also substitute the exprs in originalChildren when cloning.
-   */
-  @Override
-  protected Expr substituteImpl(ExprSubstitutionMap smap, Analyzer analyzer)
-      throws AnalysisException {
-    BetweenPredicate clone = (BetweenPredicate) super.substituteImpl(smap, analyzer);
-    Preconditions.checkNotNull(clone);
-    clone.originalChildren_ =
-        Expr.substituteList(originalChildren_, smap, analyzer, false);
-    return clone;
+    return children_.get(0).toSql() + " " + notStr + "BETWEEN " +
+        children_.get(1).toSql() + " AND " + children_.get(2).toSql();
   }
 
   @Override
   public Expr clone() { return new BetweenPredicate(this); }
-
-  @Override
-  public Expr reset() {
-    super.reset();
-    originalChildren_ = Expr.resetList(originalChildren_);
-    return this;
-  }
 }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/CreateOrAlterViewStmtBase.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/CreateOrAlterViewStmtBase.java b/fe/src/main/java/org/apache/impala/analysis/CreateOrAlterViewStmtBase.java
index 1931930..54b8557 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CreateOrAlterViewStmtBase.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CreateOrAlterViewStmtBase.java
@@ -21,12 +21,12 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.thrift.TCreateOrAlterViewParams;
 import org.apache.impala.thrift.TTableName;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
@@ -156,7 +156,7 @@ public abstract class CreateOrAlterViewStmtBase extends StatementBase {
   }
 
   /**
-   * Computes the column lineage graph for a create/alter view statetement.
+   * Computes the column lineage graph for a create/alter view statement.
    */
   protected void computeLineageGraph(Analyzer analyzer) {
     ColumnLineageGraph graph = analyzer.getColumnLineageGraph();

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java b/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
index f7f8417..2f5f166 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
@@ -17,8 +17,8 @@
 
 package org.apache.impala.analysis;
 
-import java.util.List;
 import java.util.EnumSet;
+import java.util.List;
 
 import org.apache.impala.authorization.Privilege;
 import org.apache.impala.catalog.Db;
@@ -27,8 +27,10 @@ import org.apache.impala.catalog.KuduTable;
 import org.apache.impala.catalog.MetaStoreClientPool.MetaStoreClient;
 import org.apache.impala.catalog.Table;
 import org.apache.impala.common.AnalysisException;
+import org.apache.impala.rewrite.ExprRewriter;
 import org.apache.impala.service.CatalogOpExecutor;
 import org.apache.impala.thrift.THdfsFileFormat;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 
@@ -209,6 +211,12 @@ public class CreateTableAsSelectStmt extends StatementBase {
   }
 
   @Override
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    Preconditions.checkState(isAnalyzed());
+    insertStmt_.rewriteExprs(rewriter);
+  }
+
+  @Override
   public void reset() {
     super.reset();
     insertStmt_.reset();

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java b/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
index 94f5e76..3ee2070 100644
--- a/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
@@ -21,14 +21,15 @@ import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.catalog.ColumnStats;
 import org.apache.impala.catalog.StructField;
 import org.apache.impala.catalog.StructType;
 import org.apache.impala.catalog.View;
 import org.apache.impala.common.AnalysisException;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
@@ -262,6 +263,13 @@ public class InlineViewRef extends TableRef {
   }
 
   @Override
+  public void rewriteExprs(ExprRewriter rewriter, Analyzer analyzer)
+      throws AnalysisException {
+    super.rewriteExprs(rewriter, analyzer);
+    queryStmt_.rewriteExprs(rewriter);
+  }
+
+  @Override
   public List<TupleId> getMaterializedTupleIds() {
     Preconditions.checkState(isAnalyzed_);
     Preconditions.checkState(materializedTupleIds_.size() > 0);

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java b/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
index e95516e..5e457a3 100644
--- a/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
@@ -22,11 +22,6 @@ import java.util.ArrayList;
 import java.util.List;
 import java.util.Set;
 
-import org.apache.impala.planner.TableSink;
-import com.google.common.collect.ImmutableList;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.authorization.Privilege;
 import org.apache.impala.authorization.PrivilegeRequestBuilder;
 import org.apache.impala.catalog.Column;
@@ -39,8 +34,14 @@ import org.apache.impala.catalog.View;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.common.FileSystemUtil;
 import org.apache.impala.planner.DataSink;
+import org.apache.impala.planner.TableSink;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Iterables;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Sets;
@@ -659,6 +660,12 @@ public class InsertStmt extends StatementBase {
     }
   }
 
+  @Override
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    Preconditions.checkState(isAnalyzed());
+    queryStmt_.rewriteExprs(rewriter);
+  }
+
   public List<String> getPlanHints() { return planHints_; }
   public TableName getTargetTableName() { return targetTableName_; }
   public Table getTargetTable() { return table_; }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java b/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
index be22f02..00f99a5 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
@@ -17,6 +17,8 @@
 
 package org.apache.impala.analysis;
 
+import static java.lang.String.format;
+
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
@@ -30,14 +32,14 @@ import org.apache.impala.catalog.Table;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.common.Pair;
 import org.apache.impala.planner.DataSink;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-import org.slf4j.LoggerFactory;
-
-import static java.lang.String.format;
 
 /**
  * Abstract super class for statements that modify existing data like
@@ -286,8 +288,18 @@ public abstract class ModifyStmt extends StatementBase {
     }
   }
 
+  @Override
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    Preconditions.checkState(isAnalyzed());
+    for (Pair<SlotRef, Expr> assignment: assignments_) {
+      assignment.second = rewriter.rewrite(assignment.second, analyzer_);
+    }
+    sourceStmt_.rewriteExprs(rewriter);
+  }
+
   public QueryStmt getQueryStmt() { return sourceStmt_; }
   public abstract DataSink createDataSink();
+  @Override
   public abstract String toSql();
 
 

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/SelectList.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/SelectList.java b/fe/src/main/java/org/apache/impala/analysis/SelectList.java
index 4297f94..4c504bf 100644
--- a/fe/src/main/java/org/apache/impala/analysis/SelectList.java
+++ b/fe/src/main/java/org/apache/impala/analysis/SelectList.java
@@ -19,6 +19,9 @@ package org.apache.impala.analysis;
 
 import java.util.List;
 
+import org.apache.impala.common.AnalysisException;
+import org.apache.impala.rewrite.ExprRewriter;
+
 import com.google.common.collect.Lists;
 
 /**
@@ -83,6 +86,14 @@ public class SelectList {
     }
   }
 
+  public void rewriteExprs(ExprRewriter rewriter, Analyzer analyzer)
+      throws AnalysisException {
+    for (SelectListItem item: items_) {
+      if (item.isStar()) continue;
+      item.setExpr(rewriter.rewrite(item.getExpr(), analyzer));
+    }
+  }
+
   @Override
   public SelectList clone() { return new SelectList(this); }
 

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/SelectListItem.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/SelectListItem.java b/fe/src/main/java/org/apache/impala/analysis/SelectListItem.java
index 80aee25..b47e59f 100644
--- a/fe/src/main/java/org/apache/impala/analysis/SelectListItem.java
+++ b/fe/src/main/java/org/apache/impala/analysis/SelectListItem.java
@@ -23,7 +23,7 @@ import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 
 class SelectListItem {
-  private final Expr expr_;
+  private Expr expr_;
   private String alias_;
 
   // for "[path.]*" (excludes trailing '*')
@@ -52,6 +52,7 @@ class SelectListItem {
   }
 
   public Expr getExpr() { return expr_; }
+  public void setExpr(Expr expr) { expr_ = expr; }
   public boolean isStar() { return isStar_; }
   public String getAlias() { return alias_; }
   public void setAlias(String alias) { alias_ = alias; }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/SelectStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/SelectStmt.java b/fe/src/main/java/org/apache/impala/analysis/SelectStmt.java
index 9585f47..b112083 100644
--- a/fe/src/main/java/org/apache/impala/analysis/SelectStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/SelectStmt.java
@@ -22,9 +22,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.analysis.Path.PathType;
 import org.apache.impala.catalog.Column;
 import org.apache.impala.catalog.StructField;
@@ -35,6 +32,10 @@ import org.apache.impala.common.AnalysisException;
 import org.apache.impala.common.ColumnAliasGenerator;
 import org.apache.impala.common.TableAliasGenerator;
 import org.apache.impala.common.TreeNode;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;
@@ -56,7 +57,7 @@ public class SelectStmt extends QueryStmt {
   protected final FromClause fromClause_;
   protected Expr whereClause_;
   protected ArrayList<Expr> groupingExprs_;
-  protected final Expr havingClause_;  // original having clause
+  protected Expr havingClause_;  // original having clause
 
   // havingClause with aliases and agg output resolved
   private Expr havingPred_;
@@ -863,6 +864,29 @@ public class SelectStmt extends QueryStmt {
     }
   }
 
+  @Override
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    Preconditions.checkState(isAnalyzed());
+    selectList_.rewriteExprs(rewriter, analyzer_);
+    for (TableRef ref: fromClause_.getTableRefs()) ref.rewriteExprs(rewriter, analyzer_);
+    if (whereClause_ != null) {
+      whereClause_ = rewriter.rewrite(whereClause_, analyzer_);
+      // Also rewrite exprs in the statements of subqueries.
+      List<Subquery> subqueryExprs = Lists.newArrayList();
+      whereClause_.collect(Subquery.class, subqueryExprs);
+      for (Subquery s: subqueryExprs) s.getStatement().rewriteExprs(rewriter);
+    }
+    if (havingClause_ != null) {
+      havingClause_ = rewriter.rewrite(havingClause_, analyzer_);
+    }
+    if (groupingExprs_ != null) rewriter.applyList(groupingExprs_, analyzer_);
+    if (orderByElements_ != null) {
+      for (OrderByElement orderByElem: orderByElements_) {
+        orderByElem.setExpr(rewriter.rewrite(orderByElem.getExpr(), analyzer_));
+      }
+    }
+  }
+
   /**
    * Returns the SQL string corresponding to this SelectStmt.
    */

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/StatementBase.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/StatementBase.java b/fe/src/main/java/org/apache/impala/analysis/StatementBase.java
index 9faaddd..b4e3155 100644
--- a/fe/src/main/java/org/apache/impala/analysis/StatementBase.java
+++ b/fe/src/main/java/org/apache/impala/analysis/StatementBase.java
@@ -18,10 +18,10 @@
 package org.apache.impala.analysis;
 
 import org.apache.commons.lang.NotImplementedException;
-
 import org.apache.impala.catalog.Column;
 import org.apache.impala.catalog.Type;
 import org.apache.impala.common.AnalysisException;
+import org.apache.impala.rewrite.ExprRewriter;
 
 /**
  * Base class for all Impala SQL statements.
@@ -63,6 +63,17 @@ abstract class StatementBase implements ParseNode {
     analyzer_ = analyzer;
   }
 
+  /**
+   * Uses the given 'rewriter' to transform all Exprs in this statement according
+   * to the rules specified in the 'rewriter'. Replaces the original Exprs with the
+   * transformed ones in-place. Subclasses that have Exprs to be rewritten must
+   * override this method. Valid to call after analyze().
+   */
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    throw new IllegalStateException(
+        "rewriteExprs() not implemented for this stmt: " + getClass().getSimpleName());
+  }
+
   public Analyzer getAnalyzer() { return analyzer_; }
   public boolean isAnalyzed() { return analyzer_ != null; }
 

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/StmtRewriter.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/StmtRewriter.java b/fe/src/main/java/org/apache/impala/analysis/StmtRewriter.java
index bc18dfd..eccb136 100644
--- a/fe/src/main/java/org/apache/impala/analysis/StmtRewriter.java
+++ b/fe/src/main/java/org/apache/impala/analysis/StmtRewriter.java
@@ -20,12 +20,12 @@ package org.apache.impala.analysis;
 import java.util.ArrayList;
 import java.util.List;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.analysis.AnalysisContext.AnalysisResult;
 import org.apache.impala.analysis.UnionStmt.UnionOperand;
 import org.apache.impala.common.AnalysisException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.base.Predicates;
 import com.google.common.collect.Iterables;
@@ -41,10 +41,10 @@ public class StmtRewriter {
   private final static Logger LOG = LoggerFactory.getLogger(StmtRewriter.class);
 
   /**
-   * Rewrite the statement of an analysis result. The unanalyzed rewritten
-   * statement is returned.
+   * Rewrite the statement of an analysis result in-place. Assumes that BetweenPredicates
+   * have already been rewritten.
    */
-  public static StatementBase rewrite(AnalysisResult analysisResult)
+  public static void rewrite(AnalysisResult analysisResult)
       throws AnalysisException {
     // Analyzed stmt that contains a query statement with subqueries to be rewritten.
     StatementBase stmt = analysisResult.getStmt();
@@ -66,8 +66,6 @@ public class StmtRewriter {
           stmt.toSql());
     }
     rewriteQueryStatement(queryStmt, queryStmt.getAnalyzer());
-    stmt.reset();
-    return stmt;
   }
 
   /**
@@ -204,8 +202,6 @@ public class StmtRewriter {
     int numTableRefs = stmt.fromClause_.size();
     ArrayList<Expr> exprsWithSubqueries = Lists.newArrayList();
     ExprSubstitutionMap smap = new ExprSubstitutionMap();
-    // Replace all BetweenPredicates with their equivalent compound predicates.
-    stmt.whereClause_ = rewriteBetweenPredicates(stmt.whereClause_);
     // Check if all the conjuncts in the WHERE clause that contain subqueries
     // can currently be rewritten as a join.
     for (Expr conjunct: stmt.whereClause_.getConjuncts()) {
@@ -276,20 +272,6 @@ public class StmtRewriter {
   }
 
   /**
-   * Replace all BetweenPredicates with their equivalent compound predicates from the
-   * expr tree rooted at 'expr'. The modified expr tree is returned.
-   */
-  private static Expr rewriteBetweenPredicates(Expr expr) {
-    if (expr instanceof BetweenPredicate) {
-      return ((BetweenPredicate)expr).getRewrittenPredicate();
-    }
-    for (int i = 0; i < expr.getChildren().size(); ++i) {
-      expr.setChild(i, rewriteBetweenPredicates(expr.getChild(i)));
-    }
-    return expr;
-  }
-
-  /**
    * Modifies in place an expr that contains a subquery by rewriting its
    * subquery stmt. The modified analyzed expr is returned.
    */

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/TableRef.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/TableRef.java b/fe/src/main/java/org/apache/impala/analysis/TableRef.java
index c276dba..6403091 100644
--- a/fe/src/main/java/org/apache/impala/analysis/TableRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/TableRef.java
@@ -26,7 +26,9 @@ import org.apache.impala.catalog.HdfsTable;
 import org.apache.impala.catalog.Table;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.planner.JoinNode.DistributionMode;
+import org.apache.impala.rewrite.ExprRewriter;
 import org.apache.impala.thrift.TReplicaPreference;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
@@ -509,6 +511,12 @@ public class TableRef implements ParseNode {
     }
   }
 
+  public void rewriteExprs(ExprRewriter rewriter, Analyzer analyzer)
+      throws AnalysisException {
+    Preconditions.checkState(isAnalyzed_);
+    if (onClause_ != null) onClause_ = rewriter.rewrite(onClause_, analyzer);
+  }
+
   protected String tableRefToSql() {
     String aliasSql = null;
     String alias = getExplicitAlias();

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java b/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
index fffb72c..674e399 100644
--- a/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/UnionStmt.java
@@ -22,6 +22,7 @@ import java.util.List;
 
 import org.apache.impala.catalog.ColumnStats;
 import org.apache.impala.common.AnalysisException;
+import org.apache.impala.rewrite.ExprRewriter;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -198,6 +199,7 @@ public class UnionStmt extends QueryStmt {
   public boolean hasAllOps() { return !allOperands_.isEmpty(); }
   public AggregateInfo getDistinctAggInfo() { return distinctAggInfo_; }
   public boolean hasAnalyticExprs() { return hasAnalyticExprs_; }
+  public TupleId getTupleId() { return tupleId_; }
 
   public void removeAllOperands() {
     operands_.removeAll(allOperands_);
@@ -519,7 +521,15 @@ public class UnionStmt extends QueryStmt {
     baseTblResultExprs_ = resultExprs_;
   }
 
-  public TupleId getTupleId() { return tupleId_; }
+  @Override
+  public void rewriteExprs(ExprRewriter rewriter) throws AnalysisException {
+    for (UnionOperand op: operands_) op.getQueryStmt().rewriteExprs(rewriter);
+    if (orderByElements_ != null) {
+      for (OrderByElement orderByElem: orderByElements_) {
+        orderByElem.setExpr(rewriter.rewrite(orderByElem.getExpr(), analyzer_));
+      }
+    }
+  }
 
   @Override
   public void getMaterializedTupleIds(ArrayList<TupleId> tupleIdList) {
@@ -533,9 +543,7 @@ public class UnionStmt extends QueryStmt {
 
   @Override
   public void collectTableRefs(List<TableRef> tblRefs) {
-    for (UnionOperand op: operands_) {
-      op.getQueryStmt().collectTableRefs(tblRefs);
-    }
+    for (UnionOperand op: operands_) op.getQueryStmt().collectTableRefs(tblRefs);
   }
 
   @Override

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java b/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
index 5efd474..10b6539 100644
--- a/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
+++ b/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
@@ -26,9 +26,6 @@ import java.util.NavigableMap;
 import java.util.Set;
 import java.util.TreeMap;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.BetweenPredicate;
 import org.apache.impala.analysis.BinaryPredicate;
@@ -47,6 +44,11 @@ import org.apache.impala.catalog.HdfsPartition;
 import org.apache.impala.catalog.HdfsTable;
 import org.apache.impala.common.AnalysisException;
 import org.apache.impala.common.InternalException;
+import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Preconditions;
 import com.google.common.base.Predicates;
 import com.google.common.collect.Lists;
@@ -73,7 +75,12 @@ public class HdfsPartitionPruner {
 
   private final HdfsTable tbl_;
 
-  private List<SlotId> partitionSlots_ = Lists.newArrayList();
+  private final List<SlotId> partitionSlots_ = Lists.newArrayList();
+
+  // For converting BetweenPredicates to CompoundPredicates so they can be
+  // executed in the BE.
+  private final ExprRewriter exprRewriter_ =
+      new ExprRewriter(BetweenToCompoundRule.INSTANCE);
 
   public HdfsPartitionPruner(TupleDescriptor tupleDesc) {
     Preconditions.checkState(tupleDesc.getTable() instanceof HdfsTable);
@@ -90,10 +97,10 @@ public class HdfsPartitionPruner {
 
   /**
    * Return a list of partitions left after applying the conjuncts. Please note
-   * that conjunts used for filtering will be removed from the list 'conjuncts'.
+   * that conjuncts used for filtering will be removed from the list 'conjuncts'.
    */
   public List<HdfsPartition> prunePartitions(Analyzer analyzer, List<Expr> conjuncts)
-      throws InternalException {
+      throws InternalException, AnalysisException {
     // Start with creating a collection of partition filters for the applicable conjuncts.
     List<HdfsPartitionFilter> partitionFilters = Lists.newArrayList();
     // Conjuncts that can be evaluated from the partition key values.
@@ -109,15 +116,14 @@ public class HdfsPartitionPruner {
       Expr conjunct = it.next();
       if (conjunct.isBoundBySlotIds(partitionSlots_)) {
         // Check if the conjunct can be evaluated from the partition metadata.
-        // canEvalUsingPartitionMd() operates on a cloned conjunct which may get
-        // modified if it contains constant expressions. If the cloned conjunct
-        // cannot be evaluated from the partition metadata, the original unmodified
-        // conjuct is evaluated in the BE.
-        Expr clonedConjunct = conjunct.clone();
+        // Use a cloned conjunct to rewrite BetweenPredicates and allow
+        // canEvalUsingPartitionMd() to fold constant expressions without modifying
+        // the original expr.
+        Expr clonedConjunct = exprRewriter_.rewrite(conjunct.clone(), analyzer);
         if (canEvalUsingPartitionMd(clonedConjunct, analyzer)) {
           simpleFilterConjuncts.add(Expr.pushNegationToOperands(clonedConjunct));
         } else {
-          partitionFilters.add(new HdfsPartitionFilter(conjunct, tbl_, analyzer));
+          partitionFilters.add(new HdfsPartitionFilter(clonedConjunct, tbl_, analyzer));
         }
         it.remove();
       }
@@ -169,6 +175,7 @@ public class HdfsPartitionPruner {
    */
   private boolean canEvalUsingPartitionMd(Expr expr, Analyzer analyzer) {
     Preconditions.checkNotNull(expr);
+    Preconditions.checkState(!(expr instanceof BetweenPredicate));
     if (expr instanceof BinaryPredicate) {
       // Evaluate any constant expression in the BE
       try {
@@ -208,9 +215,6 @@ public class HdfsPartitionPruner {
         if (!(expr.getChild(i).isLiteral())) return false;
       }
       return true;
-    } else if (expr instanceof BetweenPredicate) {
-      return canEvalUsingPartitionMd(((BetweenPredicate) expr).getRewrittenPredicate(),
-          analyzer);
     }
     return false;
   }
@@ -407,10 +411,11 @@ public class HdfsPartitionPruner {
    * key values; return the matching partition ids. An empty set is returned
    * if there are no matching partitions. This function can evaluate the following
    * types of predicates: BinaryPredicate, CompoundPredicate, IsNullPredicate,
-   * InPredicate, and BetweenPredicate.
+   * InPredicate.
    */
   private HashSet<Long> evalSlotBindingFilter(Expr expr) {
     Preconditions.checkNotNull(expr);
+    Preconditions.checkState(!(expr instanceof BetweenPredicate));
     if (expr instanceof BinaryPredicate) {
       return evalBinaryPredicate(expr);
     } else if (expr instanceof CompoundPredicate) {
@@ -430,8 +435,6 @@ public class HdfsPartitionPruner {
       return evalInPredicate(expr);
     } else if (expr instanceof IsNullPredicate) {
       return evalIsNullPredicate(expr);
-    } else if (expr instanceof BetweenPredicate) {
-      return evalSlotBindingFilter(((BetweenPredicate) expr).getRewrittenPredicate());
     }
     return null;
   }

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/planner/PlanNode.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/PlanNode.java b/fe/src/main/java/org/apache/impala/planner/PlanNode.java
index 4686e2c..141464e 100644
--- a/fe/src/main/java/org/apache/impala/planner/PlanNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/PlanNode.java
@@ -23,9 +23,6 @@ import java.util.Collections;
 import java.util.List;
 import java.util.Set;
 
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
 import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.Expr;
 import org.apache.impala.analysis.ExprId;
@@ -41,6 +38,9 @@ import org.apache.impala.thrift.TExplainLevel;
 import org.apache.impala.thrift.TPlan;
 import org.apache.impala.thrift.TPlanNode;
 import org.apache.impala.thrift.TQueryOptions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
@@ -669,7 +669,7 @@ abstract public class PlanNode extends TreeNode<PlanNode> {
     int numWithoutSel = 0;
     List<T> remaining = Lists.newArrayListWithCapacity(conjuncts.size());
     for (T e : conjuncts) {
-      Preconditions.checkState(e.hasCost());
+      Preconditions.checkState(e.hasCost(), e.toSql());
       totalCost += e.getCost();
       remaining.add(e);
       if (!e.hasSelectivity()) {

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/rewrite/BetweenToCompoundRule.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/rewrite/BetweenToCompoundRule.java b/fe/src/main/java/org/apache/impala/rewrite/BetweenToCompoundRule.java
new file mode 100644
index 0000000..296780d
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/rewrite/BetweenToCompoundRule.java
@@ -0,0 +1,63 @@
+// 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.impala.rewrite;
+
+import org.apache.impala.analysis.Analyzer;
+import org.apache.impala.analysis.BetweenPredicate;
+import org.apache.impala.analysis.BinaryPredicate;
+import org.apache.impala.analysis.CompoundPredicate;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.analysis.Predicate;
+import org.apache.impala.common.AnalysisException;
+
+/**
+ * Rewrites BetweenPredicates into an equivalent conjunctive/disjunctive
+ * CompoundPredicate.
+ * Examples:
+ * A BETWEEN X AND Y ==> A >= X AND A <= Y
+ * A NOT BETWEEN X AND Y ==> A < X OR A > Y
+ */
+public class BetweenToCompoundRule implements ExprRewriteRule {
+  public static ExprRewriteRule INSTANCE = new BetweenToCompoundRule();
+
+  @Override
+  public Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException {
+    if (!(expr instanceof BetweenPredicate)) return expr;
+    BetweenPredicate bp = (BetweenPredicate) expr;
+    Expr result = null;
+    if (bp.isNotBetween()) {
+      // Rewrite into disjunction.
+      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.LT,
+          bp.getChild(0), bp.getChild(1));
+      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.GT,
+          bp.getChild(0), bp.getChild(2));
+      result = new CompoundPredicate(CompoundPredicate.Operator.OR, lower, upper);
+    } else {
+      // Rewrite into conjunction.
+      Predicate lower = new BinaryPredicate(BinaryPredicate.Operator.GE,
+          bp.getChild(0), bp.getChild(1));
+      Predicate upper = new BinaryPredicate(BinaryPredicate.Operator.LE,
+          bp.getChild(0), bp.getChild(2));
+      result = new CompoundPredicate(CompoundPredicate.Operator.AND, lower, upper);
+    }
+    result.analyze(analyzer);
+    return result;
+  }
+
+  private BetweenToCompoundRule() {}
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java b/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java
new file mode 100644
index 0000000..48054a8
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java
@@ -0,0 +1,36 @@
+// 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.impala.rewrite;
+
+import org.apache.impala.analysis.Analyzer;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.common.AnalysisException;
+
+/**
+ * Base class for all Expr rewrite rules. A rule is free to modify Exprs in place,
+ * but must return a different Expr object if any modifications were made.
+ */
+public interface ExprRewriteRule {
+  /**
+   * Applies this rewrite rule to the given analyzed Expr. Returns the transformed and
+   * analyzed Expr or the original unmodified Expr if no changes were made. If any
+   * changes were made, the transformed Expr is guaranteed to be a different Expr object,
+   * so callers can rely on object reference comparison for change detection.
+   */
+  public abstract Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException;
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/main/java/org/apache/impala/rewrite/ExprRewriter.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/rewrite/ExprRewriter.java b/fe/src/main/java/org/apache/impala/rewrite/ExprRewriter.java
new file mode 100644
index 0000000..906fc0e
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/rewrite/ExprRewriter.java
@@ -0,0 +1,97 @@
+// 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.impala.rewrite;
+
+import java.util.List;
+
+import org.apache.impala.analysis.Analyzer;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.common.AnalysisException;
+import org.apache.kudu.client.shaded.com.google.common.collect.Lists;
+
+/**
+ * Helper class that drives the transformation of Exprs according to a given list of
+ * ExprRewriteRules. The rules are applied as follows:
+ * - a single rule is applied repeatedly to the Expr and all its children in a bottom-up
+ *   fashion until there are no more changes
+ * - the rule list is applied repeatedly until no rule has made any changes
+ * - the rules are applied in the order they appear in the rule list
+ * Keeps track of how many transformations were applied.
+ */
+public class ExprRewriter {
+  private int numChanges_ = 0;
+  private final List<ExprRewriteRule> rules_;
+
+  public ExprRewriter(List<ExprRewriteRule> rules) {
+    rules_ = rules;
+  }
+
+  public ExprRewriter(ExprRewriteRule rule) {
+    rules_ = Lists.newArrayList(rule);
+  }
+
+  public Expr rewrite(Expr expr, Analyzer analyzer) throws AnalysisException {
+    // Keep applying the rule list until no rule has made any changes.
+    int oldNumChanges;
+    Expr rewrittenExpr = expr;
+    do {
+      oldNumChanges = numChanges_;
+      for (ExprRewriteRule rule: rules_) {
+        rewrittenExpr = applyRuleRepeatedly(rewrittenExpr, rule, analyzer);
+      }
+    } while (oldNumChanges != numChanges_);
+    return rewrittenExpr;
+  }
+
+  /**
+   * Applies 'rule' on the Expr tree rooted at 'expr' until there are no more changes.
+   * Returns the transformed Expr or 'expr' if there were no changes.
+   */
+  private Expr applyRuleRepeatedly(Expr expr, ExprRewriteRule rule, Analyzer analyzer)
+      throws AnalysisException {
+    int oldNumChanges;
+    Expr rewrittenExpr = expr;
+    do {
+      oldNumChanges = numChanges_;
+      rewrittenExpr = applyRuleBottomUp(rewrittenExpr, rule, analyzer);
+    } while (oldNumChanges != numChanges_);
+    return rewrittenExpr;
+  }
+
+  /**
+   * Applies 'rule' on 'expr' and all its children in a bottom-up fashion.
+   * Returns the transformed Expr or 'expr' if there were no changes.
+   */
+  private Expr applyRuleBottomUp(Expr expr, ExprRewriteRule rule, Analyzer analyzer)
+      throws AnalysisException {
+    for (int i = 0; i < expr.getChildren().size(); ++i) {
+      expr.setChild(i, applyRuleBottomUp(expr.getChild(i), rule, analyzer));
+    }
+    Expr rewrittenExpr = rule.apply(expr, analyzer);
+    if (rewrittenExpr != expr) ++numChanges_;
+    return rewrittenExpr;
+  }
+
+  public void applyList(List<Expr> exprs, Analyzer analyzer) throws AnalysisException {
+    for (int i = 0; i < exprs.size(); ++i) exprs.set(i, rewrite(exprs.get(i), analyzer));
+  }
+
+  public void reset() { numChanges_ = 0; }
+  public boolean changed() { return numChanges_ > 0; }
+  public int getNumChanges() { return numChanges_; }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java b/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
index 31c0fdc..cbd2d07 100644
--- a/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
@@ -23,13 +23,13 @@ import static org.junit.Assert.fail;
 import java.lang.reflect.Field;
 import java.util.List;
 
-import org.junit.Assert;
-import org.junit.Test;
-
 import org.apache.impala.catalog.PrimitiveType;
 import org.apache.impala.catalog.ScalarType;
 import org.apache.impala.catalog.Type;
 import org.apache.impala.common.AnalysisException;
+import org.junit.Assert;
+import org.junit.Test;
+
 import com.google.common.base.Preconditions;
 import com.google.common.collect.ImmutableList;
 import com.google.common.collect.Lists;
@@ -2769,7 +2769,7 @@ public class AnalyzeStmtsTest extends AnalyzerTest {
         "from with_1) select 1 as int_col_1 from with_4) as t1) select 1 as " +
         "int_col_1 from with_3) select 1 as int_col_1 from with_2");
 
-    // WITH clasue with a between predicate
+    // WITH clause with a between predicate
     AnalyzesOk("with with_1 as (select int_col from functional.alltypestiny " +
         "where int_col between 0 and 10) select * from with_1");
     // WITH clause with a between predicate in the select list

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/test/java/org/apache/impala/analysis/AnalyzeSubqueriesTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/AnalyzeSubqueriesTest.java b/fe/src/test/java/org/apache/impala/analysis/AnalyzeSubqueriesTest.java
index a37ba72..fb2d63a 100644
--- a/fe/src/test/java/org/apache/impala/analysis/AnalyzeSubqueriesTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/AnalyzeSubqueriesTest.java
@@ -1276,7 +1276,7 @@ public class AnalyzeSubqueriesTest extends AnalyzerTest {
     AnalysisError("select * from functional.alltypestiny where (select min(id) " +
         "from functional.alltypes) between 1 and (select max(id) from " +
         "functional.alltypes)", "Comparison between subqueries is not supported " +
-        "in a between predicate: (SELECT min(id) FROM functional.alltypes) BETWEEN " +
+        "in a BETWEEN predicate: (SELECT min(id) FROM functional.alltypes) BETWEEN " +
         "1 AND (SELECT max(id) FROM functional.alltypes)");
     AnalyzesOk("select * from functional.alltypestiny where " +
         "int_col between 0 and 10 and exists (select 1)");

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java b/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
new file mode 100644
index 0000000..d3d52b4
--- /dev/null
+++ b/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
@@ -0,0 +1,109 @@
+// 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.impala.analysis;
+
+import java.util.List;
+
+import org.apache.impala.catalog.Catalog;
+import org.apache.impala.common.AnalysisException;
+import org.apache.impala.common.FrontendTestBase;
+import org.apache.impala.rewrite.BetweenToCompoundRule;
+import org.apache.impala.rewrite.ExprRewriteRule;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.collect.Lists;
+
+/**
+ * Tests ExprRewriteRules.
+ */
+public class ExprRewriteRulesTest extends FrontendTestBase {
+
+  public Expr RewritesOk(String expr, ExprRewriteRule rule, String expectedExpr)
+      throws AnalysisException {
+    String stmtStr = "select " + expr + " from functional.alltypes";
+    SelectStmt stmt = (SelectStmt) ParsesOk(stmtStr);
+    Analyzer analyzer = createAnalyzer(Catalog.DEFAULT_DB);
+    stmt.analyze(analyzer);
+    Expr origExpr = stmt.getResultExprs().get(0);
+    String origSql = origExpr.toSql();
+    // Create a rewriter with only a single rule.
+    List<ExprRewriteRule> rules = Lists.newArrayList();
+    rules.add(rule);
+    ExprRewriter rewriter = new ExprRewriter(rules);
+    Expr rewrittenExpr = rewriter.rewrite(origExpr, analyzer);
+    String rewrittenSql = rewrittenExpr.toSql();
+    boolean expectChange = expectedExpr != null;
+    if (expectedExpr != null) {
+      assertEquals(expectedExpr, rewrittenSql);
+    } else {
+      assertEquals(origSql, rewrittenSql);
+    }
+    Assert.assertEquals(expectChange, rewriter.changed());
+    return rewrittenExpr;
+  }
+
+  /**
+   * Helper for prettier error messages than what JUnit.Assert provides.
+   */
+  private void assertEquals(String expected, String actual) {
+    if (!actual.equals(expected)) {
+      Assert.fail(String.format("\nActual: %s\nExpected: %s\n", actual, expected));
+    }
+  }
+
+  @Test
+  public void TestBetweenToCompoundRule() throws AnalysisException {
+    ExprRewriteRule rule = BetweenToCompoundRule.INSTANCE;
+
+    // Basic BETWEEN predicates.
+    RewritesOk("int_col between float_col and double_col", rule,
+        "int_col >= float_col AND int_col <= double_col");
+    RewritesOk("int_col not between float_col and double_col", rule,
+        "int_col < float_col OR int_col > double_col");
+    RewritesOk("50.0 between null and 5000", rule,
+        "50.0 >= NULL AND 50.0 <= 5000");
+    // Basic NOT BETWEEN predicates.
+    RewritesOk("int_col between 10 and 20", rule,
+        "int_col >= 10 AND int_col <= 20");
+    RewritesOk("int_col not between 10 and 20", rule,
+        "int_col < 10 OR int_col > 20");
+    RewritesOk("50.0 not between null and 5000", rule,
+        "50.0 < NULL OR 50.0 > 5000");
+
+    // Nested BETWEEN predicates.
+    RewritesOk(
+        "int_col between if(tinyint_col between 1 and 2, 10, 20) " +
+        "and cast(smallint_col between 1 and 2 as int)", rule,
+        "int_col >= if(tinyint_col >= 1 AND tinyint_col <= 2, 10, 20) " +
+        "AND int_col <= CAST(smallint_col >= 1 AND smallint_col <= 2 AS INT)");
+    // Nested NOT BETWEEN predicates.
+    RewritesOk(
+        "int_col not between if(tinyint_col not between 1 and 2, 10, 20) " +
+        "and cast(smallint_col not between 1 and 2 as int)", rule,
+        "int_col < if(tinyint_col < 1 OR tinyint_col > 2, 10, 20) " +
+        "OR int_col > CAST(smallint_col < 1 OR smallint_col > 2 AS INT)");
+    // Mixed nested BETWEEN and NOT BETWEEN predicates.
+    RewritesOk(
+        "int_col between if(tinyint_col between 1 and 2, 10, 20) " +
+        "and cast(smallint_col not between 1 and 2 as int)", rule,
+        "int_col >= if(tinyint_col >= 1 AND tinyint_col <= 2, 10, 20) " +
+        "AND int_col <= CAST(smallint_col < 1 OR smallint_col > 2 AS INT)");
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/test/java/org/apache/impala/analysis/ExprRewriterTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ExprRewriterTest.java b/fe/src/test/java/org/apache/impala/analysis/ExprRewriterTest.java
new file mode 100644
index 0000000..310b7e4
--- /dev/null
+++ b/fe/src/test/java/org/apache/impala/analysis/ExprRewriterTest.java
@@ -0,0 +1,175 @@
+// 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.impala.analysis;
+
+import org.apache.impala.authorization.AuthorizationConfig;
+import org.apache.impala.catalog.Catalog;
+import org.apache.impala.common.AnalysisException;
+import org.apache.impala.common.RuntimeEnv;
+import org.apache.impala.rewrite.ExprRewriteRule;
+import org.apache.impala.rewrite.ExprRewriter;
+import org.apache.impala.testutil.TestUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * Tests that the ExprRewriter framework covers all clauses as well as nested statements.
+ * Does not test specific rewrite rules.
+ */
+public class ExprRewriterTest extends AnalyzerTest {
+
+  /**
+   * Replaces any Expr that does not contain a Subquery with a TRUE BoolLiteral.
+   */
+  static class ExprToBoolRule implements ExprRewriteRule {
+    public static ExprToBoolRule INSTANCE = new ExprToBoolRule();
+
+    @Override
+    public Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException {
+      if (expr.contains(Subquery.class)) return expr;
+      if (Predicate.IS_TRUE_LITERAL.apply(expr)) return expr;
+      return new BoolLiteral(true);
+    }
+
+    private ExprToBoolRule() {}
+  }
+
+  /**
+   * Replaces a TRUE BoolLiteral with a FALSE BoolLiteral.
+   */
+  static class TrueToFalseRule implements ExprRewriteRule {
+    public static TrueToFalseRule INSTANCE = new TrueToFalseRule();
+
+    @Override
+    public Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException {
+      if (Predicate.IS_TRUE_LITERAL.apply(expr)) return new BoolLiteral(false);
+      return expr;
+    }
+    private TrueToFalseRule() {}
+  }
+
+  private final ExprRewriter exprToTrue_ = new ExprRewriter(ExprToBoolRule.INSTANCE);
+  private final ExprRewriter trueToFalse_ = new ExprRewriter(TrueToFalseRule.INSTANCE);
+
+  /**
+   * Analyzes 'stmt' and rewrites Exprs with 'exprToTrue_' and validates the following:
+   * 1. The actual number of changed Exprs should be equal to 'expectedNumChanges'.
+   * 2. Checks that the Exprs were actually rewritten by doing another round of
+   *    rewriting using 'trueToFalse_'. The expected number of changes for this
+   *    second rewriting is 'expectedNumExprTrees'.
+   * Does not use an AnalysisContext to avoid rewriting subqueries which might alter the
+   * number of expressions and complicate validation.
+   */
+  public void RewritesOk(String stmt, int expectedNumChanges,
+      int expectedNumExprTrees) throws AnalysisException {
+    StatementBase parsedStmt = (StatementBase) ParsesOk(stmt);
+    parsedStmt.analyze(createAnalyzer(Catalog.DEFAULT_DB));
+
+    exprToTrue_.reset();
+    parsedStmt.rewriteExprs(exprToTrue_);
+    Assert.assertEquals(expectedNumChanges, exprToTrue_.getNumChanges());
+
+    // Verify that the Exprs were actually replaced.
+    trueToFalse_.reset();
+    parsedStmt.rewriteExprs(trueToFalse_);
+    Assert.assertEquals(expectedNumExprTrees, trueToFalse_.getNumChanges());
+
+    // Make sure the stmt can be successfully re-analyzed.
+    parsedStmt.reset();
+    parsedStmt.analyze(createAnalyzer(Catalog.DEFAULT_DB));
+  }
+
+  /**
+   * Asserts that no rewrites are performed on the given stmt.
+   */
+  public void CheckNoRewrite(String stmt) throws AnalysisException {
+    exprToTrue_.reset();
+    Analyzer analyzer = createAnalyzer(Catalog.DEFAULT_DB);
+    AnalysisContext analysisCtx = new AnalysisContext(catalog_,
+        TestUtils.createQueryContext(Catalog.DEFAULT_DB,
+            System.getProperty("user.name")),
+            AuthorizationConfig.createAuthDisabledConfig(), exprToTrue_);
+    analysisCtx.analyze(stmt, analyzer);
+    Preconditions.checkNotNull(analysisCtx.getAnalysisResult().getStmt());
+    Assert.assertEquals(0, exprToTrue_.getNumChanges());
+  }
+
+  // Select statement with all clauses that has 11 rewritable Expr trees.
+  // We expect a total of 23 exprs to be changed.
+  private final String stmt_ =
+      "select a.int_col a, 10 b, 20.2 c, count(b.int_col) cnt from " +
+      "functional.alltypes a join functional.alltypes b on (a.id = b.id)" +
+      "where b.float_col > 1 and b.double_col > 2 " +
+      "group by 1, a.string_col " +
+      "having count(b.int_col) < 3 " +
+      "order by a.int_col, 4 limit 10";
+
+  @Test
+  public void TestQueryStmts() throws AnalysisException {
+    RewritesOk(stmt_, 23, 11);
+    // Test rewriting in inline views. The view stmt is the same as the query above
+    // but with an order by + limit. Expanded star exprs are not rewritten.
+    RewritesOk("select * from (" + stmt_ + ") v", 23, 11);
+    // Test union, 11 + 11 + 1 rewritable Expr trees.
+    RewritesOk(String.format("%s union all (%s) order by cnt", stmt_, stmt_), 47, 23);
+    // Test union inside an inline view.
+    RewritesOk(String.format("select * from (%s union all (%s) order by cnt limit 10) v",
+        stmt_, stmt_), 47, 23);
+    // Constant select.
+    RewritesOk("select 1, 2, 3, 4", 4, 4);
+    // Values stmt.
+    RewritesOk("values(1, '2', 3, 4.1), (1, '2', 3, 4.1)", 8, 8);
+    // Test WHERE-clause subqueries.
+    RewritesOk("select id, int_col from functional.alltypes a " +
+        "where exists (select 1 from functional.alltypes " +
+        "where string_col = 'test' having count(*) < 10)", 9, 5);
+    RewritesOk("select id, int_col from functional.alltypes a " +
+        "where a.id in (select count(*) from functional.alltypes " +
+        "where string_col = 'test' having count(*) < 10)", 10, 6);
+  }
+
+  @Test
+  public void TestDdlStmts() throws AnalysisException {
+    RewritesOk("create table ctas_test as " + stmt_, 23, 11);
+    // Create/alter view stmts are not rewritten to preserve the original SQL.
+    CheckNoRewrite("create view view_test as " + stmt_);
+    CheckNoRewrite("alter view functional.alltypes_view as " + stmt_);
+  }
+
+  @Test
+  public void TestDmlStmts() throws AnalysisException {
+    // Insert.
+    RewritesOk("insert into functional.alltypes (id, int_col, float_col, bigint_col) " +
+      "partition(year=2009,month=10) " + stmt_, 23, 11);
+
+    if (RuntimeEnv.INSTANCE.isKuduSupported()) {
+      // Update.
+      RewritesOk("update t2 set name = 'test' from " +
+          "functional.alltypes t1 join functional_kudu.dimtbl t2 on (t1.id = t2.id) " +
+          "where t2.id < 10", 10, 5);
+      RewritesOk("update functional_kudu.dimtbl set name = 'test', zip = 4711 " +
+          "where exists (" + stmt_ + ")", 28, 16);
+      // Delete.
+      RewritesOk("delete a from " +
+          "functional_kudu.testtbl a join functional.testtbl b on a.zip = b.zip", 4, 2);
+      RewritesOk("delete functional_kudu.testtbl where exists (" + stmt_ + ")", 24, 12);
+    }
+  }
+}

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java b/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
index 0a9ad66..3244b20 100644
--- a/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
+++ b/fe/src/test/java/org/apache/impala/common/FrontendTestBase.java
@@ -25,9 +25,6 @@ import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
 
-import org.junit.After;
-import org.junit.Assert;
-
 import org.apache.impala.analysis.AnalysisContext;
 import org.apache.impala.analysis.Analyzer;
 import org.apache.impala.analysis.ColumnDef;
@@ -57,6 +54,9 @@ import org.apache.impala.testutil.TestUtils;
 import org.apache.impala.thrift.TFunctionBinaryType;
 import org.apache.impala.thrift.TQueryCtx;
 import org.apache.impala.thrift.TQueryOptions;
+import org.junit.After;
+import org.junit.Assert;
+
 import com.google.common.base.Joiner;
 import com.google.common.base.Preconditions;
 import com.google.common.collect.Lists;
@@ -183,7 +183,9 @@ public class FrontendTestBase {
     CreateViewStmt createViewStmt = (CreateViewStmt) AnalyzesOk(createViewSql);
     Db db = catalog_.getDb(createViewStmt.getDb());
     Preconditions.checkNotNull(db, "Test views must be created in an existing db.");
-    QueryStmt viewStmt = (QueryStmt) AnalyzesOk(createViewStmt.getInlineViewDef());
+    // Do not analyze the stmt to avoid applying rewrites that would alter the view
+    // definition. We want to model real views as closely as possible.
+    QueryStmt viewStmt = (QueryStmt) ParsesOk(createViewStmt.getInlineViewDef());
     View dummyView = View.createTestView(db, createViewStmt.getTbl(), viewStmt);
     db.addTable(dummyView);
     testTables_.add(dummyView);

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/testdata/workloads/functional-planner/queries/PlannerTest/tpcds-all.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/tpcds-all.test b/testdata/workloads/functional-planner/queries/PlannerTest/tpcds-all.test
index 8144524..c4cbd6f 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpcds-all.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpcds-all.test
@@ -55,7 +55,7 @@ PLAN-ROOT SINK
 |
 00:SCAN HDFS [tpcds.date_dim dt]
    partitions=1/1 files=1 size=9.84MB
-   predicates: dt.d_moy = 12, (dt.d_date_sk BETWEEN 2451149 AND 2451179 OR dt.d_date_sk BETWEEN 2451514 AND 2451544 OR dt.d_date_sk BETWEEN 2451880 AND 2451910 OR dt.d_date_sk BETWEEN 2452245 AND 2452275 OR dt.d_date_sk BETWEEN 2452610 AND 2452640)
+   predicates: dt.d_moy = 12, (dt.d_date_sk >= 2451149 AND dt.d_date_sk <= 2451179 OR dt.d_date_sk >= 2451514 AND dt.d_date_sk <= 2451544 OR dt.d_date_sk >= 2451880 AND dt.d_date_sk <= 2451910 OR dt.d_date_sk >= 2452245 AND dt.d_date_sk <= 2452275 OR dt.d_date_sk >= 2452610 AND dt.d_date_sk <= 2452640)
    runtime filters: RF000 -> dt.d_date_sk
 ---- DISTRIBUTEDPLAN
 PLAN-ROOT SINK
@@ -99,7 +99,7 @@ PLAN-ROOT SINK
 |
 00:SCAN HDFS [tpcds.date_dim dt]
    partitions=1/1 files=1 size=9.84MB
-   predicates: dt.d_moy = 12, (dt.d_date_sk BETWEEN 2451149 AND 2451179 OR dt.d_date_sk BETWEEN 2451514 AND 2451544 OR dt.d_date_sk BETWEEN 2451880 AND 2451910 OR dt.d_date_sk BETWEEN 2452245 AND 2452275 OR dt.d_date_sk BETWEEN 2452610 AND 2452640)
+   predicates: dt.d_moy = 12, (dt.d_date_sk >= 2451149 AND dt.d_date_sk <= 2451179 OR dt.d_date_sk >= 2451514 AND dt.d_date_sk <= 2451544 OR dt.d_date_sk >= 2451880 AND dt.d_date_sk <= 2451910 OR dt.d_date_sk >= 2452245 AND dt.d_date_sk <= 2452275 OR dt.d_date_sk >= 2452610 AND dt.d_date_sk <= 2452640)
    runtime filters: RF000 -> dt.d_date_sk
 ---- PARALLELPLANS
 PLAN-ROOT SINK
@@ -151,7 +151,7 @@ PLAN-ROOT SINK
 |
 00:SCAN HDFS [tpcds.date_dim dt]
    partitions=1/1 files=1 size=9.84MB
-   predicates: dt.d_moy = 12, (dt.d_date_sk BETWEEN 2451149 AND 2451179 OR dt.d_date_sk BETWEEN 2451514 AND 2451544 OR dt.d_date_sk BETWEEN 2451880 AND 2451910 OR dt.d_date_sk BETWEEN 2452245 AND 2452275 OR dt.d_date_sk BETWEEN 2452610 AND 2452640)
+   predicates: dt.d_moy = 12, (dt.d_date_sk >= 2451149 AND dt.d_date_sk <= 2451179 OR dt.d_date_sk >= 2451514 AND dt.d_date_sk <= 2451544 OR dt.d_date_sk >= 2451880 AND dt.d_date_sk <= 2451910 OR dt.d_date_sk >= 2452245 AND dt.d_date_sk <= 2452275 OR dt.d_date_sk >= 2452610 AND dt.d_date_sk <= 2452640)
    runtime filters: RF000 -> dt.d_date_sk
 ====
 # TPCDS-Q7
@@ -1209,7 +1209,7 @@ PLAN-ROOT SINK
 |  |
 |  |--01:SCAN HDFS [tpcds.date_dim]
 |  |     partitions=1/1 files=1 size=9.84MB
-|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom BETWEEN 1 AND 3 OR date_dim.d_dom BETWEEN 25 AND 28)
+|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom >= 1 AND date_dim.d_dom <= 3 OR date_dim.d_dom >= 25 AND date_dim.d_dom <= 28)
 |  |
 |  04:HASH JOIN [INNER JOIN]
 |  |  hash predicates: store_sales.ss_hdemo_sk = household_demographics.hd_demo_sk
@@ -1271,7 +1271,7 @@ PLAN-ROOT SINK
 |  |  |
 |  |  01:SCAN HDFS [tpcds.date_dim]
 |  |     partitions=1/1 files=1 size=9.84MB
-|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom BETWEEN 1 AND 3 OR date_dim.d_dom BETWEEN 25 AND 28)
+|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom >= 1 AND date_dim.d_dom <= 3 OR date_dim.d_dom >= 25 AND date_dim.d_dom <= 28)
 |  |
 |  04:HASH JOIN [INNER JOIN, BROADCAST]
 |  |  hash predicates: store_sales.ss_hdemo_sk = household_demographics.hd_demo_sk
@@ -1347,7 +1347,7 @@ PLAN-ROOT SINK
 |  |  |
 |  |  01:SCAN HDFS [tpcds.date_dim]
 |  |     partitions=1/1 files=1 size=9.84MB
-|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom BETWEEN 1 AND 3 OR date_dim.d_dom BETWEEN 25 AND 28)
+|  |     predicates: date_dim.d_year IN (1998, 1998 + 1, 1998 + 2), (date_dim.d_dom >= 1 AND date_dim.d_dom <= 3 OR date_dim.d_dom >= 25 AND date_dim.d_dom <= 28)
 |  |
 |  04:HASH JOIN [INNER JOIN, BROADCAST]
 |  |  hash predicates: store_sales.ss_hdemo_sk = household_demographics.hd_demo_sk

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
index d883b74..9b17ff1 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
@@ -3415,7 +3415,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- p_partkey
 |
 |--01:SCAN HDFS [tpch.part]
@@ -3437,7 +3437,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- p_partkey
 |
 |--04:EXCHANGE [BROADCAST]
@@ -3461,7 +3461,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- p_partkey
 |
 |--JOIN BUILD

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
index 0b7f35d..a5e6e07 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
@@ -1074,7 +1074,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |
 |--01:SCAN KUDU [tpch_kudu.part]
 |


[4/6] incubator-impala git commit: IMPALA-4309: Introduce Expr rewrite phase and supporting classes.

Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
index 3ecf764..0c3dd9b 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
@@ -2117,7 +2117,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- p_partkey
 |
 |--01:SCAN HDFS [tpch_nested_parquet.part p]
@@ -2139,7 +2139,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN, BROADCAST]
 |  hash predicates: l_partkey = p_partkey
-|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size BETWEEN 1 AND 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size BETWEEN 1 AND 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size BETWEEN 1 AND 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((p_brand = 'Brand#12' AND p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND l_quantity >= 1 AND l_quantity <= 11 AND p_size >= 1 AND p_size <= 5 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#23' AND p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND l_quantity >= 10 AND l_quantity <= 20 AND p_size >= 1 AND p_size <= 10 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON') OR (p_brand = 'Brand#34' AND p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND l_quantity >= 20 AND l_quantity <= 30 AND p_size >= 1 AND p_size <= 15 AND l_shipmode IN ('AIR', 'AIR REG') AND l_shipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- p_partkey
 |
 |--04:EXCHANGE [BROADCAST]

http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1d8cdb02/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
index c4b23f5..de442b2 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
@@ -1253,7 +1253,7 @@ PLAN-ROOT SINK
 |
 02:HASH JOIN [INNER JOIN]
 |  hash predicates: tpch.lineitem.l_partkey = tpch.part.p_partkey
-|  other predicates: ((tpch.part.p_brand = 'Brand#12' AND tpch.part.p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND tpch.lineitem.l_quantity >= 1 AND tpch.lineitem.l_quantity <= 11 AND tpch.part.p_size BETWEEN 1 AND 5 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON') OR (tpch.part.p_brand = 'Brand#23' AND tpch.part.p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND tpch.lineitem.l_quantity >= 10 AND tpch.lineitem.l_quantity <= 20 AND tpch.part.p_size BETWEEN 1 AND 10 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON') OR (tpch.part.p_brand = 'Brand#34' AND tpch.part.p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND tpch.lineitem.l_quantity >= 20 AND tpch.lineitem.l_quantity <= 30 AND tpch.part.p_size BETWEEN 1 AND 15 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON'))
+|  other predicates: ((tpch.part.p_brand = 'Brand#12' AND tpch.part.p_container IN ('SM CASE', 'SM BOX', 'SM PACK', 'SM PKG') AND tpch.lineitem.l_quantity >= 1 AND tpch.lineitem.l_quantity <= 11 AND tpch.part.p_size >= 1 AND tpch.part.p_size <= 5 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON') OR (tpch.part.p_brand = 'Brand#23' AND tpch.part.p_container IN ('MED BAG', 'MED BOX', 'MED PKG', 'MED PACK') AND tpch.lineitem.l_quantity >= 10 AND tpch.lineitem.l_quantity <= 20 AND tpch.part.p_size >= 1 AND tpch.part.p_size <= 10 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON') OR (tpch.part.p_brand = 'Brand#34' AND tpch.part.p_container IN ('LG CASE', 'LG BOX', 'LG PACK', 'LG PKG') AND tpch.lineitem.l_quantity >= 20 AND tpch.lineitem.l_quantity <= 30 AND tpch.part.p_size >= 1 AND tpch.part.p_size <= 15 AND tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG') AND tpch.lineitem.l_sh
 ipinstruct = 'DELIVER IN PERSON'))
 |  runtime filters: RF000 <- tpch.part.p_partkey
 |
 |--01:SCAN HDFS [tpch.part]