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/17 16:09:12 UTC
[01/50] [abbrv] incubator-impala git commit: IMPALA-3771: Expose kudu
client timeout and set default
Repository: incubator-impala
Updated Branches:
refs/heads/hadoop-next eae4f307d -> 32dfcebfa
IMPALA-3771: Expose kudu client timeout and set default
The Kudu client timeout was too low for Impala usage. This
sets the default timeout to 3 minutes and exposes it as a
gflag.
New timeout tests were added.
Change-Id: Iad95e8e38aad4f76d21bac6879db6c02b3c3e045
Reviewed-on: http://gerrit.cloudera.org:8080/4849
Reviewed-by: Matthew Jacobs <mj...@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/50f7753d
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/50f7753d
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/50f7753d
Branch: refs/heads/hadoop-next
Commit: 50f7753d2bf3bde0ea67319b680806a071d69871
Parents: 3e18755
Author: Matthew Jacobs <mj...@cloudera.com>
Authored: Wed Oct 26 17:25:30 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sat Nov 5 06:43:45 2016 +0000
----------------------------------------------------------------------
be/src/catalog/catalog.cc | 6 ++-
be/src/common/global-flags.cc | 8 ++++
be/src/exec/kudu-scan-node.cc | 7 +---
be/src/exec/kudu-scan-node.h | 4 +-
be/src/exec/kudu-scanner.cc | 5 +--
be/src/exec/kudu-table-sink.cc | 14 ++-----
be/src/exec/kudu-table-sink.h | 8 ++--
be/src/exec/kudu-util.cc | 11 +++++
be/src/exec/kudu-util.h | 5 +++
be/src/service/frontend.cc | 7 +++-
.../org/apache/impala/catalog/KuduTable.java | 43 +++++++++-----------
.../org/apache/impala/planner/KuduScanNode.java | 5 +--
.../apache/impala/service/BackendConfig.java | 18 +++++++-
.../org/apache/impala/service/JniCatalog.java | 18 ++++----
.../org/apache/impala/service/JniFrontend.java | 4 +-
.../impala/service/KuduCatalogOpExecutor.java | 32 ++++++++-------
.../java/org/apache/impala/util/KuduUtil.java | 30 ++++++++++----
.../QueryTest/kudu-timeouts-catalogd.test | 25 ++++++++++++
.../QueryTest/kudu-timeouts-impalad.test | 13 ++++++
tests/common/impala_test_suite.py | 3 +-
tests/custom_cluster/test_kudu.py | 24 +++++++++++
21 files changed, 199 insertions(+), 91 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/catalog/catalog.cc
----------------------------------------------------------------------
diff --git a/be/src/catalog/catalog.cc b/be/src/catalog/catalog.cc
index 9e7af4e..7d6fdca 100644
--- a/be/src/catalog/catalog.cc
+++ b/be/src/catalog/catalog.cc
@@ -42,10 +42,11 @@ DEFINE_string(sentry_config, "", "Local path to a sentry-site.xml configuration
"file. If set, authorization will be enabled.");
DECLARE_int32(non_impala_java_vlog);
+DECLARE_int32(kudu_operation_timeout_ms);
Catalog::Catalog() {
JniMethodDescriptor methods[] = {
- {"<init>", "(ZILjava/lang/String;IIZLjava/lang/String;Ljava/lang/String;)V",
+ {"<init>", "(ZILjava/lang/String;IIZLjava/lang/String;Ljava/lang/String;I)V",
&catalog_ctor_},
{"updateCatalog", "([B)[B", &update_metastore_id_},
{"execDdl", "([B)[B", &exec_ddl_id_},
@@ -77,10 +78,11 @@ Catalog::Catalog() {
jboolean auth_to_local = FLAGS_load_auth_to_local_rules && !FLAGS_principal.empty();
jstring principal = jni_env->NewStringUTF(FLAGS_principal.c_str());
jstring local_library_dir = jni_env->NewStringUTF(FLAGS_local_library_dir.c_str());
+ jint kudu_operation_timeout = FLAGS_kudu_operation_timeout_ms;
jobject catalog = jni_env->NewObject(catalog_class_, catalog_ctor_,
load_in_background, num_metadata_loading_threads, sentry_config,
FlagToTLogLevel(FLAGS_v), FlagToTLogLevel(FLAGS_non_impala_java_vlog),
- auth_to_local, principal, local_library_dir);
+ auth_to_local, principal, local_library_dir, kudu_operation_timeout);
EXIT_IF_EXC(jni_env);
ABORT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, catalog, &catalog_));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/common/global-flags.cc
----------------------------------------------------------------------
diff --git a/be/src/common/global-flags.cc b/be/src/common/global-flags.cc
index c67ec2c..f75236c 100644
--- a/be/src/common/global-flags.cc
+++ b/be/src/common/global-flags.cc
@@ -108,8 +108,16 @@ DEFINE_int32(fault_injection_rpc_type, 0, "A fault injection option that specifi
"which rpc call will be injected with the delay. Effective in debug builds only.");
#endif
+// Used for testing the path where the Kudu client is stubbed.
DEFINE_bool(disable_kudu, false, "If true, Kudu features will be disabled.");
+// Timeout (ms) used in the FE for admin and metadata operations (set on the KuduClient),
+// and in the BE for scans and writes (set on the KuduScanner and KuduSession
+// accordingly).
+DEFINE_int32(kudu_operation_timeout_ms, 3 * 60 * 1000, "Timeout (milliseconds) set for "
+ "all Kudu operations. This must be a positive value, and there is no way to disable "
+ "timeouts.");
+
DEFINE_bool(enable_accept_queue_server, true,
"If true, uses a modified version of "
"TThreadedServer that accepts connections as quickly as possible and hands them off "
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-scan-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-scan-node.cc b/be/src/exec/kudu-scan-node.cc
index 1aef102..f98077e 100644
--- a/be/src/exec/kudu-scan-node.cc
+++ b/be/src/exec/kudu-scan-node.cc
@@ -121,12 +121,7 @@ Status KuduScanNode::Open(RuntimeState* state) {
const KuduTableDescriptor* table_desc =
static_cast<const KuduTableDescriptor*>(tuple_desc_->table_desc());
- kudu::client::KuduClientBuilder b;
- for (const string& address: table_desc->kudu_master_addresses()) {
- b.add_master_server_addr(address);
- }
-
- KUDU_RETURN_IF_ERROR(b.Build(&client_), "Unable to create Kudu client");
+ RETURN_IF_ERROR(CreateKuduClient(table_desc->kudu_master_addresses(), &client_));
uint64_t latest_ts = static_cast<uint64_t>(
max<int64_t>(0, state->query_ctx().session.kudu_latest_observed_ts));
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-scan-node.h
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-scan-node.h b/be/src/exec/kudu-scan-node.h
index 79ed480..84e2531 100644
--- a/be/src/exec/kudu-scan-node.h
+++ b/be/src/exec/kudu-scan-node.h
@@ -65,8 +65,8 @@ class KuduScanNode : public ScanNode {
const TupleDescriptor* tuple_desc_;
/// The Kudu client and table. Scanners share these instances.
- std::tr1::shared_ptr<kudu::client::KuduClient> client_;
- std::tr1::shared_ptr<kudu::client::KuduTable> table_;
+ kudu::client::sp::shared_ptr<kudu::client::KuduClient> client_;
+ kudu::client::sp::shared_ptr<kudu::client::KuduTable> table_;
/// Set of scan tokens to be deserialized into Kudu scanners.
std::vector<std::string> scan_tokens_;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-scanner.cc b/be/src/exec/kudu-scanner.cc
index d230985..c13b6a8 100644
--- a/be/src/exec/kudu-scanner.cc
+++ b/be/src/exec/kudu-scanner.cc
@@ -49,8 +49,7 @@ DEFINE_int32(kudu_scanner_keep_alive_period_sec, 15,
"The period at which Kudu Scanners should send keep-alive requests to the tablet "
"server to ensure that scanners do not time out.");
-DEFINE_int32(kudu_scanner_timeout_sec, 60,
- "The timeout used for Kudu Scan requests.");
+DECLARE_int32(kudu_operation_timeout_ms);
namespace impala {
@@ -134,7 +133,7 @@ Status KuduScanner::OpenNextScanToken(const string& scan_token) {
"Could not set replica selection.");
}
- KUDU_RETURN_IF_ERROR(scanner_->SetTimeoutMillis(FLAGS_kudu_scanner_timeout_sec * 1000),
+ KUDU_RETURN_IF_ERROR(scanner_->SetTimeoutMillis(FLAGS_kudu_operation_timeout_ms),
"Could not set scanner timeout");
{
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-table-sink.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.cc b/be/src/exec/kudu-table-sink.cc
index fc26a53..14b1889 100644
--- a/be/src/exec/kudu-table-sink.cc
+++ b/be/src/exec/kudu-table-sink.cc
@@ -31,11 +31,11 @@
#include "common/names.h"
-DEFINE_int32(kudu_session_timeout_seconds, 60, "Timeout set on the Kudu session. "
- "How long to wait before considering a write failed.");
DEFINE_int32(kudu_mutation_buffer_size, 100 * 1024 * 1024, "The size (bytes) of the "
"Kudu client buffer for mutations.");
+DECLARE_int32(kudu_operation_timeout_ms);
+
using kudu::client::KuduColumnSchema;
using kudu::client::KuduSchema;
using kudu::client::KuduClient;
@@ -112,19 +112,13 @@ Status KuduTableSink::Prepare(RuntimeState* state, MemTracker* mem_tracker) {
Status KuduTableSink::Open(RuntimeState* state) {
RETURN_IF_ERROR(Expr::Open(output_expr_ctxs_, state));
-
- kudu::client::KuduClientBuilder b;
- for (const string& address: table_desc_->kudu_master_addresses()) {
- b.add_master_server_addr(address);
- }
-
- KUDU_RETURN_IF_ERROR(b.Build(&client_), "Unable to create Kudu client");
+ RETURN_IF_ERROR(CreateKuduClient(table_desc_->kudu_master_addresses(), &client_));
KUDU_RETURN_IF_ERROR(client_->OpenTable(table_desc_->table_name(), &table_),
"Unable to open Kudu table");
session_ = client_->NewSession();
- session_->SetTimeoutMillis(FLAGS_kudu_session_timeout_seconds * 1000);
+ session_->SetTimeoutMillis(FLAGS_kudu_operation_timeout_ms);
// KuduSession Set* methods here and below return a status for API compatibility.
// As long as the Kudu client is statically linked, these shouldn't fail and thus these
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-table-sink.h
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.h b/be/src/exec/kudu-table-sink.h
index fe278c5..c37b15d 100644
--- a/be/src/exec/kudu-table-sink.h
+++ b/be/src/exec/kudu-table-sink.h
@@ -100,10 +100,10 @@ class KuduTableSink : public DataSink {
std::vector<ExprContext*> output_expr_ctxs_;
/// The Kudu client, table and session.
- /// This uses 'std::tr1::shared_ptr' as that is the type expected by Kudu.
- std::tr1::shared_ptr<kudu::client::KuduClient> client_;
- std::tr1::shared_ptr<kudu::client::KuduTable> table_;
- std::tr1::shared_ptr<kudu::client::KuduSession> session_;
+ /// This uses 'kudu::client::sp::shared_ptr' as that is the type expected by Kudu.
+ kudu::client::sp::shared_ptr<kudu::client::KuduClient> client_;
+ kudu::client::sp::shared_ptr<kudu::client::KuduTable> table_;
+ kudu::client::sp::shared_ptr<kudu::client::KuduSession> session_;
/// Used to specify the type of write operation (INSERT/UPDATE/DELETE).
TSinkAction::type sink_action_;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-util.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-util.cc b/be/src/exec/kudu-util.cc
index aedf229..5afa0a4 100644
--- a/be/src/exec/kudu-util.cc
+++ b/be/src/exec/kudu-util.cc
@@ -28,9 +28,12 @@
#include "common/status.h"
using kudu::client::KuduSchema;
+using kudu::client::KuduClient;
+using kudu::client::KuduClientBuilder;
using kudu::client::KuduColumnSchema;
DECLARE_bool(disable_kudu);
+DECLARE_int32(kudu_operation_timeout_ms);
namespace impala {
@@ -54,6 +57,14 @@ Status CheckKuduAvailability() {
return Status(TErrorCode::KUDU_NOT_SUPPORTED_ON_OS);
}
+Status CreateKuduClient(const vector<string>& master_addrs,
+ kudu::client::sp::shared_ptr<KuduClient>* client) {
+ kudu::client::KuduClientBuilder b;
+ for (const string& address: master_addrs) b.add_master_server_addr(address);
+ KUDU_RETURN_IF_ERROR(b.Build(client), "Unable to create Kudu client");
+ return Status::OK();
+}
+
string KuduSchemaDebugString(const KuduSchema& schema) {
stringstream ss;
for (int i = 0; i < schema.num_columns(); ++i) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/exec/kudu-util.h
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-util.h b/be/src/exec/kudu-util.h
index 7957f7a..7774812 100644
--- a/be/src/exec/kudu-util.h
+++ b/be/src/exec/kudu-util.h
@@ -37,6 +37,11 @@ Status CheckKuduAvailability();
/// Convenience function for the bool equivalent of CheckKuduAvailability().
bool KuduIsAvailable();
+/// Creates a new KuduClient using the specified master adresses. If any error occurs,
+/// 'client' is not set and an error status is returned.
+Status CreateKuduClient(const std::vector<std::string>& master_addrs,
+ kudu::client::sp::shared_ptr<kudu::client::KuduClient>* client);
+
/// Returns a debug string for the KuduSchema.
std::string KuduSchemaDebugString(const kudu::client::KuduSchema& schema);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/be/src/service/frontend.cc
----------------------------------------------------------------------
diff --git a/be/src/service/frontend.cc b/be/src/service/frontend.cc
index ca8ecbb..f8cecfb 100644
--- a/be/src/service/frontend.cc
+++ b/be/src/service/frontend.cc
@@ -33,6 +33,7 @@ DECLARE_string(sentry_config);
DECLARE_int32(non_impala_java_vlog);
DECLARE_bool(load_auth_to_local_rules);
DECLARE_string(principal);
+DECLARE_int32(kudu_operation_timeout_ms);
DEFINE_bool(load_catalog_at_startup, false, "if true, load all catalog data at startup");
@@ -64,7 +65,7 @@ DEFINE_string(kudu_master_hosts, "", "Specifies the default Kudu master(s). The
Frontend::Frontend() {
JniMethodDescriptor methods[] = {
{"<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;"
- "Ljava/lang/String;IIZLjava/lang/String;)V", &fe_ctor_},
+ "Ljava/lang/String;IIZLjava/lang/String;I)V", &fe_ctor_},
{"createExecRequest", "([B)[B", &create_exec_request_id_},
{"getExplainPlan", "([B)Ljava/lang/String;", &get_explain_plan_id_},
{"getHadoopConfig", "([B)[B", &get_hadoop_config_id_},
@@ -114,9 +115,11 @@ Frontend::Frontend() {
// and impala is kerberized.
jboolean auth_to_local = FLAGS_load_auth_to_local_rules && !FLAGS_principal.empty();
jstring kudu_master_hosts = jni_env->NewStringUTF(FLAGS_kudu_master_hosts.c_str());
+ jint kudu_operation_timeout = FLAGS_kudu_operation_timeout_ms;
jobject fe = jni_env->NewObject(fe_class_, fe_ctor_, lazy, server_name,
policy_file_path, sentry_config, auth_provider_class, FlagToTLogLevel(FLAGS_v),
- FlagToTLogLevel(FLAGS_non_impala_java_vlog), auth_to_local, kudu_master_hosts);
+ FlagToTLogLevel(FLAGS_non_impala_java_vlog), auth_to_local, kudu_master_hosts,
+ kudu_operation_timeout);
EXIT_IF_EXC(jni_env);
ABORT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, fe, &fe_));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/KuduTable.java b/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
index a7a5933..6c30077 100644
--- a/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
@@ -23,10 +23,15 @@ import java.util.Set;
import javax.xml.bind.DatatypeConverter;
+import org.apache.hadoop.hive.common.StatsSetupConst;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.impala.analysis.ColumnDef;
import org.apache.impala.analysis.DistributeParam;
-import org.apache.impala.analysis.ToSqlUtils;
import org.apache.impala.common.ImpalaRuntimeException;
+import org.apache.impala.service.BackendConfig;
+import org.apache.impala.service.CatalogOpExecutor;
import org.apache.impala.thrift.TCatalogObjectType;
import org.apache.impala.thrift.TColumn;
import org.apache.impala.thrift.TDistributeByHashParam;
@@ -40,27 +45,21 @@ import org.apache.impala.thrift.TTableDescriptor;
import org.apache.impala.thrift.TTableType;
import org.apache.impala.util.KuduUtil;
import org.apache.impala.util.TResultRowBuilder;
-import org.apache.impala.service.CatalogOpExecutor;
-
-import com.google.common.base.Joiner;
-import com.google.common.base.Preconditions;
-import com.google.common.collect.ImmutableList;
-import com.google.common.collect.Lists;
-
-import org.apache.hadoop.hive.common.StatsSetupConst;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.client.KuduClient;
import org.apache.kudu.client.KuduException;
import org.apache.kudu.client.LocatedTablet;
+import org.apache.kudu.client.PartitionSchema;
import org.apache.kudu.client.PartitionSchema.HashBucketSchema;
import org.apache.kudu.client.PartitionSchema.RangeSchema;
-import org.apache.kudu.client.PartitionSchema;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
/**
* Representation of a Kudu table in the catalog cache.
*/
@@ -94,8 +93,6 @@ public class KuduTable extends Table {
// Key to specify the number of tablet replicas.
public static final String KEY_TABLET_REPLICAS = "kudu.num_tablet_replicas";
- public static final long KUDU_RPC_TIMEOUT_MS = 50000;
-
// Table name in the Kudu storage engine. It may not neccessarily be the same as the
// table name specified in the CREATE TABLE statement; the latter
// is stored in Table.name_. Reasons why KuduTable.kuduTableName_ and Table.name_ may
@@ -172,12 +169,12 @@ public class KuduTable extends Table {
numRows_ = getRowCount(msTable_.getParameters());
// Connect to Kudu to retrieve table metadata
- try (KuduClient kuduClient = new KuduClient.KuduClientBuilder(
- getKuduMasterHosts()).build()) {
+ try (KuduClient kuduClient = KuduUtil.createKuduClient(getKuduMasterHosts())) {
kuduTable = kuduClient.openTable(kuduTableName_);
} catch (KuduException e) {
- LOG.error("Error accessing Kudu table " + kuduTableName_);
- throw new TableLoadingException(e.getMessage());
+ throw new TableLoadingException(String.format(
+ "Error opening Kudu table '%s', Kudu error: %s",
+ kuduTableName_, e.getMessage()));
}
Preconditions.checkNotNull(kuduTable);
@@ -187,7 +184,6 @@ public class KuduTable extends Table {
loadDistributeByParams(kuduTable);
loadAllColumnStats(msClient);
} catch (ImpalaRuntimeException e) {
- LOG.error("Error loading metadata for Kudu table: " + kuduTableName_);
throw new TableLoadingException("Error loading metadata for Kudu table " +
kuduTableName_, e);
}
@@ -341,11 +337,10 @@ public class KuduTable extends Table {
resultSchema.addToColumns(new TColumn("Leader Replica", Type.STRING.toThrift()));
resultSchema.addToColumns(new TColumn("# Replicas", Type.INT.toThrift()));
- try (KuduClient client = new KuduClient.KuduClientBuilder(
- getKuduMasterHosts()).build()) {
+ try (KuduClient client = KuduUtil.createKuduClient(getKuduMasterHosts())) {
org.apache.kudu.client.KuduTable kuduTable = client.openTable(kuduTableName_);
List<LocatedTablet> tablets =
- kuduTable.getTabletsLocations(KUDU_RPC_TIMEOUT_MS);
+ kuduTable.getTabletsLocations(BackendConfig.getKuduClientTimeoutMs());
for (LocatedTablet tab: tablets) {
TResultRowBuilder builder = new TResultRowBuilder();
builder.add("-1"); // The Kudu client API doesn't expose tablet row counts.
@@ -366,7 +361,7 @@ public class KuduTable extends Table {
}
} catch (Exception e) {
- throw new ImpalaRuntimeException("Could not communicate with Kudu.", e);
+ throw new ImpalaRuntimeException("Error accessing Kudu for table stats.", e);
}
return result;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/planner/KuduScanNode.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/KuduScanNode.java b/fe/src/main/java/org/apache/impala/planner/KuduScanNode.java
index 7ef1c20..6f20abd 100644
--- a/fe/src/main/java/org/apache/impala/planner/KuduScanNode.java
+++ b/fe/src/main/java/org/apache/impala/planner/KuduScanNode.java
@@ -44,10 +44,10 @@ import org.apache.impala.thrift.TPlanNodeType;
import org.apache.impala.thrift.TScanRange;
import org.apache.impala.thrift.TScanRangeLocation;
import org.apache.impala.thrift.TScanRangeLocationList;
+import org.apache.impala.util.KuduUtil;
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
import org.apache.kudu.client.KuduClient;
-import org.apache.kudu.client.KuduClient.KuduClientBuilder;
import org.apache.kudu.client.KuduPredicate;
import org.apache.kudu.client.KuduPredicate.ComparisonOp;
import org.apache.kudu.client.KuduScanToken;
@@ -106,8 +106,7 @@ public class KuduScanNode extends ScanNode {
analyzer.createEquivConjuncts(tupleIds_.get(0), conjuncts_);
conjuncts_ = orderConjunctsByCost(conjuncts_);
- try (KuduClient client =
- new KuduClientBuilder(kuduTable_.getKuduMasterHosts()).build()) {
+ try (KuduClient client = KuduUtil.createKuduClient(kuduTable_.getKuduMasterHosts())) {
org.apache.kudu.client.KuduTable rpcTable =
client.openTable(kuduTable_.getKuduTableName());
validateSchema(rpcTable);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/service/BackendConfig.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/BackendConfig.java b/fe/src/main/java/org/apache/impala/service/BackendConfig.java
index 75dd1f7..c90f674 100644
--- a/fe/src/main/java/org/apache/impala/service/BackendConfig.java
+++ b/fe/src/main/java/org/apache/impala/service/BackendConfig.java
@@ -17,6 +17,8 @@
package org.apache.impala.service;
+import com.google.common.base.Preconditions;
+
/**
* This class is meant to provide the FE with impalad backend configuration parameters,
* including command line arguments.
@@ -31,10 +33,15 @@ public class BackendConfig {
// the default FLAGS_read_size used by the IO manager in the backend.
private final long READ_SIZE;
- // This is overriden by JniFrontend/JniCatalog classes with user set configuration.
- // TODO: Read this from backend instead of using static variables.
+ // Variables below are overriden by JniFrontend/JniCatalog with user set configuration.
+ // TODO: Read from backend instead of using static variables.
+
+ // Determines how principal to short name conversion works. See User.java for more info.
private static boolean allowAuthToLocalRules_ = false;
+ // Kudu client timeout (ms).
+ private static int kuduOperationTimeoutMs_ = 3 * 60 * 1000;
+
private BackendConfig() {
// TODO: Populate these by making calls to the backend instead of default constants.
READ_SIZE = 8 * 1024 * 1024L;
@@ -46,4 +53,11 @@ public class BackendConfig {
public static void setAuthToLocal(boolean authToLocal) {
allowAuthToLocalRules_ = authToLocal;
}
+
+ public static int getKuduClientTimeoutMs() { return kuduOperationTimeoutMs_; }
+
+ public static void setKuduClientTimeoutMs(int kuduOperationTimeoutMs) {
+ Preconditions.checkArgument(kuduOperationTimeoutMs > 0);
+ BackendConfig.kuduOperationTimeoutMs_ = kuduOperationTimeoutMs;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/service/JniCatalog.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/JniCatalog.java b/fe/src/main/java/org/apache/impala/service/JniCatalog.java
index b35877f..7993191 100644
--- a/fe/src/main/java/org/apache/impala/service/JniCatalog.java
+++ b/fe/src/main/java/org/apache/impala/service/JniCatalog.java
@@ -21,12 +21,6 @@ import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
-import org.apache.thrift.TException;
-import org.apache.thrift.TSerializer;
-import org.apache.thrift.protocol.TBinaryProtocol;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import org.apache.impala.authorization.SentryConfig;
import org.apache.impala.authorization.User;
import org.apache.impala.catalog.CatalogException;
@@ -36,7 +30,6 @@ import org.apache.impala.catalog.Function;
import org.apache.impala.common.ImpalaException;
import org.apache.impala.common.InternalException;
import org.apache.impala.common.JniUtil;
-import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TCatalogObject;
import org.apache.impala.thrift.TDatabase;
import org.apache.impala.thrift.TDdlExecRequest;
@@ -56,6 +49,12 @@ import org.apache.impala.thrift.TUniqueId;
import org.apache.impala.thrift.TUpdateCatalogRequest;
import org.apache.impala.util.GlogAppender;
import org.apache.impala.util.PatternMatcher;
+import org.apache.thrift.TException;
+import org.apache.thrift.TSerializer;
+import org.apache.thrift.protocol.TBinaryProtocol;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
@@ -81,9 +80,10 @@ public class JniCatalog {
public JniCatalog(boolean loadInBackground, int numMetadataLoadingThreads,
String sentryServiceConfig, int impalaLogLevel, int otherLogLevel,
- boolean allowAuthToLocal, String kerberosPrincipal, String localLibraryPath)
- throws InternalException {
+ boolean allowAuthToLocal, String kerberosPrincipal, String localLibraryPath,
+ int kuduOperationTimeoutMs) throws InternalException {
BackendConfig.setAuthToLocal(allowAuthToLocal);
+ BackendConfig.setKuduClientTimeoutMs(kuduOperationTimeoutMs);
Preconditions.checkArgument(numMetadataLoadingThreads > 0);
// This trick saves having to pass a TLogLevel enum, which is an object and more
// complex to pass through JNI.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/service/JniFrontend.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/JniFrontend.java b/fe/src/main/java/org/apache/impala/service/JniFrontend.java
index 0d502e5..3ef89e3 100644
--- a/fe/src/main/java/org/apache/impala/service/JniFrontend.java
+++ b/fe/src/main/java/org/apache/impala/service/JniFrontend.java
@@ -117,9 +117,11 @@ public class JniFrontend {
*/
public JniFrontend(boolean lazy, String serverName, String authorizationPolicyFile,
String sentryConfigFile, String authPolicyProviderClass, int impalaLogLevel,
- int otherLogLevel, boolean allowAuthToLocal, String defaultKuduMasterHosts)
+ int otherLogLevel, boolean allowAuthToLocal, String defaultKuduMasterHosts,
+ int kuduOperationTimeoutMs)
throws InternalException {
BackendConfig.setAuthToLocal(allowAuthToLocal);
+ BackendConfig.setKuduClientTimeoutMs(kuduOperationTimeoutMs);
GlogAppender.Install(TLogLevel.values()[impalaLogLevel],
TLogLevel.values()[otherLogLevel]);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/service/KuduCatalogOpExecutor.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/KuduCatalogOpExecutor.java b/fe/src/main/java/org/apache/impala/service/KuduCatalogOpExecutor.java
index 18043c2..a2b1fb9 100644
--- a/fe/src/main/java/org/apache/impala/service/KuduCatalogOpExecutor.java
+++ b/fe/src/main/java/org/apache/impala/service/KuduCatalogOpExecutor.java
@@ -17,7 +17,6 @@
package org.apache.impala.service;
-import java.lang.NumberFormatException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
@@ -25,9 +24,6 @@ import java.util.List;
import java.util.Map;
import java.util.Set;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
-
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.impala.catalog.KuduTable;
import org.apache.impala.catalog.Table;
@@ -39,8 +35,8 @@ import org.apache.impala.thrift.TCreateTableParams;
import org.apache.impala.thrift.TDistributeParam;
import org.apache.impala.thrift.TRangePartition;
import org.apache.impala.util.KuduUtil;
-import org.apache.kudu.ColumnSchema.ColumnSchemaBuilder;
import org.apache.kudu.ColumnSchema;
+import org.apache.kudu.ColumnSchema.ColumnSchemaBuilder;
import org.apache.kudu.Schema;
import org.apache.kudu.client.CreateTableOptions;
import org.apache.kudu.client.KuduClient;
@@ -48,6 +44,9 @@ import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.RangePartitionBound;
import org.apache.log4j.Logger;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+
/**
* This is a helper for the CatalogOpExecutor to provide Kudu related DDL functionality
* such as creating and dropping tables from Kudu.
@@ -67,7 +66,7 @@ public class KuduCatalogOpExecutor {
String masterHosts = msTbl.getParameters().get(KuduTable.KEY_MASTER_HOSTS);
LOG.debug(String.format("Creating table '%s' in master '%s'", kuduTableName,
masterHosts));
- try (KuduClient kudu = new KuduClient.KuduClientBuilder(masterHosts).build()) {
+ try (KuduClient kudu = KuduUtil.createKuduClient(masterHosts)) {
// TODO: The IF NOT EXISTS case should be handled by Kudu to ensure atomicity.
// (see KUDU-1710).
if (kudu.tableExists(kuduTableName)) {
@@ -79,7 +78,7 @@ public class KuduCatalogOpExecutor {
CreateTableOptions tableOpts = buildTableOptions(msTbl, params, schema);
kudu.createTable(kuduTableName, schema, tableOpts);
} catch (Exception e) {
- throw new ImpalaRuntimeException(String.format("Error creating table '%s'",
+ throw new ImpalaRuntimeException(String.format("Error creating Kudu table '%s'",
kuduTableName), e);
}
}
@@ -158,14 +157,16 @@ public class KuduCatalogOpExecutor {
// Set the number of table replicas, if specified.
String replication = msTbl.getParameters().get(KuduTable.KEY_TABLET_REPLICAS);
if (!Strings.isNullOrEmpty(replication)) {
+ int parsedReplicas = -1;
try {
- int r = Integer.parseInt(replication);
- Preconditions.checkState(r > 0);
- tableOpts.setNumReplicas(r);
- } catch (NumberFormatException e) {
+ parsedReplicas = Integer.parseInt(replication);
+ Preconditions.checkState(parsedReplicas > 0,
+ "Invalid number of replicas table property:" + replication);
+ } catch (Exception e) {
throw new ImpalaRuntimeException(String.format("Invalid number of table " +
- "replicas specified: '%s'", replication), e);
+ "replicas specified: '%s'", replication));
}
+ tableOpts.setNumReplicas(parsedReplicas);
}
return tableOpts;
}
@@ -182,7 +183,7 @@ public class KuduCatalogOpExecutor {
String masterHosts = msTbl.getParameters().get(KuduTable.KEY_MASTER_HOSTS);
LOG.debug(String.format("Dropping table '%s' from master '%s'", tableName,
masterHosts));
- try (KuduClient kudu = new KuduClient.KuduClientBuilder(masterHosts).build()) {
+ try (KuduClient kudu = KuduUtil.createKuduClient(masterHosts)) {
Preconditions.checkState(!Strings.isNullOrEmpty(tableName));
// TODO: The IF EXISTS case should be handled by Kudu to ensure atomicity.
// (see KUDU-1710).
@@ -211,7 +212,7 @@ public class KuduCatalogOpExecutor {
String masterHosts = msTblCopy.getParameters().get(KuduTable.KEY_MASTER_HOSTS);
LOG.debug(String.format("Loading schema of table '%s' from master '%s'",
kuduTableName, masterHosts));
- try (KuduClient kudu = new KuduClient.KuduClientBuilder(masterHosts).build()) {
+ try (KuduClient kudu = KuduUtil.createKuduClient(masterHosts)) {
if (!kudu.tableExists(kuduTableName)) {
throw new ImpalaRuntimeException(String.format("Table does not exist in Kudu: " +
"'%s'", kuduTableName));
@@ -247,9 +248,10 @@ public class KuduCatalogOpExecutor {
Preconditions.checkState(!Strings.isNullOrEmpty(masterHosts));
String kuduTableName = properties.get(KuduTable.KEY_TABLE_NAME);
Preconditions.checkState(!Strings.isNullOrEmpty(kuduTableName));
- try (KuduClient kudu = new KuduClient.KuduClientBuilder(masterHosts).build()) {
+ try (KuduClient kudu = KuduUtil.createKuduClient(masterHosts)) {
kudu.tableExists(kuduTableName);
} catch (Exception e) {
+ // TODO: This is misleading when there are other errors, e.g. timeouts.
throw new ImpalaRuntimeException(String.format("Kudu table '%s' does not exist " +
"on master '%s'", kuduTableName, masterHosts), e);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/fe/src/main/java/org/apache/impala/util/KuduUtil.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/util/KuduUtil.java b/fe/src/main/java/org/apache/impala/util/KuduUtil.java
index 9ebc480..c50bf25 100644
--- a/fe/src/main/java/org/apache/impala/util/KuduUtil.java
+++ b/fe/src/main/java/org/apache/impala/util/KuduUtil.java
@@ -17,33 +17,49 @@
package org.apache.impala.util;
+import static java.lang.String.format;
+
import java.util.HashSet;
import java.util.List;
-import com.google.common.base.Preconditions;
-import com.google.common.base.Splitter;
-import com.google.common.collect.Lists;
-import com.google.common.collect.Sets;
-
import org.apache.impala.catalog.ScalarType;
import org.apache.impala.catalog.Type;
import org.apache.impala.common.ImpalaRuntimeException;
import org.apache.impala.common.Pair;
+import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TExpr;
import org.apache.impala.thrift.TExprNode;
-
import org.apache.kudu.ColumnSchema;
import org.apache.kudu.Schema;
+import org.apache.kudu.client.KuduClient;
+import org.apache.kudu.client.KuduClient.KuduClientBuilder;
import org.apache.kudu.client.PartialRow;
import org.apache.kudu.client.RangePartitionBound;
-import static java.lang.String.format;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
public class KuduUtil {
private static final String KUDU_TABLE_NAME_PREFIX = "impala::";
/**
+ * Creates a KuduClient with the specified Kudu master addresses (as a comma-separated
+ * list of host:port pairs). The 'admin operation timeout' and the 'operation timeout'
+ * are set to BackendConfig.getKuduClientTimeoutMs(). The 'admin operations timeout' is
+ * used for operations like creating/deleting tables. The 'operation timeout' is used
+ * when fetching tablet metadata.
+ */
+ public static KuduClient createKuduClient(String kuduMasters) {
+ KuduClientBuilder b = new KuduClient.KuduClientBuilder(kuduMasters);
+ b.defaultAdminOperationTimeoutMs(BackendConfig.getKuduClientTimeoutMs());
+ b.defaultOperationTimeoutMs(BackendConfig.getKuduClientTimeoutMs());
+ return b.build();
+ }
+
+ /**
* Creates a PartialRow from a list of range partition boundary values.
*/
private static PartialRow parseRangePartitionBoundaryValues(Schema schema,
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-catalogd.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-catalogd.test b/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-catalogd.test
new file mode 100644
index 0000000..253c139
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-catalogd.test
@@ -0,0 +1,25 @@
+====
+---- QUERY
+# TODO: improve error messages (here and below) when KUDU-1734 is resolved
+describe functional_kudu.alltypes
+---- CATCH
+Error opening Kudu table 'impala::functional_kudu.alltypes'
+====
+---- QUERY
+show create table functional_kudu.alltypes
+---- CATCH
+Error opening Kudu table 'impala::functional_kudu.alltypes'
+====
+---- QUERY
+create table test_kudu (x int primary key)
+distribute by hash(x) into 3 buckets stored as kudu
+---- CATCH
+Error creating Kudu table
+====
+---- QUERY
+create external table test_kudu
+stored as kudu
+tblproperties('kudu.table_name'='doesnt_matter_this_times_out')
+---- CATCH
+Error loading schema of table 'doesnt_matter_this_times_out'
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-impalad.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-impalad.test b/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-impalad.test
new file mode 100644
index 0000000..ba3341e
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/kudu-timeouts-impalad.test
@@ -0,0 +1,13 @@
+====
+---- QUERY
+# Expected timeout while planning the scan node.
+# TODO: improve error messages (here and below) when KUDU-1734 is resolved
+select * from functional_kudu.alltypes
+---- CATCH
+Unable to initialize the Kudu scan node
+====
+---- QUERY
+show table stats functional_kudu.alltypes
+---- CATCH
+Error accessing Kudu for table stats
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/tests/common/impala_test_suite.py
----------------------------------------------------------------------
diff --git a/tests/common/impala_test_suite.py b/tests/common/impala_test_suite.py
index 46b7eee..afa8e2c 100644
--- a/tests/common/impala_test_suite.py
+++ b/tests/common/impala_test_suite.py
@@ -211,7 +211,8 @@ class ImpalaTestSuite(BaseTestSuite):
# Strip newlines so we can split error message into multiple lines
expected_str = expected_str.replace('\n', '')
if expected_str in actual_str: return
- assert False, 'Unexpected exception string: %s' % actual_str
+ assert False, 'Unexpected exception string. Expected: %s\nNot found in actual: %s' % \
+ (expected_str, actual_str)
def __verify_results_and_errors(self, vector, test_section, result, use_db):
"""Verifies that both results and error sections are as expected. Rewrites both
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/50f7753d/tests/custom_cluster/test_kudu.py
----------------------------------------------------------------------
diff --git a/tests/custom_cluster/test_kudu.py b/tests/custom_cluster/test_kudu.py
index 898a29e..bd1584b 100644
--- a/tests/custom_cluster/test_kudu.py
+++ b/tests/custom_cluster/test_kudu.py
@@ -51,3 +51,27 @@ class TestKuduOperations(CustomClusterTestSuite, KuduTestSuite):
'kudu.table_name'='%s')
""" % (table_name, KUDU_MASTER_HOSTS, kudu_table.name))
cursor.execute("DROP TABLE %s" % table_name)
+
+
+class TestKuduClientTimeout(CustomClusterTestSuite, KuduTestSuite):
+ """Kudu tests that set the Kudu client operation timeout to 1ms and expect
+ specific timeout exceptions. While we expect all exercised operations to take at
+ least 1ms, it is possible that some may not and thus the test could be flaky. If
+ this turns out to be the case, specific tests may need to be re-considered or
+ removed."""
+
+ @classmethod
+ def get_workload(cls):
+ return 'functional-query'
+
+ @pytest.mark.execute_serially
+ @CustomClusterTestSuite.with_args(impalad_args="-kudu_operation_timeout_ms=1")
+ def test_impalad_timeout(self, vector):
+ """Check impalad behavior when -kudu_operation_timeout_ms is too low."""
+ self.run_test_case('QueryTest/kudu-timeouts-impalad', vector)
+
+ @pytest.mark.execute_serially
+ @CustomClusterTestSuite.with_args(catalogd_args="-kudu_operation_timeout_ms=1")
+ def test_catalogd_timeout(self, vector):
+ """Check catalogd behavior when -kudu_operation_timeout_ms is too low."""
+ self.run_test_case('QueryTest/kudu-timeouts-catalogd', vector)
[02/50] [abbrv] incubator-impala git commit: IMPALA-4352: test infra:
store Impala/Kudu primary keys in object model
Posted by ta...@apache.org.
IMPALA-4352: test infra: store Impala/Kudu primary keys in object model
Test infrastructure, including the random query generator and the data
migrator, needs to know the primary keys of Impala/Kudu tables. This
test infrastructure keeps Python object models of the tables and
columns. This patch adds the ability to read from source Impala/Kudu
tables via SHOW CREATE TABLE and store primary keys as proper
attributes. The patch also adds tests that ensure the test
infrastructure is always able to read and store the primary keys. This
helps find breakages sooner rather than later. For example, if a
regression to "SHOW CREATE TABLE" or the test infrastructure makes us no
longer able to parse primary keys, GVO or other CI will find the
breakage faster than running the query generator.
I also fixed some flake8 issues in files I touched. There were several
files that had a lot of white space warnings, and I wanted to keep the
patch from getting too large.
Change-Id: Ib654b6cd0e8c2a172ffb7330497be4d4a751e6e5
Reviewed-on: http://gerrit.cloudera.org:8080/4873
Reviewed-by: Michael Brown <mi...@cloudera.com>
Reviewed-by: Taras Bobrovytsky <tb...@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/ac516670
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/ac516670
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/ac516670
Branch: refs/heads/hadoop-next
Commit: ac516670b66b48b54783be6d5b8816ae2273963c
Parents: 50f7753
Author: Michael Brown <mi...@cloudera.com>
Authored: Wed Oct 26 15:38:38 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sat Nov 5 19:27:17 2016 +0000
----------------------------------------------------------------------
tests/comparison/common.py | 46 +++++++++++++++++--
tests/comparison/db_connection.py | 58 +++++++++++++++++++-----
tests/conftest.py | 37 +++++++++++++---
tests/metadata/test_show_create_table.py | 63 +++++++++++++++++++++++----
4 files changed, 175 insertions(+), 29 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ac516670/tests/comparison/common.py
----------------------------------------------------------------------
diff --git a/tests/comparison/common.py b/tests/comparison/common.py
index 9c70fa4..376243d 100644
--- a/tests/comparison/common.py
+++ b/tests/comparison/common.py
@@ -27,10 +27,13 @@ from copy import deepcopy
# lazyily imported using the following function. Keep in mind that python "globals" are
# module local, there is no such thing as a cross-module global.
__ALREADY_IMPORTED = False
+
+
def get_import(name):
+ # noqa below tells flake8 to not warn when it thinks imports are not used
global __ALREADY_IMPORTED
if not __ALREADY_IMPORTED:
- from db_types import (
+ from db_types import ( # noqa
BigInt,
Boolean,
Char,
@@ -41,13 +44,14 @@ def get_import(name):
JOINABLE_TYPES,
Number,
Timestamp)
- from funcs import AggFunc, AnalyticFunc, Func
- from query import InlineView, Subquery, WithClauseInlineView
+ from funcs import AggFunc, AnalyticFunc, Func # noqa
+ from query import InlineView, Subquery, WithClauseInlineView # noqa
for key, value in locals().items():
globals()[key] = value
__ALREADY_IMPORTED = True
return globals()[name]
+
class ValExpr(object):
'''This is class that represents a generic expr that results in a scalar.'''
@@ -259,6 +263,7 @@ class Column(ValExpr):
self.owner = owner
self.name = name
self._exact_type = exact_type
+ self.is_primary_key = False
@property
def exact_type(self):
@@ -489,7 +494,7 @@ class Table(TableExpr):
def __init__(self, name):
self.name = name
- self._cols = [] # can include CollectionColumns and StructColumns
+ self._cols = [] # can include CollectionColumns and StructColumns
self._unique_cols = []
self.alias = None
self.is_visible = True # Tables used in SEMI or ANTI JOINs are invisible
@@ -512,6 +517,39 @@ class Table(TableExpr):
return self.alias or self.name
@property
+ def primary_keys(self):
+ """
+ Return immutable sequence of primary keys.
+ """
+ return tuple(col for col in self._cols if col.is_primary_key)
+
+ @property
+ def primary_key_names(self):
+ """
+ Return immutable sequence for primary key names.
+ """
+ return tuple(col.name for col in self.primary_keys)
+
+ @property
+ def updatable_columns(self):
+ """
+ Return immutable sequence of columns that may be updated (i.e., not primary keys).
+
+ If the table doesn't have primary keys, no columns are updatable.
+ """
+ if self.primary_keys:
+ return tuple(col for col in self._cols if not col.is_primary_key)
+ else:
+ return ()
+
+ @property
+ def updatable_column_names(self):
+ """
+ Return immutable sequence of column names that may be updated
+ """
+ return tuple(col.name for col in self.updatable_columns)
+
+ @property
def cols(self):
result = ValExprList()
for col in self._cols:
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ac516670/tests/comparison/db_connection.py
----------------------------------------------------------------------
diff --git a/tests/comparison/db_connection.py b/tests/comparison/db_connection.py
index 9076da8..5c51ff3 100644
--- a/tests/comparison/db_connection.py
+++ b/tests/comparison/db_connection.py
@@ -23,6 +23,7 @@
'''
import hashlib
import impala.dbapi
+import re
import shelve
from abc import ABCMeta, abstractmethod
from contextlib import closing
@@ -39,7 +40,6 @@ from pyparsing import (
nums,
Suppress,
Word)
-from re import compile
from tempfile import gettempdir
from threading import Lock
from time import time
@@ -74,6 +74,7 @@ MYSQL = "MYSQL"
ORACLE = "ORACLE"
POSTGRESQL = "POSTGRESQL"
+
class DbCursor(object):
'''Wraps a DB API 2 cursor to provide access to the related conn. This class
implements the DB API 2 interface by delegation.
@@ -125,10 +126,10 @@ class DbCursor(object):
return tables
- SQL_TYPE_PATTERN = compile(r'([^()]+)(\((\d+,? ?)*\))?')
+ SQL_TYPE_PATTERN = re.compile(r'([^()]+)(\((\d+,? ?)*\))?')
TYPE_NAME_ALIASES = \
dict((type_.name().upper(), type_.name().upper()) for type_ in EXACT_TYPES)
- TYPES_BY_NAME = dict((type_.name().upper(), type_) for type_ in EXACT_TYPES)
+ TYPES_BY_NAME = dict((type_.name().upper(), type_) for type_ in EXACT_TYPES)
EXACT_TYPES_TO_SQL = dict((type_, type_.name().upper()) for type_ in EXACT_TYPES)
@classmethod
@@ -396,11 +397,13 @@ class DbCursor(object):
raise Exception('unable to parse: {0}, type: {1}'.format(col_name, col_type))
def create_table_from_describe(self, table_name, describe_rows):
+ primary_key_names = self._fetch_primary_key_names(table_name)
table = Table(table_name.lower())
for row in describe_rows:
col_name, data_type = row[:2]
col_type = self.parse_col_desc(data_type)
col = self.create_column(col_name, col_type)
+ col.is_primary_key = col_name in primary_key_names
table.add_col(col)
return table
@@ -526,6 +529,16 @@ class DbCursor(object):
unique_cols.append(cols)
table.unique_cols = unique_cols
+ def _fetch_primary_key_names(self, table_name):
+ """
+ This must return a tuple of strings representing the primary keys of table_name,
+ or an empty tuple if there are no primary keys.
+ """
+ # This is the base method. Since we haven't tested this on Oracle or Mysql or plan
+ # to implement this for those databases, the base method needs to return an empty
+ # tuple.
+ return ()
+
class DbConnection(object):
@@ -558,7 +571,7 @@ class DbConnection(object):
try:
unlink(link)
except OSError as e:
- if not 'No such file' in str(e):
+ if 'No such file' not in str(e):
raise e
try:
symlink(sql_log_path, link)
@@ -641,6 +654,8 @@ class DbConnection(object):
class ImpalaCursor(DbCursor):
+ PK_SEARCH_PATTERN = re.compile('PRIMARY KEY \((?P<keys>.*?)\)')
+
@classmethod
def make_insert_sql_from_data(cls, table, rows):
if not rows:
@@ -673,6 +688,31 @@ class ImpalaCursor(DbCursor):
def cluster(self):
return self.conn.cluster
+ def _fetch_primary_key_names(self, table_name):
+ self.execute("SHOW CREATE TABLE {0}".format(table_name))
+ # This returns 1 column with 1 multiline string row, resembling:
+ #
+ # CREATE TABLE db.table (
+ # pk1 BIGINT,
+ # pk2 BIGINT,
+ # col BIGINT,
+ # PRIMARY KEY (pk1, pk2)
+ # )
+ #
+ # Even a 1-column primary key will be shown as a PRIMARY KEY constraint, like:
+ #
+ # CREATE TABLE db.table (
+ # pk1 BIGINT,
+ # col BIGINT,
+ # PRIMARY KEY (pk1)
+ # )
+ (raw_result,) = self.fetchone()
+ search_result = ImpalaCursor.PK_SEARCH_PATTERN.search(raw_result)
+ if search_result is None:
+ return ()
+ else:
+ return tuple(search_result.group("keys").split(", "))
+
def invalidate_metadata(self, table_name=None):
self.execute("INVALIDATE METADATA %s" % (table_name or ""))
@@ -958,6 +998,10 @@ class MySQLConnection(DbConnection):
PORT = 3306
USER_NAME = "root"
+ def __init__(self, client, conn, db_name=None):
+ DbConnection.__init__(self, client, conn, db_name=db_name)
+ self._session_id = self.execute_and_fetchall('SELECT connection_id()')[0][0]
+
def _connect(self):
try:
import MySQLdb
@@ -973,12 +1017,6 @@ class MySQLConnection(DbConnection):
db=self.db_name)
self._conn.autocommit = True
-class MySQLConnection(DbConnection):
-
- def __init__(self, client, conn, db_name=None):
- DbConnection.__init__(self, client, conn, db_name=db_name)
- self._session_id = self.execute_and_fetchall('SELECT connection_id()')[0][0]
-
@property
def supports_kill_connection(self):
return True
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ac516670/tests/conftest.py
----------------------------------------------------------------------
diff --git a/tests/conftest.py b/tests/conftest.py
index c22de39..c75f117 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -30,6 +30,7 @@ import pytest
from common import KUDU_MASTER_HOSTS
from common.test_result_verifier import QueryTestResult
from tests.common.patterns import is_valid_impala_identifier
+from tests.comparison.db_connection import ImpalaConnection
from tests.util.filesystem_utils import FILESYSTEM, ISILON_WEBHDFS_PORT
logging.basicConfig(level=logging.INFO, format='%(threadName)s: %(message)s')
@@ -246,9 +247,12 @@ def unique_database(request, testid_checksum):
num_dbs = 1
fixture_params = getattr(request, 'param', None)
if fixture_params is not None:
- if "name_prefix" in fixture_params: db_name_prefix = fixture_params["name_prefix"]
- if "sync_ddl" in fixture_params: sync_ddl = fixture_params["sync_ddl"]
- if "num_dbs" in fixture_params: num_dbs = fixture_params["num_dbs"]
+ if "name_prefix" in fixture_params:
+ db_name_prefix = fixture_params["name_prefix"]
+ if "sync_ddl" in fixture_params:
+ sync_ddl = fixture_params["sync_ddl"]
+ if "num_dbs" in fixture_params:
+ num_dbs = fixture_params["num_dbs"]
first_db_name = '{0}_{1}'.format(db_name_prefix, testid_checksum)
db_names = [first_db_name]
@@ -256,8 +260,8 @@ def unique_database(request, testid_checksum):
db_names.append(first_db_name + str(i))
for db_name in db_names:
if not is_valid_impala_identifier(db_name):
- raise ValueError('Unique database name "{0}" is not a valid Impala identifer; check '
- 'test function name or any prefixes for long length or invalid '
+ raise ValueError('Unique database name "{0}" is not a valid Impala identifer; check'
+ ' test function name or any prefixes for long length or invalid '
'characters.'.format(db_name))
def cleanup():
@@ -267,8 +271,8 @@ def unique_database(request, testid_checksum):
request.instance.execute_query_expect_success(
request.instance.client, 'DROP DATABASE `{0}` CASCADE'.format(db_name),
{'sync_ddl': sync_ddl})
- LOG.info('Dropped database "{0}" for test ID "{1}"'.format(db_name,
- str(request.node.nodeid)))
+ LOG.info('Dropped database "{0}" for test ID "{1}"'.format(
+ db_name, str(request.node.nodeid)))
request.addfinalizer(cleanup)
@@ -283,6 +287,7 @@ def unique_database(request, testid_checksum):
str(request.node.nodeid)))
return first_db_name
+
@pytest.yield_fixture
def kudu_client():
"""Provides a new Kudu client as a pytest fixture. The client only exists for the
@@ -401,6 +406,7 @@ def cursor(conn):
with __auto_closed_cursor(conn) as cur:
yield cur
+
@pytest.yield_fixture(scope="class")
def cls_cursor(conn):
"""Provides a new DB-API compliant cursor from a connection provided by the conn()
@@ -441,3 +447,20 @@ def __auto_closed_cursor(conn):
cursor.close()
except Exception as e:
LOG.warn("Error closing Impala cursor: %s", e)
+
+
+@pytest.yield_fixture
+def impala_testinfra_cursor():
+ """
+ Return ImpalaCursor object. Used for "tests of tests" for the infra for the query
+ generator, stress test, etc.
+ """
+ # This differs from the cursors above, which return direct Impyla cursors. Tests that
+ # use this fixture want to interact with the objects in
+ # tests.comparison.db_connection, which need testing.
+ with ImpalaConnection() as conn:
+ cursor = conn.cursor()
+ try:
+ yield cursor
+ finally:
+ cursor.close()
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ac516670/tests/metadata/test_show_create_table.py
----------------------------------------------------------------------
diff --git a/tests/metadata/test_show_create_table.py b/tests/metadata/test_show_create_table.py
index aae9f0c..19841ad 100644
--- a/tests/metadata/test_show_create_table.py
+++ b/tests/metadata/test_show_create_table.py
@@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
import pprint
+import pytest
import re
import shlex
@@ -46,8 +47,8 @@ class TestShowCreateTable(ImpalaTestSuite):
cls.TestMatrix.clear_dimension('exec_option')
# There is no reason to run these tests using all dimensions.
cls.TestMatrix.add_dimension(create_uncompressed_text_dimension(cls.get_workload()))
- cls.TestMatrix.add_constraint(lambda v:
- v.get_value('table_format').file_format == 'text' and
+ cls.TestMatrix.add_constraint(
+ lambda v: v.get_value('table_format').file_format == 'text' and
v.get_value('table_format').compression_codec == 'none')
def test_show_create_table(self, vector, unique_database):
@@ -163,7 +164,8 @@ class TestShowCreateTable(ImpalaTestSuite):
def __remove_properties_maps(self, s):
""" Removes the tblproperties and serdeproperties from the string """
- return re.sub(self.__properties_map_regex("WITH SERDEPROPERTIES"), "",
+ return re.sub(
+ self.__properties_map_regex("WITH SERDEPROPERTIES"), "",
re.sub(self.__properties_map_regex("TBLPROPERTIES"), "", s)).strip()
def __get_properties_map(self, s, properties_map_name):
@@ -194,11 +196,11 @@ class ShowCreateTableTestCase(object):
self.existing_table = True
self.show_create_table_sql = remove_comments(test_section['QUERY']).strip()
elif 'CREATE_TABLE' in test_section:
- self.__process_create_section(test_section['CREATE_TABLE'], test_file_name,
- test_db_name, 'table')
+ self.__process_create_section(
+ test_section['CREATE_TABLE'], test_file_name, test_db_name, 'table')
elif 'CREATE_VIEW' in test_section:
- self.__process_create_section(test_section['CREATE_VIEW'], test_file_name,
- test_db_name, 'view')
+ self.__process_create_section(
+ test_section['CREATE_VIEW'], test_file_name, test_db_name, 'view')
else:
assert 0, 'Error in test file %s. Test cases require a '\
'CREATE_TABLE section.\n%s' %\
@@ -225,7 +227,7 @@ class ShowCreateTableTestCase(object):
if len(tokens) < 3 or tokens[0].lower() != "create":
assert 0, 'Error in test. Invalid CREATE TABLE statement: %s' % (create_table_sql)
if tokens[1].lower() != table_type.lower() and \
- (tokens[1].lower() != "external" or tokens[2].lower() != table_type.lower()):
+ (tokens[1].lower() != "external" or tokens[2].lower() != table_type.lower()):
assert 0, 'Error in test. Invalid CREATE TABLE statement: %s' % (create_table_sql)
if tokens[1].lower() == "external":
@@ -234,3 +236,48 @@ class ShowCreateTableTestCase(object):
else:
# expect a create table table_name ...
return tokens[2]
+
+
+class TestInfraCompat(ImpalaTestSuite):
+ """
+ This test suite ensures our test infra (qgen, stress) can always properly read the
+ output of "SHOW CREATE TABLE" and find primary keys and updatable columns.
+ """
+
+ TABLE_PRIMARY_KEYS_MAPS = [
+ {'table': 'tpch.customer',
+ 'primary_keys': (),
+ 'updatable_columns': ()},
+ {'table': 'tpch_kudu.customer',
+ 'primary_keys': ('c_custkey',),
+ 'updatable_columns': ('c_name', 'c_address', 'c_nationkey', 'c_phone',
+ 'c_acctbal', 'c_mktsegment', 'c_comment')},
+ {'table': 'tpch_kudu.lineitem',
+ 'primary_keys': ('l_orderkey', 'l_partkey', 'l_suppkey', 'l_linenumber'),
+ 'updatable_columns': ('l_quantity', 'l_extendedprice', 'l_discount', 'l_tax',
+ 'l_returnflag', 'l_linestatus', 'l_shipdate', 'l_commitdate',
+ 'l_receiptdate', 'l_shipinstruct', 'l_shipmode',
+ 'l_comment')}]
+
+ @SkipIf.kudu_not_supported
+ @pytest.mark.parametrize('table_primary_keys_map', TABLE_PRIMARY_KEYS_MAPS)
+ def test_primary_key_parse(self, impala_testinfra_cursor, table_primary_keys_map):
+ """
+ Test the query generator's Impala -> Postgres data migrator's ability to parse primary
+ keys via SHOW CREATE TABLE. If this test fails, update _fetch_primary_key_names, or fix
+ the SHOW CREATE TABLE defect.
+ """
+ assert impala_testinfra_cursor._fetch_primary_key_names(
+ table_primary_keys_map['table']) == table_primary_keys_map['primary_keys']
+
+ @SkipIf.kudu_not_supported
+ @pytest.mark.parametrize('table_primary_keys_map', TABLE_PRIMARY_KEYS_MAPS)
+ def test_load_table_with_primary_key_attr(self, impala_testinfra_cursor,
+ table_primary_keys_map):
+ """
+ Test that when we load a table for the query generator that the primary keys are
+ found and stored in the object model.
+ """
+ table = impala_testinfra_cursor.describe_table(table_primary_keys_map['table'])
+ assert table_primary_keys_map['primary_keys'] == table.primary_key_names
+ assert table_primary_keys_map['updatable_columns'] == table.updatable_column_names
[05/50] [abbrv] incubator-impala git commit: IMPALA-4338: test infra
data migrator: include tables' primary keys in PostgreSQL
Posted by ta...@apache.org.
IMPALA-4338: test infra data migrator: include tables' primary keys in PostgreSQL
This patch adds the ability for the test infrastructure's
Impala-to-PostgreSQL data migration tool to recognize whether the Impala
source tables have primary keys, and if so, CREATE the tables in
PostgreSQL with the same primary keys. This is needed especially for
performing CRUD operations by the random query generator for comparison
with Impala/Kudu tables and equivalent PostgreSQL tables.
I modified the make_create_table_sql() implementation to check the
"universal" Python object model of the table's columns. We generate
CREATE TABLE statements with, or without, a PRIMARY KEY clause. For
Impala-side tables that this tool may create, we also ensure that we
only write such a clause when the table's format supports primary keys
(currently Kudu).
When the random query generator runs, it needs to know that the tables
it's examining in both databases are equivalent. It does this by
examining the tables' names, column names, and column types. I have
added whether the column is a primary key as part of this equivalence
test.
Testing:
- The patch includes some unit and system tests for the tool.
- Actually migrated a few small Kudu and HDFS tables from Impala into
both PostgreSQL 9.3 and 9.5 and examined the tables in PostgreSQL to
make sure they had primary keys (or not) as expected.
- Very short discrepancy_searcher.py --explain-only runs to test positive
and negative cases of Impala/PostgreSQL equivalency.
Change-Id: I447f022e2dc3d4fc8373b7f388c7875a869921b8
Reviewed-on: http://gerrit.cloudera.org:8080/4951
Reviewed-by: Taras Bobrovytsky <tb...@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/822b2ca1
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/822b2ca1
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/822b2ca1
Branch: refs/heads/hadoop-next
Commit: 822b2ca1c6a9bb09328857b59851035260be851f
Parents: 7c00188
Author: Michael Brown <mi...@cloudera.com>
Authored: Tue Nov 1 17:54:14 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sun Nov 6 06:50:48 2016 +0000
----------------------------------------------------------------------
tests/comparison/db_connection.py | 88 ++++++++++++--
tests/comparison/tests/fake_query.py | 9 +-
tests/comparison/tests/test_cursor.py | 184 +++++++++++++++++++++++++++++
3 files changed, 271 insertions(+), 10 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/822b2ca1/tests/comparison/db_connection.py
----------------------------------------------------------------------
diff --git a/tests/comparison/db_connection.py b/tests/comparison/db_connection.py
index 5c51ff3..8e35031 100644
--- a/tests/comparison/db_connection.py
+++ b/tests/comparison/db_connection.py
@@ -41,6 +41,7 @@ from pyparsing import (
Suppress,
Word)
from tempfile import gettempdir
+from textwrap import dedent
from threading import Lock
from time import time
@@ -113,6 +114,14 @@ class DbCursor(object):
' It has a different number of columns across databases.', table_name)
mismatch = True
break
+ if common_table.primary_key_names != table.primary_key_names:
+ LOG.debug(
+ 'Ignoring table {name} because of differing primary keys: '
+ '{common_table_keys} vs. {table_keys}'.format(
+ name=table_name, common_table_keys=common_table.primary_key_names,
+ table_keys=table.primary_key_names))
+ mismatch = True
+ break
for left, right in izip(common_table.cols, table.cols):
if not left.name == right.name and left.type == right.type:
LOG.debug('Ignoring table %s. It has different columns %s vs %s.' %
@@ -438,13 +447,34 @@ class DbCursor(object):
LOG.debug('Created table %s', table.name)
def make_create_table_sql(self, table):
- sql = 'CREATE TABLE %s (%s)' % (
- table.name,
- ', '.join('%s %s' %
- (col.name, self.get_sql_for_data_type(col.exact_type)) +
- ('' if self.conn.data_types_are_implictly_nullable else ' NULL')
- for col in table.cols))
- return sql
+ column_declarations = []
+ primary_key_names = []
+ for col in table.cols:
+ if col.is_primary_key:
+ null_constraint = ''
+ primary_key_names.append(col.name)
+ elif self.conn.data_types_are_implictly_nullable:
+ null_constraint = ''
+ else:
+ null_constraint = ' NULL'
+ column_declaration = '{name} {col_type}{null_constraint}'.format(
+ name=col.name, col_type=self.get_sql_for_data_type(col.exact_type),
+ null_constraint=null_constraint)
+ column_declarations.append(column_declaration)
+
+ if primary_key_names:
+ primary_key_constraint = ', PRIMARY KEY ({keys})'.format(
+ keys=', '.join(primary_key_names))
+ else:
+ primary_key_constraint = ''
+
+ create_table = ('CREATE TABLE {table_name} ('
+ '{all_columns}'
+ '{primary_key_constraint}'
+ ')'.format(
+ table_name=table.name, all_columns=', '.join(column_declarations),
+ primary_key_constraint=primary_key_constraint))
+ return create_table
def get_sql_for_data_type(self, data_type):
if issubclass(data_type, VarChar):
@@ -655,6 +685,7 @@ class DbConnection(object):
class ImpalaCursor(DbCursor):
PK_SEARCH_PATTERN = re.compile('PRIMARY KEY \((?P<keys>.*?)\)')
+ STORAGE_FORMATS_WITH_PRIMARY_KEYS = ('KUDU',)
@classmethod
def make_insert_sql_from_data(cls, table, rows):
@@ -757,6 +788,28 @@ class ImpalaCursor(DbCursor):
def make_create_table_sql(self, table):
sql = super(ImpalaCursor, self).make_create_table_sql(table)
+
+ if table.primary_keys:
+ if table.storage_format in ImpalaCursor.STORAGE_FORMATS_WITH_PRIMARY_KEYS:
+ # IMPALA-4424 adds support for parametrizing the partitions; for now, on our
+ # small scale, this is ok, especially since the model is to migrate tables from
+ # Impala into Postgres anyway. 3 was chosen for the buckets because our
+ # minicluster tends to have 3 tablet servers, but otherwise it's arbitrary and
+ # provides valid syntax for creating Kudu tables in Impala.
+ sql += '\nDISTRIBUTE BY HASH ({col}) INTO 3 BUCKETS'.format(
+ col=table.primary_key_names[0])
+ else:
+ raise Exception(
+ 'table representation has primary keys {keys} but is not in a format that '
+ 'supports them: {storage_format}'.format(
+ keys=str(table.primary_key_names),
+ storage_format=table.storage_format))
+ elif table.storage_format in ImpalaCursor.STORAGE_FORMATS_WITH_PRIMARY_KEYS:
+ raise Exception(
+ 'table representation has storage format {storage_format} '
+ 'but does not have any primary keys'.format(
+ storage_format=table.storage_format))
+
if table.storage_format != 'TEXTFILE':
sql += "\nSTORED AS " + table.storage_format
if table.storage_location:
@@ -947,6 +1000,27 @@ class PostgresqlCursor(DbCursor):
return 'VARCHAR(%s)' % String.MAX
return super(PostgresqlCursor, self).get_sql_for_data_type(data_type)
+ def _fetch_primary_key_names(self, table_name):
+ # see:
+ # https://www.postgresql.org/docs/9.5/static/infoschema-key-column-usage.html
+ # https://www.postgresql.org/docs/9.5/static/infoschema-table-constraints.html
+ sql = dedent('''
+ SELECT
+ key_cols.column_name AS column_name
+ FROM
+ information_schema.key_column_usage key_cols,
+ information_schema.table_constraints table_constraints
+ WHERE
+ key_cols.constraint_catalog = table_constraints.constraint_catalog AND
+ key_cols.table_name = table_constraints.table_name AND
+ key_cols.constraint_name = table_constraints.constraint_name AND
+ table_constraints.constraint_type = 'PRIMARY KEY' AND
+ key_cols.table_name = '{table_name}'
+ ORDER BY key_cols.ordinal_position'''.format(table_name=table_name))
+ self.execute(sql)
+ rows = self.fetchall()
+ return tuple(row[0] for row in rows)
+
class PostgresqlConnection(DbConnection):
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/822b2ca1/tests/comparison/tests/fake_query.py
----------------------------------------------------------------------
diff --git a/tests/comparison/tests/fake_query.py b/tests/comparison/tests/fake_query.py
index 1241b73..3bf1410 100644
--- a/tests/comparison/tests/fake_query.py
+++ b/tests/comparison/tests/fake_query.py
@@ -37,17 +37,19 @@ from tests.comparison.funcs import AnalyticFirstValue
from tests.comparison.query import Query, SelectClause, SelectItem
-def FakeColumn(name, type_):
+def FakeColumn(name, type_, is_primary_key=False):
"""
Return a Column, the creation of which allows the user not to have to specify the
first argument, which is the table to which the column belongs.
Typical use should be when creating a FakeTable, use FakeColumns as arguments.
"""
- return Column(None, name, type_)
+ col = Column(None, name, type_)
+ col.is_primary_key = is_primary_key
+ return col
-def FakeTable(name, fake_columns):
+def FakeTable(name, fake_columns, storage_format='TEXTFILE'):
"""
Return a Table consisting of one or more FakeColumns. Because Columns are added via
method, we support nesting here instead.
@@ -57,6 +59,7 @@ def FakeTable(name, fake_columns):
raise Exception('You must supply at least one FakeColumn argument')
for fake_column in fake_columns:
table.add_col(fake_column)
+ table.storage_format = storage_format
return table
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/822b2ca1/tests/comparison/tests/test_cursor.py
----------------------------------------------------------------------
diff --git a/tests/comparison/tests/test_cursor.py b/tests/comparison/tests/test_cursor.py
new file mode 100644
index 0000000..972a7f2
--- /dev/null
+++ b/tests/comparison/tests/test_cursor.py
@@ -0,0 +1,184 @@
+# 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.
+
+
+import pytest
+
+from tests.comparison.db_connection import ImpalaConnection, PostgresqlConnection
+from tests.comparison.db_connection import ImpalaCursor, PostgresqlCursor
+from tests.comparison.db_types import Char, Int
+from fake_query import FakeColumn, FakeTable
+
+
+# These are fake connection objects that provide some data needed to "unit test" infra
+# cursor implementations.
+class FakeImpalaConnection(ImpalaConnection):
+ def _connect(self):
+ pass
+
+
+class FakePostgresqlConnection(PostgresqlConnection):
+ def _connect(self):
+ pass
+
+
+@pytest.fixture
+def unittest_cursor_map(request):
+ """
+ Given a dictionary parameter to the fixture with the class key/value set as a cursor
+ class, return a connectionless, "fake" cursor. The cursor is accessible via the
+ fixture's 'cursor' key in the test methods.
+
+ The fixture parameter dictionary can be annotated with other arbitrary key/values that
+ describe expectations for that particular cursor and test case.
+ """
+ connection_map = {
+ ImpalaCursor: FakeImpalaConnection,
+ PostgresqlCursor: FakePostgresqlConnection
+ }
+ cursor_class = request.param['class']
+ connection_class = connection_map[cursor_class]
+ fake_connection_obj = connection_class()
+ request.param['cursor'] = cursor_class(fake_connection_obj, None)
+ return request.param
+
+
+@pytest.yield_fixture
+def postgresql_cursor():
+ """
+ Yield a PostgresqlCursor object needed for test infra system tests.
+ """
+ with PostgresqlConnection() as conn:
+ cursor = conn.cursor()
+ try:
+ yield cursor
+ finally:
+ cursor.close()
+
+
+@pytest.mark.parametrize(
+ 'unittest_cursor_map', [
+ {'class': ImpalaCursor,
+ 'sql': {'two_cols': 'CREATE TABLE two_cols (col1 INT, col2 INT)',
+ 'one_pk': 'CREATE TABLE one_pk (col1 INT, col2 INT, '
+ 'PRIMARY KEY (col1))\n'
+ 'DISTRIBUTE BY HASH (col1) INTO 3 BUCKETS\n'
+ 'STORED AS KUDU',
+ 'three_pks': 'CREATE TABLE three_pks (col1 INT, col2 CHAR(255), '
+ 'col3 INT, col4 INT, PRIMARY KEY (col1, col2, col3))\n'
+ 'DISTRIBUTE BY HASH (col1) INTO 3 BUCKETS\n'
+ 'STORED AS KUDU'}},
+ {'class': PostgresqlCursor,
+ 'sql': {'two_cols': 'CREATE TABLE two_cols (col1 INTEGER NULL, '
+ 'col2 INTEGER NULL)',
+ 'one_pk': 'CREATE TABLE one_pk (col1 INTEGER, col2 INTEGER NULL, '
+ 'PRIMARY KEY (col1))',
+ 'three_pks': 'CREATE TABLE three_pks (col1 INTEGER, col2 CHAR(255), '
+ 'col3 INTEGER, col4 INTEGER NULL, '
+ 'PRIMARY KEY (col1, col2, col3))'}},
+ ], indirect=True)
+@pytest.mark.parametrize(
+ 'table_data', [
+ {'descr': 'two_cols',
+ 'data': FakeTable('two_cols', (FakeColumn('col1', Int),
+ FakeColumn('col2', Int)))},
+ {'descr': 'one_pk',
+ 'data': FakeTable('one_pk', (FakeColumn('col1', Int, is_primary_key=True),
+ FakeColumn('col2', Int)),
+ storage_format='KUDU')},
+ {'descr': 'three_pks',
+ 'data': FakeTable('three_pks', (FakeColumn('col1', Int, is_primary_key=True),
+ FakeColumn('col2', Char, is_primary_key=True),
+ FakeColumn('col3', Int, is_primary_key=True),
+ FakeColumn('col4', Int)),
+ storage_format='KUDU')},
+ ])
+def test_make_create_table_sql(unittest_cursor_map, table_data):
+ """
+ Test that for a given Table representation, both the Impala and PostgreSQL cursor
+ objects generate valid SQL for creating their tables.
+ """
+ which_sql = table_data['descr']
+ table_object = table_data['data']
+ expected_sql = unittest_cursor_map['sql'][which_sql]
+ cursor = unittest_cursor_map['cursor']
+ assert expected_sql == cursor.make_create_table_sql(table_object)
+
+
+@pytest.mark.parametrize(
+ 'unittest_cursor_map', [
+ {'class': ImpalaCursor,
+ 'exceptions_text': {
+ 'text_with_pk': "table representation has primary keys ('col1',) but is "
+ 'not in a format that supports them: TEXTFILE',
+ 'kudu_without_pk': 'table representation has storage format KUDU but does '
+ 'not have any primary keys'}}
+ ], indirect=True)
+@pytest.mark.parametrize(
+ 'table_data', [
+ {'descr': 'text_with_pk',
+ 'data': FakeTable('two_cols', (FakeColumn('col1', Int, is_primary_key=True),
+ FakeColumn('col2', Int)))},
+ {'descr': 'kudu_without_pk',
+ 'data': FakeTable('two_cols', (FakeColumn('col1', Int),
+ FakeColumn('col2', Int)),
+ storage_format='KUDU')},
+
+ ])
+def test_invalid_tables(unittest_cursor_map, table_data):
+ """
+ Test that for a given invalid Table representation considering primary keys and
+ storage formats, the ImpalaCursor properly fails to generate the SQL needed to create
+ the table.
+ """
+ table_object = table_data['data']
+ cursor = unittest_cursor_map['cursor']
+ which_test = table_data['descr']
+ expected_exception_text = unittest_cursor_map['exceptions_text'][which_test]
+ # http://doc.pytest.org/en/latest/assert.html#assertions-about-expected-exceptions
+ with pytest.raises(Exception) as excinfo:
+ cursor.make_create_table_sql(table_object)
+ assert str(excinfo.value) == expected_exception_text
+
+
+# TODO: It's not worth it now, but in the future, if we need to interact with postgresql
+# with a bunch of infra tests, we should consider some more sophisticated data
+# structures and fixtures to handle things in parallel and to reduce code reuse.
+@pytest.mark.parametrize(
+ 'sql_primary_key_map', [
+ {'sql': 'CREATE TABLE mytable (col1 INTEGER NULL, col2 INTEGER NULL)',
+ 'primary_keys': ()},
+ {'sql': ('CREATE TABLE mytable (col1 INTEGER, col2 INTEGER NULL, '
+ 'PRIMARY KEY (col1))'),
+ 'primary_keys': ('col1',)},
+ {'sql': ('CREATE TABLE mytable (col1 INTEGER, col2 CHAR(255), col3 INTEGER, '
+ 'col4 INTEGER NULL, PRIMARY KEY (col1, col2, col3))'),
+ 'primary_keys': ('col1', 'col2', 'col3')}
+ ])
+def test_postgres_table_reading(postgresql_cursor, sql_primary_key_map):
+ """
+ Test that when a postgres table is read by the Postgresql cursor, the Table object
+ contains the correct primary keys. This tests interacts with the local PostgreSQL
+ database that's part of the minicluster.
+ """
+ try:
+ postgresql_cursor.execute('DROP TABLE IF EXISTS mytable')
+ postgresql_cursor.execute(sql_primary_key_map['sql'])
+ table = postgresql_cursor.describe_table('mytable')
+ assert table.primary_key_names == sql_primary_key_map['primary_keys']
+ finally:
+ postgresql_cursor.execute('DROP TABLE mytable')
[41/50] [abbrv] incubator-impala git commit: IMPALA-4433: Always
generate testdata using the same time zone setting
Posted by ta...@apache.org.
IMPALA-4433: Always generate testdata using the same time zone setting
Before this change, testdata was generated using the
java.util.TimeZone.getDefault() TimeZone of the machine it was running
on. This patch standardizes on "America/Los_Angeles", which matches
the existing expected results in the end-to-end tests.
Change-Id: Iaf7cc796e44e9ff64880f9ae852f40961592f279
Reviewed-on: http://gerrit.cloudera.org:8080/5058
Reviewed-by: Jim Apple <jb...@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/0ea4a666
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/0ea4a666
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/0ea4a666
Branch: refs/heads/hadoop-next
Commit: 0ea4a666dc12e093cc12ca4cd640f0ede51661a2
Parents: f4a5d86
Author: Jim Apple <jb...@cloudera.com>
Authored: Fri Nov 11 12:05:30 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 04:18:33 2016 +0000
----------------------------------------------------------------------
.../java/org/apache/impala/datagenerator/TestDataGenerator.java | 5 +++++
1 file changed, 5 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0ea4a666/testdata/src/main/java/org/apache/impala/datagenerator/TestDataGenerator.java
----------------------------------------------------------------------
diff --git a/testdata/src/main/java/org/apache/impala/datagenerator/TestDataGenerator.java b/testdata/src/main/java/org/apache/impala/datagenerator/TestDataGenerator.java
index 7753ac0..29fd0d7 100644
--- a/testdata/src/main/java/org/apache/impala/datagenerator/TestDataGenerator.java
+++ b/testdata/src/main/java/org/apache/impala/datagenerator/TestDataGenerator.java
@@ -25,6 +25,7 @@ import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
+import java.util.TimeZone;
class TestDataGenerator {
// 2 years
@@ -152,6 +153,10 @@ class TestDataGenerator {
System.err.println("Usage: " + "TestDataGenerator BaseOutputDirectory");
}
+ // The TimeZone should be the same no matter what the TimeZone is of the computer
+ // running this code, in order to ensure the generated data is always the same.
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+
// Generate AllTypes
String dirName = args[0] + "/AllTypes";
File dir = new File(dirName);
[25/50] [abbrv] incubator-impala git commit: IMPALA-1430,
IMPALA-4108: codegen all builtin aggregate functions
Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/java-udf.test b/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
index c473fdf..c4e2f1c 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
@@ -1,20 +1,20 @@
====
---- QUERY
-select udf_test.hive_pi()
+select hive_pi()
---- RESULTS
3.141592653589793
---- TYPES
DOUBLE
====
---- QUERY
-select udf_test.hive_bin(100)
+select hive_bin(100)
---- RESULTS
'1100100'
---- TYPES
STRING
====
---- QUERY
-select min(udf_test.hive_pi()) from functional.alltypesagg
+select min(hive_pi()) from functional.alltypesagg
---- RESULTS
3.141592653589793
---- TYPES
@@ -22,49 +22,49 @@ DOUBLE
====
---- QUERY
# Test identity functions
-select udf_test.identity(true);
+select identity(true);
---- TYPES
boolean
---- RESULTS
true
====
---- QUERY
-select udf_test.identity(cast(10 as tinyint));
+select identity(cast(10 as tinyint));
---- TYPES
tinyint
---- RESULTS
10
====
---- QUERY
-select udf_test.identity(cast(10 as smallint));
+select identity(cast(10 as smallint));
---- TYPES
smallint
---- RESULTS
10
====
---- QUERY
-select udf_test.identity(cast(10 as int));
+select identity(cast(10 as int));
---- TYPES
int
---- RESULTS
10
====
---- QUERY
-select udf_test.identity(cast(10 as bigint));
+select identity(cast(10 as bigint));
---- TYPES
bigint
---- RESULTS
10
====
---- QUERY
-select udf_test.identity(cast(10.0 as float));
+select identity(cast(10.0 as float));
---- TYPES
float
---- RESULTS
10
====
---- QUERY
-select udf_test.identity(cast(10.0 as double));
+select identity(cast(10.0 as double));
---- TYPES
double
---- RESULTS
@@ -73,16 +73,16 @@ double
---- QUERY
# IMPALA-1456. Each "identity" call below tests a different type (BytesWritable, Text,
# and String).
-select udf_test.identity("why hello there"),
- udf_test.identity("why", " hello there"),
- udf_test.identity("why", " hello", " there");
+select identity("why hello there"),
+ identity("why", " hello there"),
+ identity("why", " hello", " there");
---- TYPES
string, string, string
---- RESULTS
'why hello there','why hello there','why hello there'
====
---- QUERY
-select udf_test.identity(NULL);
+select identity(NULL);
---- TYPES
boolean
---- RESULTS
@@ -91,9 +91,9 @@ NULL
---- QUERY
# IMPALA-1134. Each "identity" call below tests a different type (BytesWritable, Text,
# and String). The different types are handled slightly differently.
-select length(udf_test.identity("0123456789")),
- length(udf_test.identity("0123456789", "0123456789")),
- length(udf_test.identity("0123456789", "0123456789", "0123456789"));
+select length(identity("0123456789")),
+ length(identity("0123456789", "0123456789")),
+ length(identity("0123456789", "0123456789", "0123456789"));
---- TYPES
int, int, int
---- RESULTS
@@ -101,14 +101,14 @@ int, int, int
====
---- QUERY
# IMPALA-1392: Hive UDFs that throw exceptions should return NULL
-select udf_test.throws_exception();
+select throws_exception();
---- TYPES
boolean
---- RESULTS
NULL
====
---- QUERY
-select udf_test.throws_exception() from functional.alltypestiny;
+select throws_exception() from functional.alltypestiny;
---- TYPES
boolean
---- RESULTS
@@ -122,49 +122,49 @@ NULL
NULL
====
---- QUERY
-select udf_test.hive_add(cast(1 as int), cast(2 as int));
+select hive_add(cast(1 as int), cast(2 as int));
---- TYPES
int
---- RESULTS
3
====
---- QUERY
-select udf_test.hive_add(udf_test.hive_add(cast(1 as int), cast(2 as int)), cast(2 as int));
+select hive_add(hive_add(cast(1 as int), cast(2 as int)), cast(2 as int));
---- TYPES
int
---- RESULTS
5
====
---- QUERY
-select udf_test.hive_add(cast(udf_test.hive_add(cast(1 as int), cast(2 as int)) - udf_test.hive_add(cast(2 as int), cast(1 as int)) as int), cast(2 as int));
+select hive_add(cast(hive_add(cast(1 as int), cast(2 as int)) - hive_add(cast(2 as int), cast(1 as int)) as int), cast(2 as int));
---- TYPES
int
---- RESULTS
2
====
---- QUERY
-select udf_test.hive_add(cast(1 as smallint), cast(2 as smallint));
+select hive_add(cast(1 as smallint), cast(2 as smallint));
---- TYPES
smallint
---- RESULTS
3
====
---- QUERY
-select udf_test.hive_add(cast(1.0 as float), cast(2.0 as float));
+select hive_add(cast(1.0 as float), cast(2.0 as float));
---- TYPES
float
---- RESULTS
3.0
====
---- QUERY
-select udf_test.hive_add(cast(1.0 as double), cast(2.0 as double));
+select hive_add(cast(1.0 as double), cast(2.0 as double));
---- TYPES
double
---- RESULTS
3.0
====
---- QUERY
-select udf_test.hive_add(cast(1 as boolean), cast(0 as boolean));
+select hive_add(cast(1 as boolean), cast(0 as boolean));
---- TYPES
boolean
---- RESULTS
@@ -172,63 +172,63 @@ false
====
---- QUERY
# Testing whether all of persistent Java udfs are accessible.
-select java_udfs_test.identity(true);
+select identity_anytype(true);
---- TYPES
boolean
---- RESULTS
true
====
---- QUERY
-select java_udfs_test.identity(cast(10 as tinyint));
+select identity_anytype(cast(10 as tinyint));
---- TYPES
tinyint
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity(cast(10 as smallint));
+select identity_anytype(cast(10 as smallint));
---- TYPES
smallint
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity(cast(10 as int));
+select identity_anytype(cast(10 as int));
---- TYPES
int
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity(cast(10 as bigint));
+select identity_anytype(cast(10 as bigint));
---- TYPES
bigint
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity(cast(10.0 as float));
+select identity_anytype(cast(10.0 as float));
---- TYPES
float
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity(cast(10.0 as double));
+select identity_anytype(cast(10.0 as double));
---- TYPES
double
---- RESULTS
10
====
---- QUERY
-select java_udfs_test.identity("a", "b");
+select identity_anytype("a", "b");
---- TYPES
string
---- RESULTS
'ab'
====
---- QUERY
-select java_udfs_test.identity("a", "b", "c");
+select identity_anytype("a", "b", "c");
---- TYPES
string
---- RESULTS
@@ -238,37 +238,37 @@ string
# IMPALA-3378: test many Java UDFs being opened and run concurrently
select * from
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(bool_col) union all
+ where identity(bool_col) union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(tinyint_col) > 1 union all
+ where identity(tinyint_col) > 1 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(smallint_col) > 1 union all
+ where identity(smallint_col) > 1 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(int_col) > 1 union all
+ where identity(int_col) > 1 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(bigint_col) > 1 union all
+ where identity(bigint_col) > 1 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(float_col) > 1.0 union all
+ where identity(float_col) > 1.0 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(double_col) > 1.0 union all
+ where identity(double_col) > 1.0 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(string_col) > '1' union all
+ where identity(string_col) > '1' union all
(select max(int_col) from functional.alltypesagg
- where not udf_test.identity(bool_col) union all
+ where not identity(bool_col) union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(tinyint_col) > 2 union all
+ where identity(tinyint_col) > 2 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(smallint_col) > 2 union all
+ where identity(smallint_col) > 2 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(int_col) > 2 union all
+ where identity(int_col) > 2 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(bigint_col) > 2 union all
+ where identity(bigint_col) > 2 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(float_col) > 2.0 union all
+ where identity(float_col) > 2.0 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(double_col) > 2.0 union all
+ where identity(double_col) > 2.0 union all
(select max(int_col) from functional.alltypesagg
- where udf_test.identity(string_col) > '2'
+ where identity(string_col) > '2'
)))))))))))))))) v
---- TYPES
INT
@@ -301,7 +301,7 @@ values('toast'), ('scone'), ('stuff'), ('sssss'), ('yes'), ('scone'), ('stuff');
# Regression test for IMPALA-4266: memory management bugs with output strings from
# Java UDFS, exposed by using the UDF as a grouping key in an aggregation.
# The UDF replaces "s" with "ss" in the strings.
-select distinct udf_test.replace_string(_c0) as es
+select distinct replace_string(_c0) as es
from replace_string_input
order by 1;
---- TYPES
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/libs_with_same_filenames.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/libs_with_same_filenames.test b/testdata/workloads/functional-query/queries/QueryTest/libs_with_same_filenames.test
index cb46d9c..64fdced 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/libs_with_same_filenames.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/libs_with_same_filenames.test
@@ -1,24 +1,21 @@
====
---- QUERY
-drop function if exists same_lib_filename_udf_test.no_args();
-drop function if exists same_lib_filename_udf_test.no_args2();
-
-create function same_lib_filename_udf_test.no_args() returns string
+create function no_args() returns string
location '$FILESYSTEM_PREFIX/test-warehouse/libTestUdfs.so' symbol='NoArgs';
-create function same_lib_filename_udf_test.no_args2() returns string
+create function no_args2() returns string
location '$FILESYSTEM_PREFIX/test-warehouse/udf_test/libTestUdfs.so' symbol='NoArgs';
---- RESULTS
====
---- QUERY
-select same_lib_filename_udf_test.no_args();
+select no_args();
---- TYPES
string
---- RESULTS
'string'
====
---- QUERY
-select same_lib_filename_udf_test.no_args2();
+select no_args2();
---- TYPES
string
---- RESULTS
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test b/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
index ab0c8bb..5ff4488 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
@@ -1,130 +1,99 @@
====
---- QUERY
-drop function if exists udf_test.hive_pi();
-drop function if exists udf_test.hive_round(double);
-drop function if exists udf_test.hive_floor(double);
-drop function if exists udf_test.hive_mod(int, int);
-drop function if exists udf_test.hive_bin(bigint);
-drop function if exists udf_test.hive_lower(string);
-
-drop function if exists udf_test.identity(boolean);
-drop function if exists udf_test.identity(tinyint);
-drop function if exists udf_test.identity(smallint);
-drop function if exists udf_test.identity(int);
-drop function if exists udf_test.identity(bigint);
-drop function if exists udf_test.identity(float);
-drop function if exists udf_test.identity(double);
-drop function if exists udf_test.identity(string);
-drop function if exists udf_test.identity(string, string);
-drop function if exists udf_test.identity(string, string, string);
-drop function if exists udf_test.identity(timestamp);
-
-drop function if exists udf_test.hive_add(int, int);
-drop function if exists udf_test.hive_add(float, float);
-drop function if exists udf_test.hive_add(double, double);
-drop function if exists udf_test.hive_add(smallint, smallint);
-drop function if exists udf_test.hive_add(boolean, boolean);
-
-drop function if exists udf_test.throws_exception();
-
-drop function if exists java_udfs_test.identity;
-
-drop function if exists udf_test.replace_string(string);
-
-create function udf_test.hive_pi() returns double
+create function hive_pi() returns double
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFPI';
-create function udf_test.hive_round(double) returns double
+create function hive_round(double) returns double
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFRound';
-create function udf_test.hive_floor(double) returns bigint
+create function hive_floor(double) returns bigint
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFFloor';
-create function udf_test.hive_mod(int, int) returns int
+create function hive_mod(int, int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFPosMod';
-create function udf_test.hive_bin(bigint) returns string
+create function hive_bin(bigint) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFBin';
-create function udf_test.hive_lower(string) returns string
+create function hive_lower(string) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFLower';
# Used to test persistent java functions
-create function java_udfs_test.identity
+create function identity_anytype
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(boolean) returns boolean
+create function identity(boolean) returns boolean
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(tinyint) returns tinyint
+create function identity(tinyint) returns tinyint
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(smallint) returns smallint
+create function identity(smallint) returns smallint
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(int) returns int
+create function identity(int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(bigint) returns bigint
+create function identity(bigint) returns bigint
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(float) returns float
+create function identity(float) returns float
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(double) returns double
+create function identity(double) returns double
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(string) returns string
+create function identity(string) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(string, string) returns string
+create function identity(string, string) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.identity(string, string, string) returns string
+create function identity(string, string, string) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.hive_add(int, int) returns int
+create function hive_add(int, int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.hive_add(smallint, smallint) returns smallint
+create function hive_add(smallint, smallint) returns smallint
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.hive_add(float, float) returns float
+create function hive_add(float, float) returns float
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.hive_add(double, double) returns double
+create function hive_add(double, double) returns double
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.hive_add(boolean, boolean) returns boolean
+create function hive_add(boolean, boolean) returns boolean
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdf';
-create function udf_test.throws_exception() returns boolean
+create function throws_exception() returns boolean
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdfException';
-create function udf_test.replace_string(string) returns string
+create function replace_string(string) returns string
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.ReplaceStringUdf';
====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/uda-mem-limit.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/uda-mem-limit.test b/testdata/workloads/functional-query/queries/QueryTest/uda-mem-limit.test
index 3a21274..b7c2f5f 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/uda-mem-limit.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/uda-mem-limit.test
@@ -1,8 +1,5 @@
====
---- QUERY
-create database if not exists native_function_test;
-use native_function_test;
-
drop function if exists agg_memtest(bigint);
create aggregate function agg_memtest(bigint) returns bigint
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/uda.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/uda.test b/testdata/workloads/functional-query/queries/QueryTest/uda.test
index 21877cf..05e24e7 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/uda.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/uda.test
@@ -41,3 +41,31 @@ true
---- TYPES
boolean
====
+---- QUERY
+# Test with even number of input rows.
+select toggle_null(id), count(*)
+from functional_parquet.alltypesagg
+---- RESULTS
+NULL,11000
+---- TYPES
+int,bigint
+====
+---- QUERY
+# Test with odd number of input rows.
+select toggle_null(id), count(*)
+from functional_parquet.alltypesagg
+where id <= 9998
+---- RESULTS
+1,10999
+---- TYPES
+int,bigint
+====
+---- QUERY
+# Test that input NULLs are passed to aggregate functions ok.
+select count_nulls(tinyint_col), count(*)
+from functional.alltypesagg
+---- RESULTS
+2000,11000
+---- TYPES
+bigint,bigint
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/udf-codegen-required.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/udf-codegen-required.test b/testdata/workloads/functional-query/queries/QueryTest/udf-codegen-required.test
new file mode 100644
index 0000000..07c93c3
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/udf-codegen-required.test
@@ -0,0 +1,10 @@
+====
+---- QUERY
+# Codegen is required for > 20 args.
+select twenty_one_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
+---- TYPES
+INT
+---- RESULTS
+231
+====
+
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/udf-errors.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/udf-errors.test b/testdata/workloads/functional-query/queries/QueryTest/udf-errors.test
index 948d584..73aee7e 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/udf-errors.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/udf-errors.test
@@ -1,23 +1,19 @@
====
---- QUERY
-create database if not exists udf_test_errors;
----- RESULTS
-====
----- QUERY
-create function if not exists udf_test_errors.hive_pi() returns double
+create function if not exists hive_pi() returns double
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFPI';
---- RESULTS
====
---- QUERY
-create function if not exists udf_test_errors.foo() returns double
+create function if not exists foo() returns double
location '$FILESYSTEM_PREFIX/test-warehouse/not-a-real-file.so'
symbol='FnDoesNotExist';
---- CATCH
Could not load binary: $FILESYSTEM_PREFIX/test-warehouse/not-a-real-file.so
====
---- QUERY
-create function if not exists udf_test_errors.foo() returns double
+create function if not exists foo() returns double
location '$FILESYSTEM_PREFIX/test-warehouse/not-a-real-file.so'
symbol='FnDoesNotExist';
---- CATCH
@@ -25,7 +21,7 @@ Could not load binary: $FILESYSTEM_PREFIX/test-warehouse/not-a-real-file.so
====
---- QUERY
# This test is run with codegen disabled. Interpretation only handles up to 20 arguments.
-create function if not exists udf_test_errors.twenty_args(int, int, int, int, int, int,
+create function if not exists twenty_args(int, int, int, int, int, int,
int, int, int, int, int, int, int, int, int, int, int, int, int, int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/libTestUdfs.so'
symbol='TwentyArgs';
@@ -33,7 +29,7 @@ symbol='TwentyArgs';
====
---- QUERY
# Verifies that interpretation can support up to 20 arguments
-select udf_test_errors.twenty_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
+select twenty_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20);
---- TYPES
INT
---- RESULTS
@@ -41,7 +37,7 @@ INT
====
---- QUERY
# This test is run with codegen disabled. Interpretation only handles up to 20 arguments.
-create function if not exists udf_test_errors.twenty_one_args(int, int, int, int, int, int,
+create function if not exists twenty_one_args(int, int, int, int, int, int,
int, int, int, int, int, int, int, int, int, int, int, int, int, int, int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/libTestUdfs.so'
symbol='TwentyOneArgs';
@@ -49,35 +45,36 @@ symbol='TwentyOneArgs';
====
---- QUERY
# Verifies that interpretation fails with more than 20 arguments.
-select udf_test_errors.twenty_one_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
+select twenty_one_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
---- CATCH
Cannot interpret native UDF 'twenty_one_args': number of arguments is more than 20. Codegen is needed. Please set DISABLE_CODEGEN to false.
====
---- QUERY
# This test is run with codegen disabled. IR UDF will fail.
-create function if not exists udf_test_errors.nine_args_ir(int, int, int, int, int, int,
+create function if not exists nine_args_ir(int, int, int, int, int, int,
int, int, int) returns int
location '$FILESYSTEM_PREFIX/test-warehouse/test-udfs.ll'
symbol='NineArgs';
---- RESULTS
====
---- QUERY
-select udf_test_errors.nine_args_ir(1,2,3,4,5,6,7,8,9);
+select nine_args_ir(1,2,3,4,5,6,7,8,9);
---- CATCH
Cannot interpret LLVM IR UDF 'nine_args_ir': Codegen is needed. Please set DISABLE_CODEGEN to false.
====
---- QUERY
-drop database udf_test_errors;
+use default;
+drop database $DATABASE;
---- CATCH
-Cannot drop non-empty database: udf_test_errors
+Cannot drop non-empty database:
====
---- QUERY
-drop function udf_test_errors.hive_pi();
-drop function udf_test_errors.twenty_args(int, int, int, int, int, int, int, int,
+use $DATABASE;
+drop function hive_pi();
+drop function twenty_args(int, int, int, int, int, int, int, int,
int, int, int, int, int, int, int, int, int, int, int, int);
-drop function udf_test_errors.twenty_one_args(int, int, int, int, int, int, int, int,
+drop function twenty_one_args(int, int, int, int, int, int, int, int,
int, int, int, int, int, int, int, int, int, int, int, int, int);
-drop function udf_test_errors.nine_args_ir(int, int, int, int, int, int, int, int, int);
-drop database udf_test_errors;
+drop function nine_args_ir(int, int, int, int, int, int, int, int, int);
---- RESULTS
====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/udf-mem-limit.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/udf-mem-limit.test b/testdata/workloads/functional-query/queries/QueryTest/udf-mem-limit.test
index f9b8d4b..3f23aeb 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/udf-mem-limit.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/udf-mem-limit.test
@@ -1,10 +1,5 @@
====
---- QUERY
-create database if not exists native_function_test;
-use native_function_test;
-
-drop function if exists memtest(bigint);
-
create function memtest(bigint) returns bigint
location '$FILESYSTEM_PREFIX/test-warehouse/libTestUdfs.so' symbol='MemTest'
prepare_fn='MemTestPrepare' close_fn='MemTestClose';
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/testdata/workloads/functional-query/queries/QueryTest/udf.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/udf.test b/testdata/workloads/functional-query/queries/QueryTest/udf.test
index 5cbbecb..ef777a1 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/udf.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/udf.test
@@ -536,10 +536,3 @@ INT
---- RESULTS
210
====
----- QUERY
-select twenty_one_args(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21);
----- TYPES
-INT
----- RESULTS
-231
-====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/tests/common/test_result_verifier.py
----------------------------------------------------------------------
diff --git a/tests/common/test_result_verifier.py b/tests/common/test_result_verifier.py
index 6bf991e..80daf09 100644
--- a/tests/common/test_result_verifier.py
+++ b/tests/common/test_result_verifier.py
@@ -482,3 +482,25 @@ def verify_runtime_profile(expected, actual):
assert len(unmatched_lines) == 0, ("Did not find matches for lines in runtime profile:"
"\nEXPECTED LINES:\n%s\n\nACTUAL PROFILE:\n%s" % ('\n'.join(unmatched_lines),
actual))
+
+def get_node_exec_options(profile_string, exec_node_id):
+ """ Return a list with all of the ExecOption strings for the given exec node id. """
+ results = []
+ matched_node = False
+ id_string = "(id={0})".format(exec_node_id)
+ for line in profile_string.splitlines():
+ if matched_node and line.strip().startswith("ExecOption:"):
+ results.append(line.strip())
+ matched_node = False
+ if id_string in line:
+ # Check for the ExecOption string on the next line.
+ matched_node = True
+ return results
+
+def assert_codegen_enabled(profile_string, exec_node_ids):
+ """ Check that codegen is enabled for the given exec node ids by parsing the text
+ runtime profile in 'profile_string'"""
+ for exec_node_id in exec_node_ids:
+ for exec_options in get_node_exec_options(profile_string, exec_node_id):
+ assert 'Codegen Enabled' in exec_options
+ assert not 'Codegen Disabled' in exec_options
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/tests/query_test/test_aggregation.py
----------------------------------------------------------------------
diff --git a/tests/query_test/test_aggregation.py b/tests/query_test/test_aggregation.py
index 82d50c8..c44c784 100644
--- a/tests/query_test/test_aggregation.py
+++ b/tests/query_test/test_aggregation.py
@@ -19,28 +19,64 @@
#
import pytest
+from tests.common.environ import USING_OLD_AGGS_JOINS
from tests.common.impala_test_suite import ImpalaTestSuite
+from tests.common.skip import SkipIfOldAggsJoins
from tests.common.test_dimensions import (
create_exec_option_dimension,
create_uncompressed_text_dimension)
+from tests.common.test_result_verifier import assert_codegen_enabled
from tests.common.test_vector import TestDimension
-from tests.common.skip import SkipIfOldAggsJoins
-
-agg_functions = ['sum', 'count', 'min', 'max', 'avg']
-data_types = ['int', 'bool', 'double', 'bigint', 'tinyint',
- 'smallint', 'float', 'timestamp']
+# Test dimensions for TestAggregation.
+AGG_FUNCTIONS = ['sum', 'count', 'min', 'max', 'avg', 'ndv']
+DATA_TYPES = ['int', 'bool', 'double', 'bigint', 'tinyint',
+ 'smallint', 'float', 'timestamp', 'string']
+# Lookup table for TestAggregation results.
result_lut = {
- # TODO: Add verification for other types
'sum-tinyint': 45000, 'avg-tinyint': 5, 'count-tinyint': 9000,
- 'min-tinyint': 1, 'max-tinyint': 9,
+ 'min-tinyint': 1, 'max-tinyint': 9, 'ndv-tinyint': 9,
'sum-smallint': 495000, 'avg-smallint': 50, 'count-smallint': 9900,
- 'min-smallint': 1, 'max-smallint': 99,
+ 'min-smallint': 1, 'max-smallint': 99, 'ndv-smallint': 99,
'sum-int': 4995000, 'avg-int': 500, 'count-int': 9990,
- 'min-int': 1, 'max-int': 999,
+ 'min-int': 1, 'max-int': 999, 'ndv-int': 999,
'sum-bigint': 49950000, 'avg-bigint': 5000, 'count-bigint': 9990,
- 'min-bigint': 10, 'max-bigint': 9990,
+ 'min-bigint': 10, 'max-bigint' : 9990, 'ndv-bigint': 999,
+ 'sum-bool': 5000, 'count-bool': 10000, 'min-bool': 'false',
+ 'max-bool': 'true', 'avg-bool': 0.5, 'ndv-bool': 2,
+ 'sum-double': 50449500.0, 'count-double': 9990, 'min-double': 10.1,
+ 'max-double': 10089.9, 'avg-double': 5050.0, 'ndv-double': 999,
+ 'sum-float': 5494500.0, 'count-float': 9990, 'min-float': 1.10,
+ 'max-float': 1098.9, 'avg-float': 550.0, 'ndv-float': 999,
+ 'count-timestamp': 10000, 'min-timestamp': '2010-01-01 00:00:00',
+ 'max-timestamp': '2010-01-10 18:02:05.100000000',
+ 'avg-timestamp': '2010-01-05 20:47:11.705080000', 'ndv-timestamp': 10000,
+ 'count-string': 10000, 'min-string': '0', 'max-string': '999', 'ndv-string': 999,
+ 'sum-distinct-tinyint': 45, 'count-distinct-tinyint': 9, 'min-distinct-tinyint': 1,
+ 'max-distinct-tinyint': 9, 'avg-distinct-tinyint': 5, 'ndv-distinct-tinyint': 9,
+ 'sum-distinct-smallint': 4950, 'count-distinct-smallint': 99,
+ 'min-distinct-smallint': 1, 'max-distinct-smallint': 99,
+ 'avg-distinct-smallint': 50, 'ndv-distinct-smallint': 99,
+ 'sum-distinct-int': 499500, 'count-distinct-int': 999, 'min-distinct-int': 1,
+ 'max-distinct-int': 999, 'avg-distinct-int': 500, 'ndv-distinct-int': 999,
+ 'sum-distinct-bigint': 4995000, 'count-distinct-bigint': 999, 'min-distinct-bigint': 10,
+ 'max-distinct-bigint': 9990, 'avg-distinct-bigint': 5000,
+ 'ndv-distinct-bigint': 999,
+ 'sum-distinct-bool': 1, 'count-distinct-bool': 2, 'min-distinct-bool': 'false',
+ 'max-distinct-bool': 'true', 'avg-distinct-bool': 0.5, 'ndv-distinct-bool': 2,
+ 'sum-distinct-double': 5044950.0, 'count-distinct-double': 999,
+ 'min-distinct-double': 10.1, 'max-distinct-double': 10089.9,
+ 'avg-distinct-double': 5050.0, 'ndv-distinct-double': 999,
+ 'sum-distinct-float': 549450.0, 'count-distinct-float': 999, 'min-distinct-float': 1.1,
+ 'max-distinct-float': 1098.9, 'avg-distinct-float': 550.0,
+ 'ndv-distinct-float': 999,
+ 'count-distinct-timestamp': 10000, 'min-distinct-timestamp': '2010-01-01 00:00:00',
+ 'max-distinct-timestamp': '2010-01-10 18:02:05.100000000',
+ 'avg-distinct-timestamp': '2010-01-05 20:47:11.705080000',
+ 'ndv-distinct-timestamp': 10000,
+ 'count-distinct-string': 1000, 'min-distinct-string': '0',
+ 'max-distinct-string': '999', 'ndv-distinct-string': 999,
}
class TestAggregation(ImpalaTestSuite):
@@ -53,8 +89,8 @@ class TestAggregation(ImpalaTestSuite):
super(TestAggregation, cls).add_test_dimensions()
# Add two more dimensions
- cls.TestMatrix.add_dimension(TestDimension('agg_func', *agg_functions))
- cls.TestMatrix.add_dimension(TestDimension('data_type', *data_types))
+ cls.TestMatrix.add_dimension(TestDimension('agg_func', *AGG_FUNCTIONS))
+ cls.TestMatrix.add_dimension(TestDimension('data_type', *DATA_TYPES))
cls.TestMatrix.add_constraint(lambda v: cls.is_valid_vector(v))
@classmethod
@@ -68,30 +104,63 @@ class TestAggregation(ImpalaTestSuite):
if vector.get_value('exec_option')['batch_size'] != 0: return False
# Avro doesn't have timestamp type
+ non_numeric = data_type in ['bool', 'string']
if file_format == 'avro' and data_type == 'timestamp':
return False
- elif agg_func not in ['min', 'max', 'count'] and data_type == 'bool':
+ elif non_numeric and agg_func not in ['min', 'max', 'count', 'ndv']:
return False
elif agg_func == 'sum' and data_type == 'timestamp':
return False
return True
def test_aggregation(self, vector):
+ exec_option = vector.get_value('exec_option')
+ disable_codegen = exec_option['disable_codegen']
+ # The old aggregation node does not support codegen for all aggregate functions.
+ check_codegen_enabled = not disable_codegen and not USING_OLD_AGGS_JOINS
data_type, agg_func = (vector.get_value('data_type'), vector.get_value('agg_func'))
+
query = 'select %s(%s_col) from alltypesagg where day is not null' % (agg_func,
data_type)
- result = self.execute_scalar(query, vector.get_value('exec_option'),
- table_format=vector.get_value('table_format'))
- if 'int' in data_type:
- assert result_lut['%s-%s' % (agg_func, data_type)] == int(result)
-
- # AVG
- if vector.get_value('data_type') == 'timestamp' and\
- vector.get_value('agg_func') == 'avg':
- return
+ result = self.execute_query(query, exec_option,
+ table_format=vector.get_value('table_format'))
+ assert len(result.data) == 1
+ self.verify_agg_result(agg_func, data_type, False, result.data[0]);
+
+ if check_codegen_enabled:
+ # Verify codegen was enabled for both stages of the aggregation.
+ assert_codegen_enabled(result.runtime_profile, [1, 3])
+
query = 'select %s(DISTINCT(%s_col)) from alltypesagg where day is not null' % (
agg_func, data_type)
- result = self.execute_scalar(query, vector.get_value('exec_option'))
+ result = self.execute_query(query, vector.get_value('exec_option'))
+ assert len(result.data) == 1
+ self.verify_agg_result(agg_func, data_type, True, result.data[0]);
+
+ if check_codegen_enabled:
+ # Verify codegen was enabled for all stages of the aggregation.
+ assert_codegen_enabled(result.runtime_profile, [1, 2, 4, 6])
+
+ def verify_agg_result(self, agg_func, data_type, distinct, actual_string):
+ key = '%s-%s%s' % (agg_func, 'distinct-' if distinct else '', data_type)
+
+ if agg_func == 'ndv':
+ # NDV is inherently approximate. Compare with some tolerance.
+ err = abs(result_lut[key] - int(actual_string))
+ rel_err = err / float(result_lut[key])
+ print key, result_lut[key], actual_string,abs(result_lut[key] - int(actual_string))
+ assert err <= 1 or rel_err < 0.05
+ elif data_type in ('float', 'double') and agg_func != 'count':
+ # Compare with a margin of error.
+ delta = 1e6 if data_type == 'double' else 1e3
+ assert abs(result_lut[key] - float(actual_string)) < delta
+ elif data_type == 'timestamp' and agg_func != 'count':
+ # Strip off everything past 10s of microseconds.
+ ignore_digits = 4
+ assert result_lut[key][:-ignore_digits] == actual_string[:-ignore_digits]
+ else:
+ assert str(result_lut[key]) == actual_string
+
class TestAggregationQueries(ImpalaTestSuite):
"""Run the aggregation test suite, with codegen enabled and disabled, to exercise our
@@ -140,6 +209,7 @@ class TestAggregationQueries(ImpalaTestSuite):
first phase is running on multiple nodes). Need to pull the result apart and
compare the actual items)"""
exec_option = vector.get_value('exec_option')
+ disable_codegen = exec_option['disable_codegen']
table_format = vector.get_value('table_format')
# Test group_concat distinct with other aggregate function and groupings.
# expected result is the row: 2010,'1, 2, 3, 4','1-2-3-4','2|3|1|4',40,4
@@ -156,6 +226,10 @@ class TestAggregationQueries(ImpalaTestSuite):
assert(set(row[i].split(delimiter[i-1])) == set(['1', '2', '3', '4']))
assert(row[4] == '40')
assert(row[5] == '4')
+ check_codegen_enabled = not disable_codegen and not USING_OLD_AGGS_JOINS
+ if check_codegen_enabled:
+ # Verify codegen was enabled for all three stages of the aggregation.
+ assert_codegen_enabled(result.runtime_profile, [1, 2, 4])
# Test group_concat distinct with arrow delimiter, with multiple rows
query = """select day, group_concat(distinct string_col, "->")
@@ -185,6 +259,10 @@ class TestAggregationQueries(ImpalaTestSuite):
where int_col < 10"""
result = self.execute_query(query, exec_option, table_format=table_format)
assert(set((result.data)[0].split(" ")) == set(['1','2','3','4','5','6','7','8','9']))
+ if check_codegen_enabled:
+ # Verify codegen was enabled for all four stages of the aggregation.
+ assert_codegen_enabled(result.runtime_profile, [1, 2, 4, 6])
+
class TestTPCHAggregationQueries(ImpalaTestSuite):
# Uses the TPC-H dataset in order to have larger aggregations.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/tests/query_test/test_udfs.py
----------------------------------------------------------------------
diff --git a/tests/query_test/test_udfs.py b/tests/query_test/test_udfs.py
index 0497cbd..5e9fdd9 100644
--- a/tests/query_test/test_udfs.py
+++ b/tests/query_test/test_udfs.py
@@ -24,7 +24,7 @@ from tests.common.impala_cluster import ImpalaCluster
from tests.common.impala_test_suite import ImpalaTestSuite
from tests.common.skip import SkipIfLocal
from tests.common.test_dimensions import (
- create_single_exec_option_dimension,
+ create_exec_option_dimension,
create_uncompressed_text_dimension)
from tests.util.calculation_util import get_random_id
from tests.util.filesystem_utils import get_fs_path, IS_S3
@@ -37,48 +37,46 @@ class TestUdfs(ImpalaTestSuite):
@classmethod
def add_test_dimensions(cls):
super(TestUdfs, cls).add_test_dimensions()
- # Without limiting the test suite to a single exec option, the tests will fail
- # because the same test case may be executed in parallel with different exec option
- # values leading to conflicting DDL ops.
- cls.TestMatrix.add_dimension(create_single_exec_option_dimension())
+ cls.TestMatrix.add_dimension(
+ create_exec_option_dimension(disable_codegen_options=[False, True]))
# There is no reason to run these tests using all dimensions.
cls.TestMatrix.add_dimension(create_uncompressed_text_dimension(cls.get_workload()))
- def test_native_functions(self, vector):
- database = 'native_function_test'
-
+ def test_native_functions(self, vector, unique_database):
self.__load_functions(
- self.create_udfs_template, vector, database,
+ self.create_udfs_template, vector, unique_database,
get_fs_path('/test-warehouse/libTestUdfs.so'))
self.__load_functions(
- self.create_sample_udas_template, vector, database,
+ self.create_sample_udas_template, vector, unique_database,
get_fs_path('/test-warehouse/libudasample.so'))
self.__load_functions(
- self.create_test_udas_template, vector, database,
+ self.create_test_udas_template, vector, unique_database,
get_fs_path('/test-warehouse/libTestUdas.so'))
- self.run_test_case('QueryTest/udf', vector, use_db=database)
- if not IS_S3: # S3 doesn't support INSERT
- self.run_test_case('QueryTest/udf-init-close', vector, use_db=database)
- self.run_test_case('QueryTest/uda', vector, use_db=database)
+ self.run_test_case('QueryTest/udf', vector, use_db=unique_database)
+ if not vector.get_value('exec_option')['disable_codegen']:
+ self.run_test_case('QueryTest/udf-codegen-required', vector, use_db=unique_database)
+ self.run_test_case('QueryTest/udf-init-close', vector, use_db=unique_database)
+ self.run_test_case('QueryTest/uda', vector, use_db=unique_database)
- def test_ir_functions(self, vector):
- database = 'ir_function_test'
+ def test_ir_functions(self, vector, unique_database):
+ if vector.get_value('exec_option')['disable_codegen']:
+ # IR functions require codegen to be enabled.
+ return
self.__load_functions(
- self.create_udfs_template, vector, database,
+ self.create_udfs_template, vector, unique_database,
get_fs_path('/test-warehouse/test-udfs.ll'))
- self.run_test_case('QueryTest/udf', vector, use_db=database)
- if not IS_S3: # S3 doesn't support INSERT
- self.run_test_case('QueryTest/udf-init-close', vector, use_db=database)
+ self.run_test_case('QueryTest/udf', vector, use_db=unique_database)
+ self.run_test_case('QueryTest/udf-init-close', vector, use_db=unique_database)
- def test_udf_errors(self, vector):
+ def test_udf_errors(self, vector, unique_database):
# Disable codegen to force interpretation path to be taken.
# Aim to exercise two failure cases:
# 1. too many arguments
# 2. IR UDF
vector.get_value('exec_option')['disable_codegen'] = 1
- self.run_test_case('QueryTest/udf-errors', vector)
+ self.run_test_case('QueryTest/udf-errors', vector, use_db=unique_database)
def test_udf_invalid_symbol(self, vector):
""" IMPALA-1642: Impala crashes if the symbol for a Hive UDF doesn't exist
@@ -98,17 +96,9 @@ class TestUdfs(ImpalaTestSuite):
finally:
self.client.execute(drop_fn_stmt)
- def test_java_udfs(self, vector):
- self.client.execute("create database if not exists java_udfs_test "
- "location '%s'" % get_fs_path('/test-warehouse/java_udf_test.db'))
- self.client.execute("create database if not exists udf_test "
- "location '%s'" % get_fs_path('/test-warehouse/udf_test.db'))
- try:
- self.run_test_case('QueryTest/load-java-udfs', vector)
- self.run_test_case('QueryTest/java-udf', vector)
- finally:
- self.client.execute("drop database if exists java_udfs_test cascade")
- self.client.execute("drop database if exists udf_test cascade")
+ def test_java_udfs(self, vector, unique_database):
+ self.run_test_case('QueryTest/load-java-udfs', vector, use_db=unique_database)
+ self.run_test_case('QueryTest/java-udf', vector, use_db=unique_database)
@SkipIfLocal.multiple_impalad
def test_hive_udfs_missing_jar(self, vector, unique_database):
@@ -150,13 +140,8 @@ class TestUdfs(ImpalaTestSuite):
except ImpalaBeeswaxException, e:
assert "Failed to get file info" in str(e)
- def test_libs_with_same_filenames(self, vector):
- self.client.execute("create database if not exists same_lib_filename_udf_test "
- "location '%s'" % get_fs_path('/test-warehouse/same_lib_filename_udf_test.db'))
- try:
- self.run_test_case('QueryTest/libs_with_same_filenames', vector)
- finally:
- self.client.execute("drop database if exists same_lib_filename_udf_test cascade")
+ def test_libs_with_same_filenames(self, vector, unique_database):
+ self.run_test_case('QueryTest/libs_with_same_filenames', vector, use_db=unique_database)
def test_udf_update_via_drop(self, vector, unique_database):
"""Test updating the UDF binary without restarting Impala. Dropping
@@ -263,19 +248,19 @@ class TestUdfs(ImpalaTestSuite):
# Run serially because this will blow the process limit, potentially causing other
# queries to fail
@pytest.mark.execute_serially
- def test_mem_limits(self, vector):
+ def test_mem_limits(self, vector, unique_database):
# Set the mem limit high enough that a simple scan can run
mem_limit = 1024 * 1024
vector.get_value('exec_option')['mem_limit'] = mem_limit
try:
- self.run_test_case('QueryTest/udf-mem-limit', vector)
+ self.run_test_case('QueryTest/udf-mem-limit', vector, use_db=unique_database)
assert False, "Query was expected to fail"
except ImpalaBeeswaxException, e:
self.__check_exception(e)
try:
- self.run_test_case('QueryTest/uda-mem-limit', vector)
+ self.run_test_case('QueryTest/uda-mem-limit', vector, use_db=unique_database)
assert False, "Query was expected to fail"
except ImpalaBeeswaxException, e:
self.__check_exception(e)
@@ -330,6 +315,8 @@ returns decimal(9,2) location '{location}' update_fn='SumSmallDecimalUpdate';
create_test_udas_template = """
drop function if exists {database}.trunc_sum(double);
drop function if exists {database}.arg_is_const(int, int);
+drop function if exists {database}.toggle_null(int);
+drop function if exists {database}.count_nulls(bigint);
create database if not exists {database};
@@ -341,6 +328,14 @@ serialize_fn='TruncSumSerialize' finalize_fn='TruncSumFinalize';
create aggregate function {database}.arg_is_const(int, int)
returns boolean location '{location}'
init_fn='ArgIsConstInit' update_fn='ArgIsConstUpdate' merge_fn='ArgIsConstMerge';
+
+create aggregate function {database}.toggle_null(int)
+returns int location '{location}'
+update_fn='ToggleNullUpdate' merge_fn='ToggleNullMerge';
+
+create aggregate function {database}.count_nulls(bigint)
+returns bigint location '{location}'
+update_fn='CountNullsUpdate' merge_fn='CountNullsMerge';
"""
# Create test UDF functions in {database} from library {location}
[06/50] [abbrv] incubator-impala git commit: IMPALA-4437: hit DCHECK
in buffered-block-mgr-test
Posted by ta...@apache.org.
IMPALA-4437: hit DCHECK in buffered-block-mgr-test
The issue was introduced by "IMPALA-3202: DiskIoMgr improvements
for new buffer pool". The bug is pretty straightforward - I forgot
to update some error/cancellation paths to handle client-provided
buffers.
Testing:
Was able to reproduce locally before the fix, have run it in a loop for
a while with the fix and not seen any crashes.
Change-Id: Ib7e8ffdbec341f6ffbc310fb29df63ab45fed545
Reviewed-on: http://gerrit.cloudera.org:8080/4973
Reviewed-by: Henry Robinson <he...@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/58d8861c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/58d8861c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/58d8861c
Branch: refs/heads/hadoop-next
Commit: 58d8861c58fd911411fdb61a4c2c850dc86d9803
Parents: 822b2ca
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Sun Nov 6 19:15:39 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 7 11:50:43 2016 +0000
----------------------------------------------------------------------
be/src/runtime/disk-io-mgr.cc | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/58d8861c/be/src/runtime/disk-io-mgr.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr.cc b/be/src/runtime/disk-io-mgr.cc
index 7c5620a..265b49a 100644
--- a/be/src/runtime/disk-io-mgr.cc
+++ b/be/src/runtime/disk-io-mgr.cc
@@ -980,7 +980,7 @@ void DiskIoMgr::HandleReadFinished(DiskQueue* disk_queue, DiskIoRequestContext*
if (reader->state_ == DiskIoRequestContext::Cancelled) {
state.DecrementRequestThreadAndCheckDone(reader);
DCHECK(reader->Validate()) << endl << reader->DebugString();
- FreeBufferMemory(buffer);
+ if (!buffer->is_client_buffer()) FreeBufferMemory(buffer);
buffer->scan_range_->Cancel(reader->status_);
// Enqueue the buffer to use the scan range's buffer cleanup path.
buffer->scan_range_->EnqueueBuffer(buffer);
@@ -996,7 +996,7 @@ void DiskIoMgr::HandleReadFinished(DiskQueue* disk_queue, DiskIoRequestContext*
// 3. Middle of scan range
if (!buffer->status_.ok()) {
// Error case
- FreeBufferMemory(buffer);
+ if (!buffer->is_client_buffer()) FreeBufferMemory(buffer);
buffer->eosr_ = true;
--state.num_remaining_ranges();
buffer->scan_range_->Cancel(buffer->status_);
[40/50] [abbrv] incubator-impala git commit: IMPALA-4465: Don't hold
process wide lock while serializing Runtime Profile in GetRuntimeProfileStr()
Posted by ta...@apache.org.
IMPALA-4465: Don't hold process wide lock while serializing Runtime Profile in GetRuntimeProfileStr()
This patch changes the code so that the query_exec_state_map_lock_
is not held while serializing the RuntimeProfile, since that is a
pretty expensive operation and happens at least once per query. This
change makes a lot of client calls have less lock contention including
Webserver calls and query registration/unregistration.
Change-Id: I3ad8a1d6644259f177dfb3b29b3ba1ad6a76210a
Reviewed-on: http://gerrit.cloudera.org:8080/5035
Reviewed-by: Sailesh Mukil <sa...@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/f4a5d863
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/f4a5d863
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/f4a5d863
Branch: refs/heads/hadoop-next
Commit: f4a5d863c3123503d8b8c89bf1415f4bbdd6a810
Parents: 628685a
Author: Sailesh <sa...@cloudera.com>
Authored: Thu Nov 10 11:33:31 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 03:33:14 2016 +0000
----------------------------------------------------------------------
be/src/service/impala-server.cc | 10 +++++-----
1 file changed, 5 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/f4a5d863/be/src/service/impala-server.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.cc b/be/src/service/impala-server.cc
index 730dfbf..c210e28 100644
--- a/be/src/service/impala-server.cc
+++ b/be/src/service/impala-server.cc
@@ -565,13 +565,13 @@ Status ImpalaServer::GetRuntimeProfileStr(const TUniqueId& query_id,
DCHECK(output != NULL);
// Search for the query id in the active query map
{
- lock_guard<mutex> l(query_exec_state_map_lock_);
- QueryExecStateMap::const_iterator exec_state = query_exec_state_map_.find(query_id);
- if (exec_state != query_exec_state_map_.end()) {
+ shared_ptr<QueryExecState> exec_state = GetQueryExecState(query_id, false);
+ if (exec_state.get() != nullptr) {
+ lock_guard<mutex> l(*exec_state->lock());
if (base64_encoded) {
- exec_state->second->profile().SerializeToArchiveString(output);
+ exec_state->profile().SerializeToArchiveString(output);
} else {
- exec_state->second->profile().PrettyPrint(output);
+ exec_state->profile().PrettyPrint(output);
}
return Status::OK();
}
[42/50] [abbrv] incubator-impala git commit: IMPALA-4372: 'Describe
formatted' returns types in upper case
Posted by ta...@apache.org.
IMPALA-4372: 'Describe formatted' returns types in upper case
A recent change caused 'describe formatted' to display the types
in all upper case, but we want 'describe formatted' to match Hive's
'describe' output, which displays the types in lower case.
This patch also fixes several problems with test_describe_formatted,
which was encountering an error but reporting success.
Change-Id: I274b97d4d1247244247fb38a5ca7f4c10bba8d22
Reviewed-on: http://gerrit.cloudera.org:8080/4861
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/e6e2baea
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/e6e2baea
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/e6e2baea
Branch: refs/heads/hadoop-next
Commit: e6e2baea33eca0fbad9958c7c2f6087ee1019c46
Parents: 0ea4a66
Author: Thomas Tauber-Marshall <tm...@cloudera.com>
Authored: Wed Oct 26 19:41:19 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 05:38:12 2016 +0000
----------------------------------------------------------------------
.../java/org/apache/impala/catalog/Column.java | 2 +-
.../queries/QueryTest/avro-schema-changes.test | 6 +--
tests/common/impala_test_suite.py | 9 ++--
.../metadata/test_metadata_query_statements.py | 47 +++++++++++++++-----
tests/performance/query_exec_functions.py | 10 ++---
tests/performance/query_executor.py | 1 +
6 files changed, 49 insertions(+), 26 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/fe/src/main/java/org/apache/impala/catalog/Column.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/Column.java b/fe/src/main/java/org/apache/impala/catalog/Column.java
index ab064e7..91928aa 100644
--- a/fe/src/main/java/org/apache/impala/catalog/Column.java
+++ b/fe/src/main/java/org/apache/impala/catalog/Column.java
@@ -124,7 +124,7 @@ public class Column {
return Lists.transform(columns, new Function<Column, FieldSchema>() {
public FieldSchema apply(Column column) {
Preconditions.checkNotNull(column.getType());
- return new FieldSchema(column.getName(), column.getType().toSql(),
+ return new FieldSchema(column.getName(), column.getType().toSql().toLowerCase(),
column.getComment());
}
});
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/testdata/workloads/functional-query/queries/QueryTest/avro-schema-changes.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/avro-schema-changes.test b/testdata/workloads/functional-query/queries/QueryTest/avro-schema-changes.test
index 1e3eac9..8233a02 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/avro-schema-changes.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/avro-schema-changes.test
@@ -101,8 +101,8 @@ DESCRIBE FORMATTED avro_alter_schema_add_new_column;
---- TYPES
string,string,string
---- RESULTS: VERIFY_IS_SUBSET
-'old_col','STRING','from deserializer'
-'new_col','STRING','from deserializer'
+'old_col','string','from deserializer'
+'new_col','string','from deserializer'
====
---- QUERY
# IMPALA-3776: Create an Avro table, remove a column from the Avro schema and make sure
@@ -134,5 +134,5 @@ DESCRIBE FORMATTED avro_alter_schema_remove_column;
---- TYPES
string,string,string
---- RESULTS: VERIFY_IS_SUBSET
-'col1','STRING','from deserializer'
+'col1','string','from deserializer'
====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/tests/common/impala_test_suite.py
----------------------------------------------------------------------
diff --git a/tests/common/impala_test_suite.py b/tests/common/impala_test_suite.py
index afa8e2c..e287360 100644
--- a/tests/common/impala_test_suite.py
+++ b/tests/common/impala_test_suite.py
@@ -467,24 +467,23 @@ class ImpalaTestSuite(BaseTestSuite):
assert len(result.data) <= 1, 'Multiple values returned from scalar'
return result.data[0] if len(result.data) == 1 else None
- def exec_and_compare_hive_and_impala_hs2(self, stmt):
+ def exec_and_compare_hive_and_impala_hs2(self, stmt, compare = lambda x, y: x == y):
"""Compare Hive and Impala results when executing the same statment over HS2"""
# execute_using_jdbc expects a Query object. Convert the query string into a Query
# object
query = Query()
query.query_str = stmt
# Run the statement targeting Hive
- exec_opts = JdbcQueryExecConfig(impalad=HIVE_HS2_HOST_PORT)
+ exec_opts = JdbcQueryExecConfig(impalad=HIVE_HS2_HOST_PORT, transport='SASL')
hive_results = execute_using_jdbc(query, exec_opts).data
# Run the statement targeting Impala
- exec_opts = JdbcQueryExecConfig(impalad=IMPALAD_HS2_HOST_PORT)
+ exec_opts = JdbcQueryExecConfig(impalad=IMPALAD_HS2_HOST_PORT, transport='NOSASL')
impala_results = execute_using_jdbc(query, exec_opts).data
# Compare the results
assert (impala_results is not None) and (hive_results is not None)
- for impala, hive in zip(impala_results, hive_results):
- assert impala == hive
+ assert compare(impala_results, hive_results)
def load_query_test_file(self, workload, file_name, valid_section_names=None,
encoding=None):
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/tests/metadata/test_metadata_query_statements.py
----------------------------------------------------------------------
diff --git a/tests/metadata/test_metadata_query_statements.py b/tests/metadata/test_metadata_query_statements.py
index 0a51acb..8e25a2a 100644
--- a/tests/metadata/test_metadata_query_statements.py
+++ b/tests/metadata/test_metadata_query_statements.py
@@ -18,6 +18,7 @@
# Impala tests for queries that query metadata and set session settings
import pytest
+import re
from tests.beeswax.impala_beeswax import ImpalaBeeswaxException
from tests.common.impala_test_suite import ImpalaTestSuite
@@ -75,13 +76,36 @@ class TestMetadataQueryStatements(ImpalaTestSuite):
@SkipIfS3.hive
@SkipIfLocal.hive
def test_describe_formatted(self, vector, unique_database):
+ # For describe formmated, we try to match Hive's output as closely as possible.
+ # However, we're inconsistent with our handling of NULLs vs theirs - Impala sometimes
+ # specifies 'NULL' where Hive uses an empty string, and Hive somtimes specifies 'null'
+ # with padding where Impala uses a sequence of blank spaces - and for now
+ # we want to leave it that way to not affect users who rely on this output.
+ def compare_describe_formatted(impala_results, hive_results):
+ for impala, hive in zip(re.split(',|\n', impala_results),
+ re.split(',|\n', hive_results)):
+
+ if impala != hive:
+ # If they don't match, check if it's because of the inconsistent null handling.
+ impala = impala.replace(' ', '').lower()
+ hive = hive.replace(' ', '').lower()
+ if not ((impala == "'null'" and hive == "''") or
+ (impala == "''" and hive == "'null'")):
+ return False
+ return True
+
# Describe a partitioned table.
- self.exec_and_compare_hive_and_impala_hs2("describe formatted functional.alltypes")
+ self.exec_and_compare_hive_and_impala_hs2("describe formatted functional.alltypes",
+ compare=compare_describe_formatted)
self.exec_and_compare_hive_and_impala_hs2(
- "describe formatted functional_text_lzo.alltypes")
+ "describe formatted functional_text_lzo.alltypes",
+ compare=compare_describe_formatted)
+
# Describe an unpartitioned table.
- self.exec_and_compare_hive_and_impala_hs2("describe formatted tpch.lineitem")
- self.exec_and_compare_hive_and_impala_hs2("describe formatted functional.jointbl")
+ self.exec_and_compare_hive_and_impala_hs2("describe formatted tpch.lineitem",
+ compare=compare_describe_formatted)
+ self.exec_and_compare_hive_and_impala_hs2("describe formatted functional.jointbl",
+ compare=compare_describe_formatted)
# Create and describe an unpartitioned and partitioned Avro table created
# by Impala without any column definitions.
@@ -91,20 +115,19 @@ class TestMetadataQueryStatements(ImpalaTestSuite):
self.client.execute((
"create table %s.%s with serdeproperties ('avro.schema.url'='%s') stored as avro"
% (unique_database, "avro_alltypes_nopart", self.AVRO_SCHEMA_LOC)))
- self.exec_and_compare_hive_and_impala_hs2("describe formatted avro_alltypes_nopart")
+ self.exec_and_compare_hive_and_impala_hs2("describe formatted avro_alltypes_nopart",
+ compare=compare_describe_formatted)
self.client.execute((
"create table %s.%s partitioned by (year int, month int) "
"with serdeproperties ('avro.schema.url'='%s') stored as avro"
% (unique_database, "avro_alltypes_part", self.AVRO_SCHEMA_LOC)))
- self.exec_and_compare_hive_and_impala_hs2("describe formatted avro_alltypes_part")
+ self.exec_and_compare_hive_and_impala_hs2("describe formatted avro_alltypes_part",
+ compare=compare_describe_formatted)
- try:
- # Describe a view
- self.exec_and_compare_hive_and_impala_hs2(\
- "describe formatted functional.alltypes_view_sub")
- except AssertionError:
- pytest.xfail("Investigate minor difference in displaying null vs empty values")
+ self.exec_and_compare_hive_and_impala_hs2(\
+ "describe formatted functional.alltypes_view_sub",
+ compare=compare_describe_formatted)
@pytest.mark.execute_serially # due to data src setup/teardown
def test_show_data_sources(self, vector):
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/tests/performance/query_exec_functions.py
----------------------------------------------------------------------
diff --git a/tests/performance/query_exec_functions.py b/tests/performance/query_exec_functions.py
index 3abcae2..f7d00ec 100644
--- a/tests/performance/query_exec_functions.py
+++ b/tests/performance/query_exec_functions.py
@@ -245,7 +245,7 @@ def execute_using_jdbc(query, query_config):
cmd = query_config.jdbc_client_cmd + " -q \"%s\"" % query_string
return run_query_capture_results(cmd, query, exit_on_error=False)
-def parse_jdbc_query_results(stdout, stderr):
+def parse_jdbc_query_results(stdout, stderr, query):
"""
Parse query execution results for the Impala JDBC client
@@ -260,10 +260,10 @@ def parse_jdbc_query_results(stdout, stderr):
time_taken = float(('%s.%s') % (match.group(1), match.group(2)))
break
result_data = re.findall(r'\[START\]----\n(.*?)\n----\[END\]', stdout, re.DOTALL)[0]
- return create_exec_result(time_taken, result_data)
+ return create_exec_result(time_taken, result_data, query)
-def create_exec_result(time_taken, result_data):
- exec_result = HiveQueryResult()
+def create_exec_result(time_taken, result_data, query):
+ exec_result = HiveQueryResult(query)
if result_data:
LOG.debug('Data:\n%s\n' % result_data)
exec_result.data = result_data
@@ -296,7 +296,7 @@ def run_query_capture_results(cmd, query, exit_on_error):
exec_result.query_error = msg
return exec_result
# The command completed
- exec_result = parse_jdbc_query_results(stdout, stderr)
+ exec_result = parse_jdbc_query_results(stdout, stderr, query)
exec_result.query = query
exec_result.start_time = start_time
return exec_result
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e6e2baea/tests/performance/query_executor.py
----------------------------------------------------------------------
diff --git a/tests/performance/query_executor.py b/tests/performance/query_executor.py
index 56065b8..5d9fc61 100644
--- a/tests/performance/query_executor.py
+++ b/tests/performance/query_executor.py
@@ -91,6 +91,7 @@ class JdbcQueryExecConfig(ImpalaQueryExecConfig):
Constructed on the fly, since the impalad it points to can change.
"""
+ assert self.transport is not None
return JdbcQueryExecConfig.JDBC_CLIENT_PATH + ' -i "%s" -t %s' % (self._impalad,
self.transport)
[35/50] [abbrv] incubator-impala git commit: IMPALA-4452: Always call
AggFnEvaluator::Open() before AggFnEvaluator::Init()
Posted by ta...@apache.org.
IMPALA-4452: Always call AggFnEvaluator::Open() before AggFnEvaluator::Init()
As part of the fix for IMPALA-2379, the expression contexts of
aggregation function evaluators are expected to be opened before
their initFn() are called so \ constant arguments can be accessed
in initFn(). However, the legacy aggregation node wasn't updated
to follow this order for singleton result tuple (i.e. no group-by).
This patch fixes the problem by deferring the creation of the
singleton tuple to a point in AggregationNode::Open() after the
expression contexts of all aggregate function evaluators have
been opened. PartitionedAggregationNode() was already updated
to follow this order.
This patch also fixes a minor bug in which uninitialized entries
of agg_fn_ctxs_[] may be accessed in AggregationNode::Close()
if AggregationNode::Prepare() fails.
Change-Id: I2f261dee47821c517d8dbe1babf4112462d85807
Reviewed-on: http://gerrit.cloudera.org:8080/5049
Reviewed-by: Michael Ho <kw...@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/cac02d6b
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/cac02d6b
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/cac02d6b
Branch: refs/heads/hadoop-next
Commit: cac02d6b767601ce308050f57520b65285566183
Parents: 10a4c5a
Author: Michael Ho <kw...@cloudera.com>
Authored: Thu Nov 10 00:15:06 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 14 22:38:09 2016 +0000
----------------------------------------------------------------------
be/src/exec/aggregation-node.cc | 35 +++++++++++++++++++----------------
1 file changed, 19 insertions(+), 16 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cac02d6b/be/src/exec/aggregation-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/aggregation-node.cc b/be/src/exec/aggregation-node.cc
index 0607aa3..a5c7490 100644
--- a/be/src/exec/aggregation-node.cc
+++ b/be/src/exec/aggregation-node.cc
@@ -141,30 +141,23 @@ Status AggregationNode::Prepare(RuntimeState* state) {
Expr::Prepare(build_expr_ctxs_, state, build_row_desc, expr_mem_tracker()));
AddExprCtxsToFree(build_expr_ctxs_);
- agg_fn_ctxs_.resize(aggregate_evaluators_.size());
int j = probe_expr_ctxs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
SlotDescriptor* intermediate_slot_desc = intermediate_tuple_desc_->slots()[j];
SlotDescriptor* output_slot_desc = output_tuple_desc_->slots()[j];
+ FunctionContext* agg_fn_ctx;
RETURN_IF_ERROR(aggregate_evaluators_[i]->Prepare(state, child(0)->row_desc(),
- intermediate_slot_desc, output_slot_desc, agg_fn_pool_.get(), &agg_fn_ctxs_[i]));
- state->obj_pool()->Add(agg_fn_ctxs_[i]);
+ intermediate_slot_desc, output_slot_desc, agg_fn_pool_.get(), &agg_fn_ctx));
+ agg_fn_ctxs_.push_back(agg_fn_ctx);
+ state->obj_pool()->Add(agg_fn_ctx);
}
+ DCHECK_EQ(agg_fn_ctxs_.size(), aggregate_evaluators_.size());
// TODO: how many buckets?
hash_tbl_.reset(new OldHashTable(state, build_expr_ctxs_, probe_expr_ctxs_,
vector<ExprContext*>(), 1, true, vector<bool>(build_expr_ctxs_.size(), true), id(),
mem_tracker(), vector<RuntimeFilter*>(), true));
- if (probe_expr_ctxs_.empty()) {
- // create single intermediate tuple now; we need to output something
- // even if our input is empty
- singleton_intermediate_tuple_ = ConstructIntermediateTuple();
- // Check for failures during AggFnEvaluator::Init().
- RETURN_IF_ERROR(state->GetQueryStatus());
- hash_tbl_->Insert(singleton_intermediate_tuple_);
- output_iterator_ = hash_tbl_->Begin();
- }
if (!state->codegen_enabled()) {
runtime_profile()->AddCodegenMsg(false, "disabled by query option DISABLE_CODEGEN");
}
@@ -202,6 +195,15 @@ Status AggregationNode::Open(RuntimeState* state) {
RETURN_IF_ERROR(aggregate_evaluators_[i]->Open(state, agg_fn_ctxs_[i]));
}
+ if (probe_expr_ctxs_.empty()) {
+ // Create single intermediate tuple. This must happen after
+ // opening the aggregate evaluators.
+ singleton_intermediate_tuple_ = ConstructIntermediateTuple();
+ // Check for failures during AggFnEvaluator::Init().
+ RETURN_IF_ERROR(state->GetQueryStatus());
+ hash_tbl_->Insert(singleton_intermediate_tuple_);
+ }
+
RETURN_IF_ERROR(children_[0]->Open(state));
RowBatch batch(children_[0]->row_desc(), state->batch_size(), mem_tracker());
@@ -319,10 +321,11 @@ void AggregationNode::Close(RuntimeState* state) {
if (hash_tbl_.get() != NULL) hash_tbl_->Close();
agg_expr_ctxs_.clear();
- DCHECK(agg_fn_ctxs_.empty() || aggregate_evaluators_.size() == agg_fn_ctxs_.size());
- for (int i = 0; i < aggregate_evaluators_.size(); ++i) {
- aggregate_evaluators_[i]->Close(state);
- if (!agg_fn_ctxs_.empty()) agg_fn_ctxs_[i]->impl()->Close();
+ for (AggFnEvaluator* aggregate_evaluator : aggregate_evaluators_) {
+ aggregate_evaluator->Close(state);
+ }
+ for (FunctionContext* agg_fn_ctx : agg_fn_ctxs_) {
+ agg_fn_ctx->impl()->Close();
}
if (agg_fn_pool_.get() != NULL) agg_fn_pool_->FreeAll();
[45/50] [abbrv] incubator-impala git commit: Increase wait times for
startup of Hive and its Metastore
Posted by ta...@apache.org.
Increase wait times for startup of Hive and its Metastore
On Ubuntu 14.04 on AWS EC2 m4.4x, instances, these components
frequently take more than 30 seconds to start. I have seen the HMS
take more than 90 seconds; this patch sets a more conservative timeout
default.
Change-Id: I43eb8646cca495578c8f9730faa04812957d2917
Reviewed-on: http://gerrit.cloudera.org:8080/5068
Reviewed-by: Jim Apple <jb...@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/4b774880
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/4b774880
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/4b774880
Branch: refs/heads/hadoop-next
Commit: 4b774880c9bd46fccf8855f383ce579e585c7115
Parents: b3cbc96
Author: Jim Apple <jb...@cloudera.com>
Authored: Mon Nov 14 09:38:32 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 20:35:01 2016 +0000
----------------------------------------------------------------------
testdata/bin/wait-for-hiveserver2.py | 2 +-
testdata/bin/wait-for-metastore.py | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/4b774880/testdata/bin/wait-for-hiveserver2.py
----------------------------------------------------------------------
diff --git a/testdata/bin/wait-for-hiveserver2.py b/testdata/bin/wait-for-hiveserver2.py
index 233b541..bf57ea8 100755
--- a/testdata/bin/wait-for-hiveserver2.py
+++ b/testdata/bin/wait-for-hiveserver2.py
@@ -60,7 +60,7 @@ hs2_client = TCLIService.Client(protocol)
# Try to connect to the HiveServer2 service and create a session
now = time.time()
-TIMEOUT_SECONDS = 30.0
+TIMEOUT_SECONDS = 300.0
while time.time() - now < TIMEOUT_SECONDS:
try:
hs2_transport.open()
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/4b774880/testdata/bin/wait-for-metastore.py
----------------------------------------------------------------------
diff --git a/testdata/bin/wait-for-metastore.py b/testdata/bin/wait-for-metastore.py
index a528142..2dc6550 100755
--- a/testdata/bin/wait-for-metastore.py
+++ b/testdata/bin/wait-for-metastore.py
@@ -50,7 +50,7 @@ hive_client = ThriftHiveMetastore.Client(protocol)
# Try to connect to the Hive metastore
now = time.time()
-TIMEOUT_SECONDS = 30.0
+TIMEOUT_SECONDS = 300.0
while time.time() - now < TIMEOUT_SECONDS:
try:
hive_transport.open()
[12/50] [abbrv] incubator-impala git commit: IMPALA-4441:
Divide-by-zero in RuntimeProfile::SummaryStatsCounter::SetStats
Posted by ta...@apache.org.
IMPALA-4441: Divide-by-zero in RuntimeProfile::SummaryStatsCounter::SetStats
This patch anticipates the case where total_num_values_ can be 0 and
makes sure a divide-by-zero is not possible.
Change-Id: I33f1e6fb45505dce7d79497d1632c5f63a409151
Reviewed-on: http://gerrit.cloudera.org:8080/4975
Reviewed-by: Henry Robinson <he...@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/e3483c44
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/e3483c44
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/e3483c44
Branch: refs/heads/hadoop-next
Commit: e3483c44a3180a5c1f15a09f7c4f4f7b45ffcb44
Parents: 1a99b78
Author: Sailesh <sa...@cloudera.com>
Authored: Mon Nov 7 11:36:39 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 00:55:47 2016 +0000
----------------------------------------------------------------------
be/src/util/runtime-profile.cc | 4 +++-
1 file changed, 3 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/e3483c44/be/src/util/runtime-profile.cc
----------------------------------------------------------------------
diff --git a/be/src/util/runtime-profile.cc b/be/src/util/runtime-profile.cc
index a9b46b9..19044fa 100644
--- a/be/src/util/runtime-profile.cc
+++ b/be/src/util/runtime-profile.cc
@@ -1037,6 +1037,8 @@ void RuntimeProfile::SummaryStatsCounter::UpdateCounter(int64_t new_value) {
}
void RuntimeProfile::SummaryStatsCounter::SetStats(const TSummaryStatsCounter& counter) {
+ // We drop this input if it looks malformed.
+ if (counter.total_num_values < 0) return;
lock_guard<SpinLock> l(lock_);
unit_ = counter.unit;
sum_ = counter.sum;
@@ -1044,7 +1046,7 @@ void RuntimeProfile::SummaryStatsCounter::SetStats(const TSummaryStatsCounter& c
min_ = counter.min_value;
max_ = counter.max_value;
- value_.Store(sum_ / total_num_values_);
+ value_.Store(total_num_values_ == 0 ? 0 : sum_ / total_num_values_);
}
int64_t RuntimeProfile::SummaryStatsCounter::MinValue() {
[43/50] [abbrv] incubator-impala git commit: IMPALA-4479: Use correct
isSet() thrift function when evaluating constant bool exprs.
Posted by ta...@apache.org.
IMPALA-4479: Use correct isSet() thrift function when evaluating constant bool exprs.
Change-Id: Ie3ba195a5241ca630bd0cf71b83d423733b06546
Reviewed-on: http://gerrit.cloudera.org:8080/5088
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/91b5264e
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/91b5264e
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/91b5264e
Branch: refs/heads/hadoop-next
Commit: 91b5264e5239b2cf3ad4ea896eb28dd5fbdcb74a
Parents: e6e2bae
Author: Alex Behm <al...@cloudera.com>
Authored: Mon Nov 14 15:44:10 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 11:17:43 2016 +0000
----------------------------------------------------------------------
.../main/java/org/apache/impala/analysis/LiteralExpr.java | 2 +-
.../functional-planner/queries/PlannerTest/kudu.test | 9 +++++++++
2 files changed, 10 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/91b5264e/fe/src/main/java/org/apache/impala/analysis/LiteralExpr.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/LiteralExpr.java b/fe/src/main/java/org/apache/impala/analysis/LiteralExpr.java
index 84368f5..de73770 100644
--- a/fe/src/main/java/org/apache/impala/analysis/LiteralExpr.java
+++ b/fe/src/main/java/org/apache/impala/analysis/LiteralExpr.java
@@ -174,7 +174,7 @@ public abstract class LiteralExpr extends Expr implements Comparable<LiteralExpr
result = new NullLiteral();
break;
case BOOLEAN:
- if (val.isBool_val()) result = new BoolLiteral(val.bool_val);
+ if (val.isSetBool_val()) result = new BoolLiteral(val.bool_val);
break;
case TINYINT:
if (val.isSetByte_val()) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/91b5264e/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test b/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
index fbb7f7f..6f7bbff 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
@@ -272,3 +272,12 @@ INSERT INTO KUDU [functional_kudu.testtbl]
|
00:SCAN KUDU [functional_kudu.testtbl]
====
+# IMPALA-4479: Test proper folding of constant boolean exprs.
+select * from functional_kudu.alltypes
+where bool_col = (true and false)
+---- PLAN
+PLAN-ROOT SINK
+|
+00:SCAN KUDU [functional_kudu.alltypes]
+ kudu predicates: bool_col = FALSE
+====
[29/50] [abbrv] incubator-impala git commit: IMPALA-1286: Extract
common conjuncts from disjunctions.
Posted by ta...@apache.org.
IMPALA-1286: Extract common conjuncts from disjunctions.
Adds a new ExprRewriteRule to extract common conjuncts from
disjunctions.
Examples:
(a AND b AND c) OR (b AND d) ==> b AND ((a AND c) OR (d))
(a AND b) OR (a AND b) ==> a AND b
(a AND b AND c) OR (c) ==> c
Adds a new query option ENABLE_EXPR_REWRITES to enable/disable
non-essential expr rewrites in the FE. Note that some rewrites
are required, e.g., BetweenToCompoundRule. Disabling the rewrites
is useful for testing, in particular, to make sure that the exprs
specified in expr-test.cc are executed as written.
Testing: Added a new unit test in ExprRewriteRulesTest.
Change-Id: I3cf9b950afaa3fd753d1b09ba5e540b5258940ad
Reviewed-on: http://gerrit.cloudera.org:8080/4877
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/0aeb6805
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/0aeb6805
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/0aeb6805
Branch: refs/heads/hadoop-next
Commit: 0aeb68050b3bc16b8a10a5a3ae65428e7edd9df5
Parents: cfac09d
Author: Alex Behm <al...@cloudera.com>
Authored: Mon Oct 17 23:01:57 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 09:44:59 2016 +0000
----------------------------------------------------------------------
be/src/exprs/expr-test.cc | 3 +
be/src/service/query-options.cc | 5 +
be/src/service/query-options.h | 5 +-
common/thrift/ImpalaInternalService.thrift | 4 +
common/thrift/ImpalaService.thrift | 4 +
.../apache/impala/analysis/AnalysisContext.java | 7 ++
.../impala/analysis/BetweenPredicate.java | 6 ++
.../impala/analysis/CompoundPredicate.java | 26 +++--
.../apache/impala/analysis/ExistsPredicate.java | 10 +-
.../apache/impala/rewrite/ExprRewriteRule.java | 3 +
.../rewrite/ExtractCommonConjunctRule.java | 102 +++++++++++++++++++
.../impala/analysis/ExprRewriteRulesTest.java | 92 +++++++++++++++++
.../org/apache/impala/analysis/ExprTest.java | 3 +-
.../queries/PlannerTest/subquery-rewrite.test | 2 +-
.../queries/PlannerTest/tpch-all.test | 12 ++-
.../queries/PlannerTest/tpch-kudu.test | 5 +-
.../queries/PlannerTest/tpch-nested.test | 12 ++-
.../queries/PlannerTest/tpch-views.test | 4 +-
18 files changed, 282 insertions(+), 23 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/be/src/exprs/expr-test.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr-test.cc b/be/src/exprs/expr-test.cc
index 5b930e2..5a999b6 100644
--- a/be/src/exprs/expr-test.cc
+++ b/be/src/exprs/expr-test.cc
@@ -6124,6 +6124,9 @@ int main(int argc, char **argv) {
ABORT_IF_ERROR(executor_->Setup());
vector<string> options;
+ // Disable FE Expr rewrites to make sure the Exprs get executed exactly as specified
+ // in the tests here.
+ options.push_back("ENABLE_EXPR_REWRITES=0");
options.push_back("DISABLE_CODEGEN=1");
disable_codegen_ = true;
executor_->setExecOptions(options);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/be/src/service/query-options.cc
----------------------------------------------------------------------
diff --git a/be/src/service/query-options.cc b/be/src/service/query-options.cc
index eb1d2f9..d6d2cb2 100644
--- a/be/src/service/query-options.cc
+++ b/be/src/service/query-options.cc
@@ -441,6 +441,11 @@ Status impala::SetQueryOption(const string& key, const string& value,
}
break;
}
+ case TImpalaQueryOptions::ENABLE_EXPR_REWRITES: {
+ query_options->__set_enable_expr_rewrites(
+ iequals(value, "true") || iequals(value, "1"));
+ break;
+ }
default:
// We hit this DCHECK(false) if we forgot to add the corresponding entry here
// when we add a new query option.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/be/src/service/query-options.h
----------------------------------------------------------------------
diff --git a/be/src/service/query-options.h b/be/src/service/query-options.h
index b1194d3..6531dcb 100644
--- a/be/src/service/query-options.h
+++ b/be/src/service/query-options.h
@@ -35,7 +35,7 @@ class TQueryOptions;
// the DCHECK.
#define QUERY_OPTS_TABLE\
DCHECK_EQ(_TImpalaQueryOptions_VALUES_TO_NAMES.size(),\
- TImpalaQueryOptions::SCRATCH_LIMIT + 1);\
+ TImpalaQueryOptions::ENABLE_EXPR_REWRITES + 1);\
QUERY_OPT_FN(abort_on_default_limit_exceeded, ABORT_ON_DEFAULT_LIMIT_EXCEEDED)\
QUERY_OPT_FN(abort_on_error, ABORT_ON_ERROR)\
QUERY_OPT_FN(allow_unsupported_formats, ALLOW_UNSUPPORTED_FORMATS)\
@@ -85,7 +85,8 @@ class TQueryOptions;
QUERY_OPT_FN(runtime_filter_max_size, RUNTIME_FILTER_MAX_SIZE)\
QUERY_OPT_FN(prefetch_mode, PREFETCH_MODE)\
QUERY_OPT_FN(strict_mode, STRICT_MODE)\
- QUERY_OPT_FN(scratch_limit, SCRATCH_LIMIT);
+ QUERY_OPT_FN(scratch_limit, SCRATCH_LIMIT)\
+ QUERY_OPT_FN(enable_expr_rewrites, ENABLE_EXPR_REWRITES);
/// Converts a TQueryOptions struct into a map of key, value pairs.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/common/thrift/ImpalaInternalService.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/ImpalaInternalService.thrift b/common/thrift/ImpalaInternalService.thrift
index d5a92ca..e510331 100644
--- a/common/thrift/ImpalaInternalService.thrift
+++ b/common/thrift/ImpalaInternalService.thrift
@@ -213,6 +213,10 @@ struct TQueryOptions {
// A limit on the amount of scratch directory space that can be used;
50: optional i64 scratch_limit = -1
+
+ // Indicates whether the FE should rewrite Exprs for optimization purposes.
+ // It's sometimes useful to disable rewrites for testing, e.g., expr-test.cc.
+ 51: optional bool enable_expr_rewrites = true
}
// Impala currently has two types of sessions: Beeswax and HiveServer2
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/common/thrift/ImpalaService.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/ImpalaService.thrift b/common/thrift/ImpalaService.thrift
index 573709b..68a0588 100644
--- a/common/thrift/ImpalaService.thrift
+++ b/common/thrift/ImpalaService.thrift
@@ -243,6 +243,10 @@ enum TImpalaQueryOptions {
// Unspecified or a limit of -1 means no limit;
// Otherwise specified in the same way as MEM_LIMIT.
SCRATCH_LIMIT
+
+ // Indicates whether the FE should rewrite Exprs for optimization purposes.
+ // It's sometimes useful to disable rewrites for testing, e.g., expr-test.cc.
+ ENABLE_EXPR_REWRITES
}
// The summary of an insert.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 b22bccb..3323ed4 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AnalysisContext.java
@@ -37,6 +37,7 @@ 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.rewrite.ExtractCommonConjunctRule;
import org.apache.impala.thrift.TAccessEvent;
import org.apache.impala.thrift.TLineageGraph;
import org.apache.impala.thrift.TQueryCtx;
@@ -65,7 +66,13 @@ public class AnalysisContext {
catalog_ = catalog;
queryCtx_ = queryCtx;
authzConfig_ = authzConfig;
+ // BetweenPredicates must be rewritten to be executable. Other non-essential
+ // expr rewrites can be disabled via a query option. When rewrites are enabled
+ // BetweenPredicates should be rewritten first to help trigger other rules.
List<ExprRewriteRule> rules = Lists.newArrayList(BetweenToCompoundRule.INSTANCE);
+ if (queryCtx.getRequest().getQuery_options().enable_expr_rewrites) {
+ rules.add(ExtractCommonConjunctRule.INSTANCE);
+ }
rewriter_ = new ExprRewriter(rules);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 2459715..ef19a52 100644
--- a/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
+++ b/fe/src/main/java/org/apache/impala/analysis/BetweenPredicate.java
@@ -75,5 +75,11 @@ public class BetweenPredicate extends Predicate {
}
@Override
+ public boolean equals(Object obj) {
+ if (!super.equals(obj)) return false;
+ return isNotBetween_ == ((BetweenPredicate)obj).isNotBetween_;
+ }
+
+ @Override
public Expr clone() { return new BetweenPredicate(this); }
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/fe/src/main/java/org/apache/impala/analysis/CompoundPredicate.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/CompoundPredicate.java b/fe/src/main/java/org/apache/impala/analysis/CompoundPredicate.java
index d549053..6757d26 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CompoundPredicate.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CompoundPredicate.java
@@ -27,6 +27,7 @@ import org.apache.impala.catalog.Type;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.thrift.TExprNode;
import org.apache.impala.thrift.TExprNodeType;
+
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
@@ -192,16 +193,27 @@ public class CompoundPredicate extends Predicate {
* Creates a conjunctive predicate from a list of exprs.
*/
public static Expr createConjunctivePredicate(List<Expr> conjuncts) {
- Expr conjunctivePred = null;
- for (Expr expr: conjuncts) {
- if (conjunctivePred == null) {
- conjunctivePred = expr;
+ return createCompoundTree(conjuncts, Operator.AND);
+ }
+
+ /**
+ * Creates a disjunctive predicate from a list of exprs.
+ */
+ public static Expr createDisjunctivePredicate(List<Expr> disjuncts) {
+ return createCompoundTree(disjuncts, Operator.OR);
+ }
+
+ private static Expr createCompoundTree(List<Expr> exprs, Operator op) {
+ Preconditions.checkState(op == Operator.AND || op == Operator.OR);
+ Expr result = null;
+ for (Expr expr: exprs) {
+ if (result == null) {
+ result = expr;
continue;
}
- conjunctivePred = new CompoundPredicate(CompoundPredicate.Operator.AND,
- expr, conjunctivePred);
+ result = new CompoundPredicate(op, result, expr);
}
- return conjunctivePred;
+ return result;
}
@Override
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/fe/src/main/java/org/apache/impala/analysis/ExistsPredicate.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/ExistsPredicate.java b/fe/src/main/java/org/apache/impala/analysis/ExistsPredicate.java
index 3131acf..578c786 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ExistsPredicate.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ExistsPredicate.java
@@ -17,11 +17,11 @@
package org.apache.impala.analysis;
+import org.apache.impala.common.AnalysisException;
+import org.apache.impala.thrift.TExprNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import org.apache.impala.common.AnalysisException;
-import org.apache.impala.thrift.TExprNode;
import com.google.common.base.Preconditions;
/**
@@ -69,6 +69,12 @@ public class ExistsPredicate extends Predicate {
}
@Override
+ public boolean equals(Object o) {
+ if (!super.equals(o)) return false;
+ return notExists_ == ((ExistsPredicate)o).notExists_;
+ }
+
+ @Override
public Expr clone() { return new ExistsPredicate(this); }
@Override
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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
index 48054a8..bbd7c38 100644
--- a/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java
+++ b/fe/src/main/java/org/apache/impala/rewrite/ExprRewriteRule.java
@@ -24,6 +24,9 @@ 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.
+ * An ExprRewriteRule is intended to apply its transformation on a single Expr and not
+ * recursively on all its children. The recursive and repeated application of
+ * ExprRewriteRules is driven by an ExprRewriter.
*/
public interface ExprRewriteRule {
/**
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/fe/src/main/java/org/apache/impala/rewrite/ExtractCommonConjunctRule.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/rewrite/ExtractCommonConjunctRule.java b/fe/src/main/java/org/apache/impala/rewrite/ExtractCommonConjunctRule.java
new file mode 100644
index 0000000..e1515d3
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/rewrite/ExtractCommonConjunctRule.java
@@ -0,0 +1,102 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.impala.rewrite;
+
+import java.util.List;
+
+import org.apache.impala.analysis.Analyzer;
+import org.apache.impala.analysis.CompoundPredicate;
+import org.apache.impala.analysis.Expr;
+import org.apache.impala.common.AnalysisException;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.Lists;
+
+/**
+ * This rule extracts common conjuncts from multiple disjunctions when it is applied
+ * recursively bottom-up to a tree of CompoundPredicates.
+ *
+ * Examples:
+ * (a AND b AND c) OR (b AND d) ==> b AND ((a AND c) OR (d))
+ * (a AND b) OR (a AND b) ==> a AND b
+ * (a AND b AND c) OR (c) ==> c
+ */
+public class ExtractCommonConjunctRule implements ExprRewriteRule {
+ public static ExprRewriteRule INSTANCE = new ExtractCommonConjunctRule();
+
+ // Arbitrary limit the number of Expr.equals() comparisons in the O(N^2) loop below.
+ // Used to avoid pathologically expensive invocations of this rule.
+ // TODO: Implement Expr.hashCode() and move to a hash-based solution for the core
+ // Expr.equals() comparison loop below.
+ private static final int MAX_EQUALS_COMPARISONS = 30 * 30;
+
+ @Override
+ public Expr apply(Expr expr, Analyzer analyzer) throws AnalysisException {
+ if (!Expr.IS_OR_PREDICATE.apply(expr)) return expr;
+
+ // Get childrens' conjuncts and check
+ List<Expr> child0Conjuncts = expr.getChild(0).getConjuncts();
+ List<Expr> child1Conjuncts = expr.getChild(1).getConjuncts();
+ Preconditions.checkState(!child0Conjuncts.isEmpty() && !child1Conjuncts.isEmpty());
+ // Impose cost bound.
+ if (child0Conjuncts.size() * child1Conjuncts.size() > MAX_EQUALS_COMPARISONS) {
+ return expr;
+ }
+
+ // Find common conjuncts.
+ List<Expr> commonConjuncts = Lists.newArrayList();
+ for (Expr conjunct: child0Conjuncts) {
+ if (child1Conjuncts.contains(conjunct)) {
+ // The conjunct may have parenthesis but there's no need to preserve them.
+ // Removing them makes the toSql() easier to read.
+ conjunct.setPrintSqlInParens(false);
+ commonConjuncts.add(conjunct);
+ }
+ }
+ if (commonConjuncts.isEmpty()) return expr;
+
+ // Remove common conjuncts.
+ child0Conjuncts.removeAll(commonConjuncts);
+ child1Conjuncts.removeAll(commonConjuncts);
+
+ // Check special case where one child contains all conjuncts of the other.
+ // (a AND b) OR (a AND b) ==> a AND b
+ // (a AND b AND c) OR (c) ==> c
+ if (child0Conjuncts.isEmpty() || child1Conjuncts.isEmpty()) {
+ Preconditions.checkState(!commonConjuncts.isEmpty());
+ Expr result = CompoundPredicate.createConjunctivePredicate(commonConjuncts);
+ result.analyze(analyzer);
+ return result;
+ }
+
+ // Re-assemble disjunctive predicate.
+ Expr child0Disjunct = CompoundPredicate.createConjunctivePredicate(child0Conjuncts);
+ child0Disjunct.setPrintSqlInParens(expr.getChild(0).getPrintSqlInParens());
+ Expr child1Disjunct = CompoundPredicate.createConjunctivePredicate(child1Conjuncts);
+ child1Disjunct.setPrintSqlInParens(expr.getChild(1).getPrintSqlInParens());
+ List<Expr> newDisjuncts = Lists.newArrayList(child0Disjunct, child1Disjunct);
+ Expr newDisjunction = CompoundPredicate.createDisjunctivePredicate(newDisjuncts);
+ newDisjunction.setPrintSqlInParens(true);
+ Expr result = CompoundPredicate.createConjunction(newDisjunction,
+ CompoundPredicate.createConjunctivePredicate(commonConjuncts));
+ result.analyze(analyzer);
+ return result;
+ }
+
+ private ExtractCommonConjunctRule() {}
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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
index d3d52b4..16ca7e2 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ExprRewriteRulesTest.java
@@ -25,6 +25,7 @@ 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.apache.impala.rewrite.ExtractCommonConjunctRule;
import org.junit.Assert;
import org.junit.Test;
@@ -106,4 +107,95 @@ public class ExprRewriteRulesTest extends FrontendTestBase {
"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)");
}
+
+ @Test
+ public void TestExtractCommonConjunctsRule() throws AnalysisException {
+ ExprRewriteRule rule = ExtractCommonConjunctRule.INSTANCE;
+
+ // One common conjunct: int_col < 10
+ RewritesOk(
+ "(int_col < 10 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col < 10)", rule,
+ "int_col < 10 AND ((bigint_col < 10) OR (string_col = '10'))");
+ // One common conjunct in multiple disjuncts: int_col < 10
+ RewritesOk(
+ "(int_col < 10 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col < 10) or " +
+ "(id < 20 and int_col < 10) or " +
+ "(int_col < 10 and float_col > 3.14)", rule,
+ "int_col < 10 AND " +
+ "((bigint_col < 10) OR (string_col = '10') OR " +
+ "(id < 20) OR (float_col > 3.14))");
+ // Same as above but with a bushy OR tree.
+ RewritesOk(
+ "((int_col < 10 and bigint_col < 10) or " +
+ " (string_col = '10' and int_col < 10)) or " +
+ "((id < 20 and int_col < 10) or " +
+ " (int_col < 10 and float_col > 3.14))", rule,
+ "int_col < 10 AND " +
+ "((bigint_col < 10) OR (string_col = '10') OR " +
+ "(id < 20) OR (float_col > 3.14))");
+ // Multiple common conjuncts: int_col < 10, bool_col is null
+ RewritesOk(
+ "(int_col < 10 and bigint_col < 10 and bool_col is null) or " +
+ "(bool_col is null and string_col = '10' and int_col < 10)", rule,
+ "int_col < 10 AND bool_col IS NULL AND " +
+ "((bigint_col < 10) OR (string_col = '10'))");
+ // Negated common conjunct: !(int_col=5 or tinyint_col > 9)
+ RewritesOk(
+ "(!(int_col=5 or tinyint_col > 9) and double_col = 7) or " +
+ "(!(int_col=5 or tinyint_col > 9) and double_col = 8)", rule,
+ "NOT (int_col = 5 OR tinyint_col > 9) AND " +
+ "((double_col = 7) OR (double_col = 8))");
+
+ // Test common BetweenPredicate: int_col between 10 and 30
+ RewritesOk(
+ "(int_col between 10 and 30 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col between 10 and 30) or " +
+ "(id < 20 and int_col between 10 and 30) or " +
+ "(int_col between 10 and 30 and float_col > 3.14)", rule,
+ "int_col BETWEEN 10 AND 30 AND " +
+ "((bigint_col < 10) OR (string_col = '10') OR " +
+ "(id < 20) OR (float_col > 3.14))");
+ // Test common NOT BetweenPredicate: int_col not between 10 and 30
+ RewritesOk(
+ "(int_col not between 10 and 30 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col not between 10 and 30) or " +
+ "(id < 20 and int_col not between 10 and 30) or " +
+ "(int_col not between 10 and 30 and float_col > 3.14)", rule,
+ "int_col NOT BETWEEN 10 AND 30 AND " +
+ "((bigint_col < 10) OR (string_col = '10') OR " +
+ "(id < 20) OR (float_col > 3.14))");
+ // Test mixed BetweenPredicates are not common.
+ RewritesOk(
+ "(int_col not between 10 and 30 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col between 10 and 30) or " +
+ "(id < 20 and int_col not between 10 and 30) or " +
+ "(int_col between 10 and 30 and float_col > 3.14)", rule,
+ null);
+
+ // All conjuncts are common.
+ RewritesOk(
+ "(int_col < 10 and id between 5 and 6) or " +
+ "(id between 5 and 6 and int_col < 10) or " +
+ "(int_col < 10 and id between 5 and 6)", rule,
+ "int_col < 10 AND id BETWEEN 5 AND 6");
+ // Complex disjuncts are redundant.
+ RewritesOk(
+ "(int_col < 10) or " +
+ "(int_col < 10 and bigint_col < 10 and bool_col is null) or " +
+ "(int_col < 10) or " +
+ "(bool_col is null and int_col < 10)", rule,
+ "int_col < 10");
+
+ // Due to the shape of the original OR tree we are left with redundant
+ // disjuncts after the extraction.
+ RewritesOk(
+ "(int_col < 10 and bigint_col < 10) or " +
+ "(string_col = '10' and int_col < 10) or " +
+ "(id < 20 and int_col < 10) or " +
+ "(int_col < 10 and id < 20)", rule,
+ "int_col < 10 AND " +
+ "((bigint_col < 10) OR (string_col = '10') OR (id < 20) OR (id < 20))");
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/fe/src/test/java/org/apache/impala/analysis/ExprTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ExprTest.java b/fe/src/test/java/org/apache/impala/analysis/ExprTest.java
index 7ae0f89..e0eca0a 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ExprTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ExprTest.java
@@ -19,10 +19,9 @@ package org.apache.impala.analysis;
import static org.junit.Assert.fail;
-import org.junit.Test;
-
import org.apache.impala.catalog.ScalarType;
import org.apache.impala.catalog.Type;
+import org.junit.Test;
public class ExprTest {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/testdata/workloads/functional-planner/queries/PlannerTest/subquery-rewrite.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/subquery-rewrite.test b/testdata/workloads/functional-planner/queries/PlannerTest/subquery-rewrite.test
index 0880d9f..dfc9072 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/subquery-rewrite.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/subquery-rewrite.test
@@ -1638,7 +1638,7 @@ where
PLAN-ROOT SINK
|
05:HASH JOIN [RIGHT SEMI JOIN]
-| hash predicates: sum(t1.id) = t.int_col
+| hash predicates: t1.id + t2.id = t.int_col
|
|--00:SCAN HDFS [functional.alltypestiny t]
| partitions=4/4 files=4 size=460B
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 9b17ff1..219e5a9 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-all.test
@@ -3415,14 +3415,16 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- p_partkey
|
|--01:SCAN HDFS [tpch.part]
| partitions=1/1 files=1 size=22.83MB
+| predicates: p_size >= 1
|
00:SCAN HDFS [tpch.lineitem]
partitions=1/1 files=1 size=718.94MB
+ predicates: l_shipmode IN ('AIR', 'AIR REG'), l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> l_partkey
---- DISTRIBUTEDPLAN
PLAN-ROOT SINK
@@ -3437,16 +3439,18 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- p_partkey
|
|--04:EXCHANGE [BROADCAST]
| |
| 01:SCAN HDFS [tpch.part]
| partitions=1/1 files=1 size=22.83MB
+| predicates: p_size >= 1
|
00:SCAN HDFS [tpch.lineitem]
partitions=1/1 files=1 size=718.94MB
+ predicates: l_shipmode IN ('AIR', 'AIR REG'), l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> l_partkey
---- PARALLELPLANS
PLAN-ROOT SINK
@@ -3461,7 +3465,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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- p_partkey
|
|--JOIN BUILD
@@ -3472,9 +3476,11 @@ PLAN-ROOT SINK
| |
| 01:SCAN HDFS [tpch.part]
| partitions=1/1 files=1 size=22.83MB
+| predicates: p_size >= 1
|
00:SCAN HDFS [tpch.lineitem]
partitions=1/1 files=1 size=718.94MB
+ predicates: l_shipmode IN ('AIR', 'AIR REG'), l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> l_partkey
====
# TPCH-Q20
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 a5e6e07..a5f2511 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-kudu.test
@@ -1074,11 +1074,14 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
|
|--01:SCAN KUDU [tpch_kudu.part]
+| kudu predicates: p_size >= 1
|
00:SCAN KUDU [tpch_kudu.lineitem]
+ predicates: l_shipmode IN ('AIR', 'AIR REG')
+ kudu predicates: l_shipinstruct = 'DELIVER IN PERSON'
====
# Q20 - Potential Part Promotion Query
select
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 0c3dd9b..31e5d40 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-nested.test
@@ -632,7 +632,7 @@ PLAN-ROOT SINK
| output: sum(l_extendedprice * l_discount)
|
00:SCAN HDFS [tpch_nested_parquet.customer.c_orders.o_lineitems]
- partitions=1/1 files=4 size=292.35MB
+ partitions=1/1 files=4 size=577.87MB
predicates: l_discount <= 0.07, l_discount >= 0.05, l_quantity < 24, l_shipdate < '1995-01-01', l_shipdate >= '1994-01-01'
---- DISTRIBUTEDPLAN
PLAN-ROOT SINK
@@ -646,7 +646,7 @@ PLAN-ROOT SINK
| output: sum(l_extendedprice * l_discount)
|
00:SCAN HDFS [tpch_nested_parquet.customer.c_orders.o_lineitems]
- partitions=1/1 files=4 size=292.35MB
+ partitions=1/1 files=4 size=577.87MB
predicates: l_discount <= 0.07, l_discount >= 0.05, l_quantity < 24, l_shipdate < '1995-01-01', l_shipdate >= '1994-01-01'
====
# TPCH-Q7
@@ -2117,14 +2117,16 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- p_partkey
|
|--01:SCAN HDFS [tpch_nested_parquet.part p]
| partitions=1/1 files=1 size=6.20MB
+| predicates: p_size >= 1
|
00:SCAN HDFS [tpch_nested_parquet.customer.c_orders.o_lineitems l]
partitions=1/1 files=4 size=577.87MB
+ predicates: l_shipmode IN ('AIR', 'AIR REG'), l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> l_partkey
---- DISTRIBUTEDPLAN
PLAN-ROOT SINK
@@ -2139,16 +2141,18 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- p_partkey
|
|--04:EXCHANGE [BROADCAST]
| |
| 01:SCAN HDFS [tpch_nested_parquet.part p]
| partitions=1/1 files=1 size=6.20MB
+| predicates: p_size >= 1
|
00:SCAN HDFS [tpch_nested_parquet.customer.c_orders.o_lineitems l]
partitions=1/1 files=4 size=577.87MB
+ predicates: l_shipmode IN ('AIR', 'AIR REG'), l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> l_partkey
====
# TPCH-Q20
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0aeb6805/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 de442b2..c927b8b 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/tpch-views.test
@@ -1253,14 +1253,16 @@ 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 >= 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'))
+| 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 <= 5) 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 <= 10) 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 <= 15))
| runtime filters: RF000 <- tpch.part.p_partkey
|
|--01:SCAN HDFS [tpch.part]
| partitions=1/1 files=1 size=22.83MB
+| predicates: tpch.part.p_size >= 1
|
00:SCAN HDFS [tpch.lineitem]
partitions=1/1 files=1 size=718.94MB
+ predicates: tpch.lineitem.l_shipmode IN ('AIR', 'AIR REG'), tpch.lineitem.l_shipinstruct = 'DELIVER IN PERSON'
runtime filters: RF000 -> tpch.lineitem.l_partkey
====
# TPCH-Q20
[46/50] [abbrv] incubator-impala git commit: IMPALA-4436:
StringValue::StringCompare() should match strncmp()
Posted by ta...@apache.org.
IMPALA-4436: StringValue::StringCompare() should match strncmp()
According to the C standard, strncmp() interprets characters as
unsigned, whereas StringCompare() uses char (which happens to be
signed). This means that for values greater than 127, they don't give
the same result (which is especially bad considering StringCompare()
falls back to strncmp(), and so the answer depends on the mismatched
position).
Fix StringCompare() to interpret as unsigned char.
Change-Id: Ic0750f98d8c5ef7d0c0ea279cd1f80b4acbad1be
Reviewed-on: http://gerrit.cloudera.org:8080/5083
Reviewed-by: Dan Hecht <dh...@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/6937fa9a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/6937fa9a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/6937fa9a
Branch: refs/heads/hadoop-next
Commit: 6937fa9a4caa9039a95d661ddf209777caa805f5
Parents: 4b77488
Author: Dan Hecht <dh...@cloudera.com>
Authored: Mon Nov 14 16:47:39 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 20:47:18 2016 +0000
----------------------------------------------------------------------
be/src/runtime/CMakeLists.txt | 1 +
be/src/runtime/string-compare-test.cc | 67 ++++++++++++++++++++++++++++++
be/src/runtime/string-value.inline.h | 4 +-
3 files changed, 71 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/6937fa9a/be/src/runtime/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/be/src/runtime/CMakeLists.txt b/be/src/runtime/CMakeLists.txt
index a0b0a94..19db090 100644
--- a/be/src/runtime/CMakeLists.txt
+++ b/be/src/runtime/CMakeLists.txt
@@ -78,6 +78,7 @@ ADD_BE_TEST(disk-io-mgr-test)
ADD_BE_TEST(buffered-block-mgr-test)
ADD_BE_TEST(parallel-executor-test)
ADD_BE_TEST(raw-value-test)
+ADD_BE_TEST(string-compare-test)
ADD_BE_TEST(string-search-test)
ADD_BE_TEST(string-value-test)
ADD_BE_TEST(thread-resource-mgr-test)
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/6937fa9a/be/src/runtime/string-compare-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/string-compare-test.cc b/be/src/runtime/string-compare-test.cc
new file mode 100644
index 0000000..ef81ac6
--- /dev/null
+++ b/be/src/runtime/string-compare-test.cc
@@ -0,0 +1,67 @@
+// 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.
+
+#include <cstring>
+
+#include "runtime/string-value.inline.h"
+#include "testutil/gtest-util.h"
+
+#include "common/names.h"
+
+// Test to verify that impala::StringCompare() and clib strncmp() give equivalent results.
+namespace impala {
+
+// Expect that strncmp() and StringCompare() return the same result.
+static void RunTestCase(const string& l, const string& r) {
+ int cmp_len = ::min(l.size(), r.size());
+ EXPECT_EQ(strncmp(l.c_str(), r.c_str(), cmp_len),
+ StringCompare(l.c_str(), l.size(), r.c_str(), r.size(), cmp_len));
+}
+
+TEST(StringCompareTest, Basic) {
+ const struct Cases {
+ string lhs, rhs;
+ } cases[] = {{"abc", "abc"},
+ {"abc", "abd"},
+ {"", ""},
+ {"\x01", "\x01"},
+ {"\x01", "\x02"},
+ {"\x7f", "\x01"},
+ {"\x80", "\x80"},
+ {"\x80", "\x01"},
+ {"\x7F", "\x80"},
+ {"\xFF", "\x01"},
+ {"\xFF", "\x7F"},
+ {"\xE9", "\x32"},
+ {"\x32", "\xE5"},
+ {"\xE5", "\xE9"}};
+
+ for (const Cases& c : cases) {
+ RunTestCase(c.lhs, c.rhs);
+ RunTestCase(c.rhs, c.lhs);
+ }
+
+ // Induce the SSE 4.2 code path by using longer strings.
+ string suffix = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
+ for (const Cases& c : cases) {
+ RunTestCase(c.lhs + suffix, c.rhs + suffix);
+ RunTestCase(c.rhs + suffix, c.lhs + suffix);
+ }
+}
+}
+
+IMPALA_TEST_MAIN();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/6937fa9a/be/src/runtime/string-value.inline.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/string-value.inline.h b/be/src/runtime/string-value.inline.h
index f52005f..073d01f 100644
--- a/be/src/runtime/string-value.inline.h
+++ b/be/src/runtime/string-value.inline.h
@@ -47,7 +47,9 @@ static inline int StringCompare(const char* s1, int n1, const char* s2, int n2,
SSEUtil::CHARS_PER_128_BIT_REGISTER, xmm1,
SSEUtil::CHARS_PER_128_BIT_REGISTER);
if (chars_match != SSEUtil::CHARS_PER_128_BIT_REGISTER) {
- return s1[chars_match] - s2[chars_match];
+ // Match strncmp() behavior, which interprets characters as unsigned char.
+ return static_cast<unsigned char>(s1[chars_match]) -
+ static_cast<unsigned char>(s2[chars_match]);
}
len -= SSEUtil::CHARS_PER_128_BIT_REGISTER;
s1 += SSEUtil::CHARS_PER_128_BIT_REGISTER;
[04/50] [abbrv] incubator-impala git commit: IMPALA-4435: Fix
in-predicate-benchmark linking by moving templates
Posted by ta...@apache.org.
IMPALA-4435: Fix in-predicate-benchmark linking by moving templates
In C++ (without export, which was removed in C++11), templates
definitions (and not just declarations) must be in headers in order to
be implicitly instantiated by callers. in-predicate-benchmark was
http://gerrit.cloudera.org:8080/4758; this patch fixes the linker
errors that were caused in some build modes by #including only the
template declarations.
Change-Id: Ie95ec71242b97f28c68e37d6f44956f2eeff8105
Reviewed-on: http://gerrit.cloudera.org:8080/4966
Reviewed-by: Jim Apple <jb...@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/7c001888
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/7c001888
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/7c001888
Branch: refs/heads/hadoop-next
Commit: 7c0018881b5c111ab175bbbc678bebc902126f5a
Parents: 120f34b
Author: Jim Apple <jb...@cloudera.com>
Authored: Sat Nov 5 07:08:27 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sun Nov 6 01:51:59 2016 +0000
----------------------------------------------------------------------
be/src/exprs/in-predicate-ir.cc | 110 --------------------------------
be/src/exprs/in-predicate.h | 117 ++++++++++++++++++++++++++++++++++-
2 files changed, 114 insertions(+), 113 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/7c001888/be/src/exprs/in-predicate-ir.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/in-predicate-ir.cc b/be/src/exprs/in-predicate-ir.cc
index 51aeec9..998fae0 100644
--- a/be/src/exprs/in-predicate-ir.cc
+++ b/be/src/exprs/in-predicate-ir.cc
@@ -19,118 +19,12 @@
#include "exprs/in-predicate.h"
-#include "exprs/anyval-util.h"
-#include "runtime/decimal-value.h"
-#include "runtime/string-value.inline.h"
-
#include "common/names.h"
using namespace impala_udf;
namespace impala {
-// Templated getter functions for extracting 'SetType' values from AnyVals
-template<typename T, typename SetType>
-SetType GetVal(const FunctionContext::TypeDesc* type, const T& x) {
- DCHECK(!x.is_null);
- return x.val;
-}
-
-template<> StringValue GetVal(const FunctionContext::TypeDesc* type, const StringVal& x) {
- DCHECK(!x.is_null);
- return StringValue::FromStringVal(x);
-}
-
-template<> TimestampValue GetVal(
- const FunctionContext::TypeDesc* type, const TimestampVal& x) {
- return TimestampValue::FromTimestampVal(x);
-}
-
-template<> Decimal16Value GetVal(
- const FunctionContext::TypeDesc* type, const DecimalVal& x) {
- if (type->precision <= ColumnType::MAX_DECIMAL4_PRECISION) {
- return Decimal16Value(x.val4);
- } else if (type->precision <= ColumnType::MAX_DECIMAL8_PRECISION) {
- return Decimal16Value(x.val8);
- } else {
- return Decimal16Value(x.val16);
- }
-}
-
-template<typename T, typename SetType>
-void InPredicate::SetLookupPrepare(
- FunctionContext* ctx, FunctionContext::FunctionStateScope scope) {
- if (scope != FunctionContext::FRAGMENT_LOCAL) return;
-
- SetLookupState<SetType>* state = new SetLookupState<SetType>;
- state->type = ctx->GetArgType(0);
- state->contains_null = false;
- for (int i = 1; i < ctx->GetNumArgs(); ++i) {
- DCHECK(ctx->IsArgConstant(i));
- T* arg = reinterpret_cast<T*>(ctx->GetConstantArg(i));
- if (arg->is_null) {
- state->contains_null = true;
- } else {
- state->val_set.insert(GetVal<T, SetType>(state->type, *arg));
- }
- }
- ctx->SetFunctionState(scope, state);
-}
-
-template<typename SetType>
-void InPredicate::SetLookupClose(
- FunctionContext* ctx, FunctionContext::FunctionStateScope scope) {
- if (scope != FunctionContext::FRAGMENT_LOCAL) return;
- SetLookupState<SetType>* state =
- reinterpret_cast<SetLookupState<SetType>*>(ctx->GetFunctionState(scope));
- delete state;
-}
-
-template<typename T, typename SetType, bool not_in, InPredicate::Strategy strategy>
-BooleanVal InPredicate::TemplatedIn(
- FunctionContext* ctx, const T& val, int num_args, const T* args) {
- if (val.is_null) return BooleanVal::null();
-
- BooleanVal found;
- if (strategy == SET_LOOKUP) {
- SetLookupState<SetType>* state = reinterpret_cast<SetLookupState<SetType>*>(
- ctx->GetFunctionState(FunctionContext::FRAGMENT_LOCAL));
- DCHECK(state != NULL);
- found = SetLookup(state, val);
- } else {
- DCHECK_EQ(strategy, ITERATE);
- found = Iterate(ctx->GetArgType(0), val, num_args, args);
- }
- if (found.is_null) return BooleanVal::null();
- return BooleanVal(found.val ^ not_in);
-}
-
-template<typename T, typename SetType>
-BooleanVal InPredicate::SetLookup(
- SetLookupState<SetType>* state, const T& v) {
- DCHECK(state != NULL);
- SetType val = GetVal<T, SetType>(state->type, v);
- bool found = state->val_set.find(val) != state->val_set.end();
- if (found) return BooleanVal(true);
- if (state->contains_null) return BooleanVal::null();
- return BooleanVal(false);
-}
-
-template<typename T>
-BooleanVal InPredicate::Iterate(
- const FunctionContext::TypeDesc* type, const T& val, int num_args, const T* args) {
- bool found_null = false;
- for (int i = 0; i < num_args; ++i) {
- if (args[i].is_null) {
- found_null = true;
- } else if (AnyValUtil::Equals(*type, val, args[i])) {
- return BooleanVal(true);
- }
- }
- if (found_null) return BooleanVal::null();
- return BooleanVal(false);
-}
-
#define IN_FUNCTIONS(AnyValType, SetType, type_name) \
BooleanVal InPredicate::InSetLookup( \
FunctionContext* context, const AnyValType& val, int num_args, \
@@ -181,8 +75,4 @@ IN_FUNCTIONS(StringVal, StringValue, string)
IN_FUNCTIONS(TimestampVal, TimestampValue, timestamp)
IN_FUNCTIONS(DecimalVal, Decimal16Value, decimal)
-// Needed for in-predicate-benchmark to build
-template BooleanVal InPredicate::Iterate<IntVal>(
- const FunctionContext::TypeDesc*, const IntVal&, int, const IntVal*);
-
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/7c001888/be/src/exprs/in-predicate.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/in-predicate.h b/be/src/exprs/in-predicate.h
index d01d844..fd53a42 100644
--- a/be/src/exprs/in-predicate.h
+++ b/be/src/exprs/in-predicate.h
@@ -21,6 +21,9 @@
#include <string>
#include "exprs/predicate.h"
+#include "exprs/anyval-util.h"
+#include "runtime/decimal-value.h"
+#include "runtime/string-value.inline.h"
#include "udf/udf.h"
namespace impala {
@@ -293,7 +296,7 @@ class InPredicate : public Predicate {
/// functions.
template<typename T, typename SetType, bool not_in, Strategy strategy>
static inline impala_udf::BooleanVal TemplatedIn(
- impala_udf::FunctionContext* context, const T& val, int num_args, const T* args);
+ impala_udf::FunctionContext* ctx, const T& val, int num_args, const T* args);
/// Initializes an SetLookupState in ctx.
template<typename T, typename SetType>
@@ -308,12 +311,120 @@ class InPredicate : public Predicate {
template<typename T, typename SetType>
static BooleanVal SetLookup(SetLookupState<SetType>* state, const T& v);
- /// Iterates through each vararg looking for val. 'type' is the type of 'val' and 'args'.
- template<typename T>
+ /// Iterates through each vararg looking for val. 'type' is the type of 'val' and
+ /// 'args'.
+ template <typename T>
static BooleanVal Iterate(
const FunctionContext::TypeDesc* type, const T& val, int num_args, const T* args);
+
+ // Templated getter functions for extracting 'SetType' values from AnyVals
+ template <typename T, typename SetType>
+ static inline SetType GetVal(const FunctionContext::TypeDesc* type, const T& x);
};
+template <typename T, typename SetType, bool not_in, InPredicate::Strategy strategy>
+inline impala_udf::BooleanVal InPredicate::TemplatedIn(
+ impala_udf::FunctionContext* ctx, const T& val, int num_args, const T* args) {
+ if (val.is_null) return BooleanVal::null();
+
+ BooleanVal found;
+ if (strategy == SET_LOOKUP) {
+ SetLookupState<SetType>* state = reinterpret_cast<SetLookupState<SetType>*>(
+ ctx->GetFunctionState(FunctionContext::FRAGMENT_LOCAL));
+ DCHECK(state != NULL);
+ found = SetLookup(state, val);
+ } else {
+ DCHECK_EQ(strategy, ITERATE);
+ found = Iterate(ctx->GetArgType(0), val, num_args, args);
+ }
+ if (found.is_null) return BooleanVal::null();
+ return BooleanVal(found.val ^ not_in);
+}
+
+template <typename T, typename SetType>
+void InPredicate::SetLookupPrepare(
+ FunctionContext* ctx, FunctionContext::FunctionStateScope scope) {
+ if (scope != FunctionContext::FRAGMENT_LOCAL) return;
+
+ SetLookupState<SetType>* state = new SetLookupState<SetType>;
+ state->type = ctx->GetArgType(0);
+ state->contains_null = false;
+ for (int i = 1; i < ctx->GetNumArgs(); ++i) {
+ DCHECK(ctx->IsArgConstant(i));
+ T* arg = reinterpret_cast<T*>(ctx->GetConstantArg(i));
+ if (arg->is_null) {
+ state->contains_null = true;
+ } else {
+ state->val_set.insert(GetVal<T, SetType>(state->type, *arg));
+ }
+ }
+ ctx->SetFunctionState(scope, state);
+}
+
+template <typename SetType>
+void InPredicate::SetLookupClose(
+ FunctionContext* ctx, FunctionContext::FunctionStateScope scope) {
+ if (scope != FunctionContext::FRAGMENT_LOCAL) return;
+ SetLookupState<SetType>* state =
+ reinterpret_cast<SetLookupState<SetType>*>(ctx->GetFunctionState(scope));
+ delete state;
+}
+
+template <typename T, typename SetType>
+BooleanVal InPredicate::SetLookup(SetLookupState<SetType>* state, const T& v) {
+ DCHECK(state != NULL);
+ SetType val = GetVal<T, SetType>(state->type, v);
+ bool found = state->val_set.find(val) != state->val_set.end();
+ if (found) return BooleanVal(true);
+ if (state->contains_null) return BooleanVal::null();
+ return BooleanVal(false);
+}
+
+template <typename T>
+BooleanVal InPredicate::Iterate(
+ const FunctionContext::TypeDesc* type, const T& val, int num_args, const T* args) {
+ bool found_null = false;
+ for (int i = 0; i < num_args; ++i) {
+ if (args[i].is_null) {
+ found_null = true;
+ } else if (AnyValUtil::Equals(*type, val, args[i])) {
+ return BooleanVal(true);
+ }
+ }
+ if (found_null) return BooleanVal::null();
+ return BooleanVal(false);
+}
+
+template <typename T, typename SetType>
+inline SetType InPredicate::GetVal(const FunctionContext::TypeDesc* type, const T& x) {
+ DCHECK(!x.is_null);
+ return x.val;
+}
+
+template <>
+inline StringValue InPredicate::GetVal(
+ const FunctionContext::TypeDesc* type, const StringVal& x) {
+ DCHECK(!x.is_null);
+ return StringValue::FromStringVal(x);
+}
+
+template <>
+inline TimestampValue InPredicate::GetVal(
+ const FunctionContext::TypeDesc* type, const TimestampVal& x) {
+ return TimestampValue::FromTimestampVal(x);
+}
+
+template <>
+inline Decimal16Value InPredicate::GetVal(
+ const FunctionContext::TypeDesc* type, const DecimalVal& x) {
+ if (type->precision <= ColumnType::MAX_DECIMAL4_PRECISION) {
+ return Decimal16Value(x.val4);
+ } else if (type->precision <= ColumnType::MAX_DECIMAL8_PRECISION) {
+ return Decimal16Value(x.val8);
+ } else {
+ return Decimal16Value(x.val16);
+ }
+}
}
#endif
[34/50] [abbrv] incubator-impala git commit: IMPALA-4480:
zero_length_region_ must be as aligned as max_align_t
Posted by ta...@apache.org.
IMPALA-4480: zero_length_region_ must be as aligned as max_align_t
MemPool::TryAllocateAligned returns memory that might be that aligned,
and it returns &MemPool::zero_length_region_ when called to allocate a
block of size 0.
While I'm here, do some things to make diagnosing test failures from
terminal output easier.
Change-Id: Ia31b27e38897f357478c4eedaab0c787e731b2d4
Reviewed-on: http://gerrit.cloudera.org:8080/5062
Reviewed-by: Dan Hecht <dh...@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/10a4c5a2
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/10a4c5a2
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/10a4c5a2
Branch: refs/heads/hadoop-next
Commit: 10a4c5a2e47ec7bf1e563b6a75d1bf2afb47ebd8
Parents: 4258b9f
Author: Jim Apple <jb...@cloudera.com>
Authored: Sun Nov 13 13:49:28 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 14 21:25:42 2016 +0000
----------------------------------------------------------------------
be/src/runtime/mem-pool-test.cc | 5 +++--
be/src/runtime/mem-pool.h | 7 ++++---
bin/run-backend-tests.sh | 1 +
3 files changed, 8 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10a4c5a2/be/src/runtime/mem-pool-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool-test.cc b/be/src/runtime/mem-pool-test.cc
index e6cb3b9..a39a120 100644
--- a/be/src/runtime/mem-pool-test.cc
+++ b/be/src/runtime/mem-pool-test.cc
@@ -504,8 +504,9 @@ TEST(MemPoolTest, TryAllocateAligned) {
for (int i = 0; i < NUM_ALLOCATIONS; ++i) {
uint8_t* ptr = pool.TryAllocateAligned(size, alignment);
- ASSERT_TRUE(ptr != NULL);
- ASSERT_EQ(0, reinterpret_cast<uintptr_t>(ptr) % alignment);
+ ASSERT_TRUE(ptr != NULL) << "size=" << size << " alignment=" << alignment;
+ ASSERT_EQ(0, reinterpret_cast<uintptr_t>(ptr) % alignment)
+ << "size=" << size << " alignment=" << alignment;
alignment = alignment == alignof(std::max_align_t) ? 1 : alignment * 2;
size = (size + 1) % MAX_ALLOCATION_SIZE;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10a4c5a2/be/src/runtime/mem-pool.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.h b/be/src/runtime/mem-pool.h
index b0fa694..234fc41 100644
--- a/be/src/runtime/mem-pool.h
+++ b/be/src/runtime/mem-pool.h
@@ -187,9 +187,10 @@ class MemPool {
allocated_bytes(0) {}
};
- /// A static field used as non-NULL pointer for zero length allocations.
- /// NULL is reserved for allocation failures.
- static uint32_t zero_length_region_;
+ /// A static field used as non-NULL pointer for zero length allocations. NULL is
+ /// reserved for allocation failures. It must be as aligned as max_align_t for
+ /// TryAllocateAligned().
+ static uint32_t zero_length_region_ alignas(std::max_align_t);
/// chunk from which we served the last Allocate() call;
/// always points to the last chunk that contains allocated data;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10a4c5a2/bin/run-backend-tests.sh
----------------------------------------------------------------------
diff --git a/bin/run-backend-tests.sh b/bin/run-backend-tests.sh
index d12950b..758c1bc 100755
--- a/bin/run-backend-tests.sh
+++ b/bin/run-backend-tests.sh
@@ -35,4 +35,5 @@ fi
cd ${IMPALA_BE_DIR}
. ${IMPALA_HOME}/bin/set-classpath.sh
+export CTEST_OUTPUT_ON_FAILURE=1
make test ARGS="${BE_TEST_ARGS}"
[21/50] [abbrv] incubator-impala git commit: IMPALA-4438: Serialize
test_failpoints.py to reduce memory pressure
Posted by ta...@apache.org.
IMPALA-4438: Serialize test_failpoints.py to reduce memory pressure
On EC2 c3.4xlarge instances, with 8cores and 30GB RAM, this test could
trigger the Linux OOM killer by running tests in parallel. This patch
switches to serial execution, which makes the test take four minutes,
rather than one to two minutes.
Change-Id: Iea4a588e1228d38f90387a077cbe530257636b7d
Reviewed-on: http://gerrit.cloudera.org:8080/4999
Reviewed-by: Jim Apple <jb...@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/4af2ea4f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/4af2ea4f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/4af2ea4f
Branch: refs/heads/hadoop-next
Commit: 4af2ea4fe4e90588b13c4b551d0138123a743650
Parents: ae24bf2
Author: Jim Apple <jb...@cloudera.com>
Authored: Mon Nov 7 20:21:27 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 01:06:33 2016 +0000
----------------------------------------------------------------------
tests/failure/test_failpoints.py | 4 ++++
1 file changed, 4 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/4af2ea4f/tests/failure/test_failpoints.py
----------------------------------------------------------------------
diff --git a/tests/failure/test_failpoints.py b/tests/failure/test_failpoints.py
index 512d6f7..49a4699 100644
--- a/tests/failure/test_failpoints.py
+++ b/tests/failure/test_failpoints.py
@@ -18,6 +18,7 @@
# Injects failures at specific locations in each of the plan nodes. Currently supports
# two types of failures - cancellation of the query and a failure test hook.
#
+import pytest
import os
import re
from collections import defaultdict
@@ -114,6 +115,9 @@ class TestFailpoints(ImpalaTestSuite):
lambda v: (v.get_value('location') != 'PREPARE_SCANNER' or
v.get_value('target_node')[0] == 'SCAN HDFS'))
+ # Run serially because this can create enough memory pressure to invoke the Linux OOM
+ # killer on machines with 30GB RAM. This makes the test run in 4 minutes instead of 1-2.
+ @pytest.mark.execute_serially
def test_failpoints(self, vector):
query = QUERY
node_type, node_ids = vector.get_value('target_node')
[14/50] [abbrv] incubator-impala git commit: IMPALA-4302,
IMPALA-2379: constant expr arg fixes
Posted by ta...@apache.org.
IMPALA-4302,IMPALA-2379: constant expr arg fixes
This patch fixes two issues around handling of constant expr args.
The patches are combined because they touch some of the same code
and depend on some of the same memory management cleanup.
First, it fixes IMPALA-2379, where constant expr args were not visible
to UDAFs. The issue is that the input exprs need to be opened before
calling the UDAF Init() function.
Second, it avoids overhead from repeated evaluation of constant
arguments for ScalarFnCall expressions on both the codegen'd and
interpreted paths. A common example is an IN predicate with a
long list of constant values.
The interpreted path was inefficient because it always evaluated all
children expressions. Instead in this patch constant args are
evaluated once and cached. The memory management of the AnyVal*
objects was somewhat nebulous - adjusted it so that they're allocated
from ExprContext::mem_pool_, which has the correct lifetime.
The codegen'd path was inefficient only with varargs - with fixed
arguments the LLVM optimiser is able to infer after inlining that
the expressions are constant and remove all evaluation. However,
for varargs it stores the vararg values into a heap-allocated buffer.
The LLVM optimiser is unable to remove these stores because they
have a side-effect that is visible to code outside the function.
The codegen'd path is improved by evaluating varargs into an automatic
buffer that can be optimised out. We also make a small related change
to bake the string constants into the codegen'd code.
Testing:
Ran exhaustive build.
Added regression test for IMPALA-2379 and MemPool test for aligned
allocation. Added a test for in predicates with constant strings.
Perf:
Added a targeted query that demonstrates the improvement. Also manually
validated the non-codegend perf. Also ran TPC-H and targeted perf
queries locally - didn't see any significant changes.
+--------------------+-------------------------------+-----------------------+--------+-------------+------------+-----------+----------------+-------------+-------+
| Workload | Query | File Format | Avg(s) | Base Avg(s) | Delta(Avg) | StdDev(%) | Base StdDev(%) | Num Clients | Iters |
+--------------------+-------------------------------+-----------------------+--------+-------------+------------+-----------+----------------+-------------+-------+
| TARGETED-PERF(_20) | primitive_filter_in_predicate | parquet / none / none | 1.19 | 9.82 | I -87.85% | 3.82% | 0.71% | 1 | 10 |
+--------------------+-------------------------------+-----------------------+--------+-------------+------------+-----------+----------------+-------------+-------+
(I) Improvement: TARGETED-PERF(_20) primitive_filter_in_predicate [parquet / none / none] (9.82s -> 1.19s [-87.85%])
+--------------+------------+----------+----------+------------+-----------+----------+----------+------------+--------+--------+-----------+
| Operator | % of Query | Avg | Base Avg | Delta(Avg) | StdDev(%) | Max | Base Max | Delta(Max) | #Hosts | #Rows | Est #Rows |
+--------------+------------+----------+----------+------------+-----------+----------+----------+------------+--------+--------+-----------+
| 01:AGGREGATE | 14.39% | 155.88ms | 214.61ms | -27.37% | 2.68% | 163.38ms | 227.53ms | -28.19% | 1 | 1 | 1 |
| 00:SCAN HDFS | 85.60% | 927.46ms | 9.43s | -90.16% | 4.49% | 1.01s | 9.50s | -89.42% | 1 | 13.77K | 14.05K |
+--------------+------------+----------+----------+------------+-----------+----------+----------+------------+--------+--------+-----------+
Change-Id: I45c3ed8c9d7a61e94a9b9d6c316e8a53d9ff6c24
Reviewed-on: http://gerrit.cloudera.org:8080/4838
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/10fa472f
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/10fa472f
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/10fa472f
Branch: refs/heads/hadoop-next
Commit: 10fa472fa6aa036be02748ae54daed1722449c68
Parents: e3483c4
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Wed Oct 26 10:55:23 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 02:44:51 2016 +0000
----------------------------------------------------------------------
be/src/benchmarks/in-predicate-benchmark.cc | 5 +-
be/src/codegen/gen_ir_descriptions.py | 4 +-
be/src/codegen/llvm-codegen.cc | 31 ++-
be/src/codegen/llvm-codegen.h | 14 +-
be/src/exec/partitioned-aggregation-node.cc | 28 +--
be/src/exprs/agg-fn-evaluator.cc | 29 ++-
be/src/exprs/aggregate-functions-ir.cc | 6 +-
be/src/exprs/anyval-util.cc | 38 ++--
be/src/exprs/anyval-util.h | 22 +-
be/src/exprs/case-expr.cc | 15 +-
be/src/exprs/expr-context.h | 11 +-
be/src/exprs/expr.cc | 89 ++++----
be/src/exprs/expr.h | 20 +-
be/src/exprs/hive-udf-call.cc | 18 +-
be/src/exprs/in-predicate.h | 35 ++-
be/src/exprs/literal.cc | 5 +-
be/src/exprs/scalar-fn-call.cc | 222 ++++++++++---------
be/src/exprs/scalar-fn-call.h | 24 +-
be/src/exprs/utility-functions-ir.cc | 1 +
be/src/runtime/free-pool-test.cc | 38 ++--
be/src/runtime/free-pool.h | 7 +-
be/src/runtime/mem-pool-test.cc | 37 +++-
be/src/runtime/mem-pool.cc | 6 +-
be/src/runtime/mem-pool.h | 61 +++--
be/src/testutil/test-udas.cc | 13 ++
be/src/udf/udf-internal.h | 63 ++++--
be/src/udf/udf-test-harness.cc | 2 +-
be/src/udf/udf.cc | 26 ++-
be/src/udf/udf.h | 15 +-
be/src/util/bit-util.h | 2 +-
.../queries/QueryTest/exprs.test | 29 +++
.../functional-query/queries/QueryTest/uda.test | 7 +
.../queries/primitive_filter_in_predicate.test | 10 +
tests/query_test/test_udfs.py | 5 +
34 files changed, 578 insertions(+), 360 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/benchmarks/in-predicate-benchmark.cc
----------------------------------------------------------------------
diff --git a/be/src/benchmarks/in-predicate-benchmark.cc b/be/src/benchmarks/in-predicate-benchmark.cc
index 1a95f7a..6547b93 100644
--- a/be/src/benchmarks/in-predicate-benchmark.cc
+++ b/be/src/benchmarks/in-predicate-benchmark.cc
@@ -173,6 +173,7 @@
using namespace impala;
using namespace impala_udf;
using namespace strings;
+using std::move;
namespace impala {
@@ -223,8 +224,8 @@ class InPredicateBenchmark {
vector<AnyVal*> constant_args;
constant_args.push_back(NULL);
- for (AnyVal* p: data.anyval_ptrs) constant_args.push_back(p);
- UdfTestHarness::SetConstantArgs(ctx, constant_args);
+ for (AnyVal* p : data.anyval_ptrs) constant_args.push_back(p);
+ UdfTestHarness::SetConstantArgs(ctx, move(constant_args));
InPredicate::SetLookupPrepare<T, SetType>(ctx, FunctionContext::FRAGMENT_LOCAL);
data.state = *reinterpret_cast<InPredicate::SetLookupState<SetType>*>(
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/codegen/gen_ir_descriptions.py
----------------------------------------------------------------------
diff --git a/be/src/codegen/gen_ir_descriptions.py b/be/src/codegen/gen_ir_descriptions.py
index 2b08509..ddcd1db 100755
--- a/be/src/codegen/gen_ir_descriptions.py
+++ b/be/src/codegen/gen_ir_descriptions.py
@@ -200,9 +200,9 @@ ir_functions = [
["TOPN_NODE_INSERT_BATCH",
"_ZN6impala8TopNNode11InsertBatchEPNS_8RowBatchE"],
["MEMPOOL_ALLOCATE",
- "_ZN6impala7MemPool8AllocateILb0EEEPhl"],
+ "_ZN6impala7MemPool8AllocateILb0EEEPhli"],
["MEMPOOL_CHECKED_ALLOCATE",
- "_ZN6impala7MemPool8AllocateILb1EEEPhl"]
+ "_ZN6impala7MemPool8AllocateILb1EEEPhli"]
]
enums_preamble = '\
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/codegen/llvm-codegen.cc
----------------------------------------------------------------------
diff --git a/be/src/codegen/llvm-codegen.cc b/be/src/codegen/llvm-codegen.cc
index f6c2e89..f629d35 100644
--- a/be/src/codegen/llvm-codegen.cc
+++ b/be/src/codegen/llvm-codegen.cc
@@ -588,9 +588,19 @@ Value* LlvmCodeGen::GetIntConstant(int num_bytes, uint64_t low_bits, uint64_t hi
return ConstantInt::get(context(), APInt(8 * num_bytes, vals));
}
+Value* LlvmCodeGen::GetStringConstant(LlvmBuilder* builder, char* data, int len) {
+ // Create a global string with private linkage.
+ Constant* const_string =
+ ConstantDataArray::getString(context(), StringRef(data, len), false);
+ GlobalVariable* gv = new GlobalVariable(
+ *module_, const_string->getType(), true, GlobalValue::PrivateLinkage, const_string);
+ // Get a pointer to the first element of the string.
+ return builder->CreateConstInBoundsGEP2_32(NULL, gv, 0, 0, "");
+}
+
AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(Function* f, const NamedVariable& var) {
IRBuilder<> tmp(&f->getEntryBlock(), f->getEntryBlock().begin());
- AllocaInst* alloca = tmp.CreateAlloca(var.type, 0, var.name.c_str());
+ AllocaInst* alloca = tmp.CreateAlloca(var.type, NULL, var.name.c_str());
if (var.type == GetType(CodegenAnyVal::LLVM_DECIMALVAL_NAME)) {
// Generated functions may manipulate DecimalVal arguments via SIMD instructions such
// as 'movaps' that require 16-byte memory alignment. LLVM uses 8-byte alignment by
@@ -600,10 +610,20 @@ AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(Function* f, const NamedVariable
return alloca;
}
+AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(
+ const LlvmBuilder& builder, Type* type, const char* name) {
+ return CreateEntryBlockAlloca(
+ builder.GetInsertBlock()->getParent(), NamedVariable(name, type));
+}
+
AllocaInst* LlvmCodeGen::CreateEntryBlockAlloca(const LlvmBuilder& builder, Type* type,
- const char* name) {
- return CreateEntryBlockAlloca(builder.GetInsertBlock()->getParent(),
- NamedVariable(name, type));
+ int num_entries, int alignment, const char* name) {
+ Function* fn = builder.GetInsertBlock()->getParent();
+ IRBuilder<> tmp(&fn->getEntryBlock(), fn->getEntryBlock().begin());
+ AllocaInst* alloca =
+ tmp.CreateAlloca(type, GetIntConstant(TYPE_INT, num_entries), name);
+ alloca->setAlignment(alignment);
+ return alloca;
}
void LlvmCodeGen::CreateIfElseBlocks(Function* fn, const string& if_name,
@@ -1237,7 +1257,8 @@ Value* LlvmCodeGen::CodegenAllocate(LlvmBuilder* builder, MemPool* pool, Value*
Function* allocate_fn = GetFunction(IRFunction::MEMPOOL_ALLOCATE, false);
PointerType* pool_type = GetPtrType(MemPool::LLVM_CLASS_NAME);
Value* pool_val = CastPtrToLlvmPtr(pool_type, pool);
- Value* fn_args[] = { pool_val, size };
+ Value* alignment = GetIntConstant(TYPE_INT, MemPool::DEFAULT_ALIGNMENT);
+ Value* fn_args[] = {pool_val, size, alignment};
return builder->CreateCall(allocate_fn, fn_args, name);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/codegen/llvm-codegen.h
----------------------------------------------------------------------
diff --git a/be/src/codegen/llvm-codegen.h b/be/src/codegen/llvm-codegen.h
index 602dc5d..095f939 100644
--- a/be/src/codegen/llvm-codegen.h
+++ b/be/src/codegen/llvm-codegen.h
@@ -359,11 +359,16 @@ class LlvmCodeGen {
/// struct allocated. The allocated variable is scoped to the function.
//
/// This should always be used instead of calling LlvmBuilder::CreateAlloca directly.
- /// LLVM doesn't optimize alloca's occuring in the middle of functions very well (e.g, an
- /// alloca may end up in a loop, potentially blowing the stack).
+ /// LLVM doesn't optimize alloca's occurring in the middle of functions very well (e.g,
+ /// an alloca may end up in a loop, potentially blowing the stack).
llvm::AllocaInst* CreateEntryBlockAlloca(llvm::Function* f, const NamedVariable& var);
+ llvm::AllocaInst* CreateEntryBlockAlloca(
+ const LlvmBuilder& builder, llvm::Type* type, const char* name = "");
+
+ /// Same as above, except allocates an array of 'type' with 'num_entries' entries
+ /// and alignment 'alignment'.
llvm::AllocaInst* CreateEntryBlockAlloca(const LlvmBuilder& builder, llvm::Type* type,
- const char* name = "");
+ int num_entries, int alignment, const char* name = "");
/// Utility to create two blocks in 'fn' for if/else codegen. if_block and else_block
/// are return parameters. insert_before is optional and if set, the two blocks
@@ -388,6 +393,9 @@ class LlvmCodeGen {
/// can generate constant up to 128-bit wide. 'byte_size' must be power of 2.
llvm::Value* GetIntConstant(int byte_size, uint64_t low_bits, uint64_t high_bits);
+ /// Initialise a constant global string and returns an i8* pointer to it.
+ llvm::Value* GetStringConstant(LlvmBuilder* builder, char* data, int len);
+
/// Returns true/false constants (bool type)
llvm::Value* true_value() { return true_value_; }
llvm::Value* false_value() { return false_value_; }
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exec/partitioned-aggregation-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/partitioned-aggregation-node.cc b/be/src/exec/partitioned-aggregation-node.cc
index 6e587a5..17fbb6c 100644
--- a/be/src/exec/partitioned-aggregation-node.cc
+++ b/be/src/exec/partitioned-aggregation-node.cc
@@ -253,14 +253,7 @@ Status PartitionedAggregationNode::Prepare(RuntimeState* state) {
needs_serialize_ |= aggregate_evaluators_[i]->SupportsSerialize();
}
- if (grouping_expr_ctxs_.empty()) {
- // Create single output tuple; we need to output something even if our input is empty.
- singleton_output_tuple_ =
- ConstructSingletonOutputTuple(agg_fn_ctxs_, mem_pool_.get());
- // Check for failures during AggFnEvaluator::Init().
- RETURN_IF_ERROR(state_->GetQueryStatus());
- singleton_output_tuple_returned_ = false;
- } else {
+ if (!grouping_expr_ctxs_.empty()) {
RETURN_IF_ERROR(HashTableCtx::Create(state, build_expr_ctxs_, grouping_expr_ctxs_,
true, vector<bool>(build_expr_ctxs_.size(), true), state->fragment_hash_seed(),
MAX_PARTITION_DEPTH, 1, mem_tracker(), &ht_ctx_));
@@ -314,6 +307,16 @@ Status PartitionedAggregationNode::Open(RuntimeState* state) {
RETURN_IF_ERROR(aggregate_evaluators_[i]->Open(state, agg_fn_ctxs_[i]));
}
+ if (grouping_expr_ctxs_.empty()) {
+ // Create the single output tuple for this non-grouping agg. This must happen after
+ // opening the aggregate evaluators.
+ singleton_output_tuple_ =
+ ConstructSingletonOutputTuple(agg_fn_ctxs_, mem_pool_.get());
+ // Check for failures during AggFnEvaluator::Init().
+ RETURN_IF_ERROR(state_->GetQueryStatus());
+ singleton_output_tuple_returned_ = false;
+ }
+
RETURN_IF_ERROR(children_[0]->Open(state));
// Streaming preaggregations do all processing in GetNext().
@@ -673,14 +676,7 @@ void PartitionedAggregationNode::CleanupHashTbl(
Status PartitionedAggregationNode::Reset(RuntimeState* state) {
DCHECK(!is_streaming_preagg_) << "Cannot reset preaggregation";
- if (grouping_expr_ctxs_.empty()) {
- // Re-create the single output tuple for this non-grouping agg.
- singleton_output_tuple_ =
- ConstructSingletonOutputTuple(agg_fn_ctxs_, mem_pool_.get());
- // Check for failures during AggFnEvaluator::Init().
- RETURN_IF_ERROR(state_->GetQueryStatus());
- singleton_output_tuple_returned_ = false;
- } else {
+ if (!grouping_expr_ctxs_.empty()) {
child_eos_ = false;
partition_eos_ = false;
// Reset the HT and the partitions for this grouping agg.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/agg-fn-evaluator.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/agg-fn-evaluator.cc b/be/src/exprs/agg-fn-evaluator.cc
index ade7c10..4c6a993 100644
--- a/be/src/exprs/agg-fn-evaluator.cc
+++ b/be/src/exprs/agg-fn-evaluator.cc
@@ -39,6 +39,7 @@
using namespace impala;
using namespace impala_udf;
using namespace llvm;
+using std::move;
// typedef for builtin aggregate functions. Unfortunately, these type defs don't
// really work since the actual builtin is implemented not in terms of the base
@@ -144,13 +145,19 @@ Status AggFnEvaluator::Prepare(RuntimeState* state, const RowDescriptor& desc,
RETURN_IF_ERROR(
Expr::Prepare(input_expr_ctxs_, state, desc, agg_fn_pool->mem_tracker()));
- ObjectPool* obj_pool = state->obj_pool();
for (int i = 0; i < input_expr_ctxs_.size(); ++i) {
- staging_input_vals_.push_back(
- CreateAnyVal(obj_pool, input_expr_ctxs_[i]->root()->type()));
+ AnyVal* staging_input_val;
+ RETURN_IF_ERROR(
+ AllocateAnyVal(state, agg_fn_pool, input_expr_ctxs_[i]->root()->type(),
+ "Could not allocate aggregate expression input value", &staging_input_val));
+ staging_input_vals_.push_back(staging_input_val);
}
- staging_intermediate_val_ = CreateAnyVal(obj_pool, intermediate_type());
- staging_merge_input_val_ = CreateAnyVal(obj_pool, intermediate_type());
+ RETURN_IF_ERROR(AllocateAnyVal(state, agg_fn_pool, intermediate_type(),
+ "Could not allocate aggregate expression intermediate value",
+ &staging_intermediate_val_));
+ RETURN_IF_ERROR(AllocateAnyVal(state, agg_fn_pool, intermediate_type(),
+ "Could not allocate aggregate expression merge input value",
+ &staging_merge_input_val_));
if (is_merge_) {
DCHECK_EQ(staging_input_vals_.size(), 1) << "Merge should only have 1 input.";
@@ -223,9 +230,12 @@ Status AggFnEvaluator::Open(RuntimeState* state, FunctionContext* agg_fn_ctx) {
// on them).
vector<AnyVal*> constant_args(input_expr_ctxs_.size());
for (int i = 0; i < input_expr_ctxs_.size(); ++i) {
- constant_args[i] = input_expr_ctxs_[i]->root()->GetConstVal(input_expr_ctxs_[i]);
+ ExprContext* input_ctx = input_expr_ctxs_[i];
+ AnyVal* const_val;
+ RETURN_IF_ERROR(input_ctx->root()->GetConstVal(state, input_ctx, &const_val));
+ constant_args[i] = const_val;
}
- agg_fn_ctx->impl()->SetConstantArgs(constant_args);
+ agg_fn_ctx->impl()->SetConstantArgs(move(constant_args));
return Status::OK();
}
@@ -301,8 +311,7 @@ inline void AggFnEvaluator::SetDstSlot(FunctionContext* ctx, const AnyVal* src,
// This code seems to trip up clang causing it to generate code that crashes.
// Be careful when modifying this. See IMPALA-959 for more details.
// I suspect an issue with xmm registers not reading from aligned memory.
- memcpy(slot, &reinterpret_cast<const DecimalVal*>(src)->val4,
- dst_slot_desc->type().GetByteSize());
+ memcpy(slot, &reinterpret_cast<const DecimalVal*>(src)->val16, 16);
#else
DCHECK(false) << "Not implemented.";
#endif
@@ -318,6 +327,8 @@ inline void AggFnEvaluator::SetDstSlot(FunctionContext* ctx, const AnyVal* src,
// This function would be replaced in codegen.
void AggFnEvaluator::Init(FunctionContext* agg_fn_ctx, Tuple* dst) {
DCHECK(init_fn_ != NULL);
+ for (ExprContext* ctx : input_expr_ctxs_) DCHECK(ctx->opened());
+
if (intermediate_type().type == TYPE_CHAR) {
// For type char, we want to initialize the staging_intermediate_val_ with
// a pointer into the tuple (the UDA should not be allocating it).
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/aggregate-functions-ir.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/aggregate-functions-ir.cc b/be/src/exprs/aggregate-functions-ir.cc
index fe19829..c07d1db 100644
--- a/be/src/exprs/aggregate-functions-ir.cc
+++ b/be/src/exprs/aggregate-functions-ir.cc
@@ -186,7 +186,7 @@ void AggregateFunctions::InitZero(FunctionContext*, T* dst) {
template<>
void AggregateFunctions::InitZero(FunctionContext*, DecimalVal* dst) {
dst->is_null = false;
- dst->val16 = 0;
+ dst->val16 = 0; // Also initializes val4 and val8 to 0.
}
template <typename T>
@@ -1026,6 +1026,8 @@ bool SampleValLess(const ReservoirSample<StringVal>& i,
template <>
bool SampleValLess(const ReservoirSample<DecimalVal>& i,
const ReservoirSample<DecimalVal>& j) {
+ // Also handles val4 and val8 - the DecimalVal memory layout ensures the least
+ // significant bits overlap in memory.
return i.val.val16 < j.val.val16;
}
@@ -1091,6 +1093,8 @@ void PrintSample(const ReservoirSample<StringVal>& v, ostream* os) {
template <>
void PrintSample(const ReservoirSample<DecimalVal>& v, ostream* os) {
+ // Also handles val4 and val8 - the DecimalVal memory layout ensures the least
+ // significant bits overlap in memory.
*os << v.val.val16;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/anyval-util.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/anyval-util.cc b/be/src/exprs/anyval-util.cc
index 1e3d409..e4d9337 100644
--- a/be/src/exprs/anyval-util.cc
+++ b/be/src/exprs/anyval-util.cc
@@ -19,6 +19,9 @@
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
+#include "gutil/strings/substitute.h"
+#include "runtime/mem-pool.h"
+#include "runtime/mem-tracker.h"
#include "common/names.h"
@@ -26,30 +29,19 @@ using namespace impala_udf;
namespace impala {
-AnyVal* CreateAnyVal(ObjectPool* pool, const ColumnType& type) {
- return pool->Add(CreateAnyVal(type));
-}
-
-AnyVal* CreateAnyVal(const ColumnType& type) {
- switch(type.type) {
- case TYPE_NULL: return new AnyVal;
- case TYPE_BOOLEAN: return new BooleanVal;
- case TYPE_TINYINT: return new TinyIntVal;
- case TYPE_SMALLINT: return new SmallIntVal;
- case TYPE_INT: return new IntVal;
- case TYPE_BIGINT: return new BigIntVal;
- case TYPE_FLOAT: return new FloatVal;
- case TYPE_DOUBLE: return new DoubleVal;
- case TYPE_STRING:
- case TYPE_VARCHAR:
- case TYPE_CHAR:
- return new StringVal;
- case TYPE_TIMESTAMP: return new TimestampVal;
- case TYPE_DECIMAL: return new DecimalVal;
- default:
- DCHECK(false) << "Unsupported type: " << type;
- return NULL;
+Status AllocateAnyVal(RuntimeState* state, MemPool* pool, const ColumnType& type,
+ const std::string& mem_limit_exceeded_msg, AnyVal** result) {
+ int anyval_size = AnyValUtil::AnyValSize(type);
+ // Ensure the allocation is sufficiently aligned (e.g. DecimalVal has a 16-byte
+ // alignment requirement).
+ int alignment = BitUtil::RoundUpToPowerOfTwo(anyval_size);
+ *result = reinterpret_cast<AnyVal*>(pool->TryAllocateAligned(anyval_size, alignment));
+ if (*result == NULL) {
+ return pool->mem_tracker()->MemLimitExceeded(
+ state, mem_limit_exceeded_msg, anyval_size);
}
+ memset(*result, 0, anyval_size);
+ return Status::OK();
}
FunctionContext::TypeDesc AnyValUtil::ColumnTypeToTypeDesc(const ColumnType& type) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/anyval-util.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/anyval-util.h b/be/src/exprs/anyval-util.h
index 624c79e..b84187a 100644
--- a/be/src/exprs/anyval-util.h
+++ b/be/src/exprs/anyval-util.h
@@ -15,7 +15,6 @@
// specific language governing permissions and limitations
// under the License.
-
#ifndef IMPALA_EXPRS_ANYVAL_UTIL_H
#define IMPALA_EXPRS_ANYVAL_UTIL_H
@@ -271,7 +270,7 @@ class AnyValUtil {
return;
#if __BYTE_ORDER == __LITTLE_ENDIAN
case 16:
- memcpy(&reinterpret_cast<DecimalVal*>(dst)->val4, slot, type.GetByteSize());
+ memcpy(&reinterpret_cast<DecimalVal*>(dst)->val16, slot, 16);
#else
DCHECK(false) << "Not implemented.";
#endif
@@ -286,19 +285,20 @@ class AnyValUtil {
private:
/// Implementations of Equals().
- template<typename T>
+ template <typename T>
static inline bool EqualsInternal(const T& x, const T& y);
- static inline bool DecimalEquals(int precision, const DecimalVal& x,
- const DecimalVal& y);
+ static inline bool DecimalEquals(
+ int precision, const DecimalVal& x, const DecimalVal& y);
};
-/// Creates the corresponding AnyVal subclass for type. The object is added to the pool.
-impala_udf::AnyVal* CreateAnyVal(ObjectPool* pool, const ColumnType& type);
-
-/// Creates the corresponding AnyVal subclass for type. The object is owned by the caller.
-impala_udf::AnyVal* CreateAnyVal(const ColumnType& type);
+/// Allocates an AnyVal subclass of 'type' from 'pool'. The AnyVal's memory is
+/// initialized to all 0's. Returns a MemLimitExceeded() error with message
+/// 'mem_limit_exceeded_msg' if the allocation cannot be made because of a memory
+/// limit.
+Status AllocateAnyVal(RuntimeState* state, MemPool* pool, const ColumnType& type,
+ const std::string& mem_limit_exceeded_msg, AnyVal** result);
-template<typename T>
+template <typename T>
inline bool AnyValUtil::EqualsInternal(const T& x, const T& y) {
DCHECK(!x.is_null);
DCHECK(!y.is_null);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/case-expr.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/case-expr.cc b/be/src/exprs/case-expr.cc
index 2262c22..f139d64 100644
--- a/be/src/exprs/case-expr.cc
+++ b/be/src/exprs/case-expr.cc
@@ -63,13 +63,14 @@ Status CaseExpr::Open(RuntimeState* state, ExprContext* ctx,
return fn_ctx->impl()->state()->GetQueryStatus();
}
fn_ctx->SetFunctionState(FunctionContext::THREAD_LOCAL, case_state);
- if (has_case_expr_) {
- case_state->case_val = CreateAnyVal(state->obj_pool(), children_[0]->type());
- case_state->when_val = CreateAnyVal(state->obj_pool(), children_[1]->type());
- } else {
- case_state->case_val = CreateAnyVal(state->obj_pool(), TYPE_BOOLEAN);
- case_state->when_val = CreateAnyVal(state->obj_pool(), children_[0]->type());
- }
+
+ const ColumnType& case_val_type = has_case_expr_ ? children_[0]->type() : TYPE_BOOLEAN;
+ RETURN_IF_ERROR(AllocateAnyVal(state, ctx->pool_.get(), case_val_type,
+ "Could not allocate expression value", &case_state->case_val));
+ const ColumnType& when_val_type =
+ has_case_expr_ ? children_[1]->type() : children_[0]->type();
+ RETURN_IF_ERROR(AllocateAnyVal(state, ctx->pool_.get(), when_val_type,
+ "Could not allocate expression value", &case_state->when_val));
return Status::OK();
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/expr-context.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr-context.h b/be/src/exprs/expr-context.h
index 09de6a5..39abc5f 100644
--- a/be/src/exprs/expr-context.h
+++ b/be/src/exprs/expr-context.h
@@ -20,10 +20,11 @@
#include <boost/scoped_ptr.hpp>
+#include "common/object-pool.h"
#include "common/status.h"
#include "exprs/expr-value.h"
-#include "udf/udf.h"
#include "udf/udf-internal.h" // for CollectionVal
+#include "udf/udf.h"
using namespace impala_udf;
@@ -61,7 +62,9 @@ class ExprContext {
/// originals but have their own MemPool and thread-local state. Clone() should be used
/// to create an ExprContext for each execution thread that needs to evaluate
/// 'root'. Note that clones are already opened. '*new_context' must be initialized by
- /// the caller to NULL.
+ /// the caller to NULL. The cloned ExprContext cannot be used after the original
+ /// ExprContext is destroyed because it may reference fragment-local state from the
+ /// original.
Status Clone(RuntimeState* state, ExprContext** new_context);
/// Closes all FunctionContexts. Must be called on every ExprContext, including clones.
@@ -111,6 +114,7 @@ class ExprContext {
}
Expr* root() const { return root_; }
+ bool opened() const { return opened_; }
bool closed() const { return closed_; }
bool is_clone() const { return is_clone_; }
@@ -143,7 +147,8 @@ class ExprContext {
private:
friend class Expr;
- /// Users of private GetValue()
+ /// Users of private GetValue() or 'pool_'.
+ friend class CaseExpr;
friend class HiveUdfCall;
friend class ScalarFnCall;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/expr.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr.cc b/be/src/exprs/expr.cc
index 8d21830..0141bae 100644
--- a/be/src/exprs/expr.cc
+++ b/be/src/exprs/expr.cc
@@ -29,10 +29,8 @@
#include "codegen/llvm-codegen.h"
#include "common/object-pool.h"
#include "common/status.h"
-#include "exprs/anyval-util.h"
-#include "exprs/expr.h"
-#include "exprs/expr-context.h"
#include "exprs/aggregate-functions.h"
+#include "exprs/anyval-util.h"
#include "exprs/bit-byte-functions.h"
#include "exprs/case-expr.h"
#include "exprs/cast-functions.h"
@@ -40,6 +38,8 @@
#include "exprs/conditional-functions.h"
#include "exprs/decimal-functions.h"
#include "exprs/decimal-operators.h"
+#include "exprs/expr-context.h"
+#include "exprs/expr.h"
#include "exprs/hive-udf-call.h"
#include "exprs/in-predicate.h"
#include "exprs/is-not-empty-predicate.h"
@@ -56,15 +56,16 @@
#include "exprs/tuple-is-null-predicate.h"
#include "exprs/udf-builtins.h"
#include "exprs/utility-functions.h"
-#include "gen-cpp/Exprs_types.h"
#include "gen-cpp/Data_types.h"
+#include "gen-cpp/Exprs_types.h"
#include "runtime/lib-cache.h"
-#include "runtime/runtime-state.h"
+#include "runtime/mem-tracker.h"
#include "runtime/raw-value.h"
-#include "runtime/tuple.h"
+#include "runtime/runtime-state.h"
#include "runtime/tuple-row.h"
-#include "udf/udf.h"
+#include "runtime/tuple.h"
#include "udf/udf-internal.h"
+#include "udf/udf.h"
#include "gen-cpp/Exprs_types.h"
#include "gen-cpp/ImpalaService_types.h"
@@ -526,63 +527,69 @@ void Expr::InitBuiltinsDummy() {
UtilityFunctions::Pid(NULL);
}
-AnyVal* Expr::GetConstVal(ExprContext* context) {
+Status Expr::GetConstVal(RuntimeState* state, ExprContext* context, AnyVal** const_val) {
DCHECK(context->opened_);
- if (!IsConstant()) return NULL;
- if (constant_val_.get() != NULL) return constant_val_.get();
+ if (!IsConstant()) {
+ *const_val = NULL;
+ return Status::OK();
+ }
+ RETURN_IF_ERROR(AllocateAnyVal(state, context->pool_.get(), type_,
+ "Could not allocate constant expression value", const_val));
switch (type_.type) {
- case TYPE_BOOLEAN: {
- constant_val_.reset(new BooleanVal(GetBooleanVal(context, NULL)));
+ case TYPE_BOOLEAN:
+ *reinterpret_cast<BooleanVal*>(*const_val) = GetBooleanVal(context, NULL);
break;
- }
- case TYPE_TINYINT: {
- constant_val_.reset(new TinyIntVal(GetTinyIntVal(context, NULL)));
+ case TYPE_TINYINT:
+ *reinterpret_cast<TinyIntVal*>(*const_val) = GetTinyIntVal(context, NULL);
break;
- }
- case TYPE_SMALLINT: {
- constant_val_.reset(new SmallIntVal(GetSmallIntVal(context, NULL)));
+ case TYPE_SMALLINT:
+ *reinterpret_cast<SmallIntVal*>(*const_val) = GetSmallIntVal(context, NULL);
break;
- }
- case TYPE_INT: {
- constant_val_.reset(new IntVal(GetIntVal(context, NULL)));
+ case TYPE_INT:
+ *reinterpret_cast<IntVal*>(*const_val) = GetIntVal(context, NULL);
break;
- }
- case TYPE_BIGINT: {
- constant_val_.reset(new BigIntVal(GetBigIntVal(context, NULL)));
+ case TYPE_BIGINT:
+ *reinterpret_cast<BigIntVal*>(*const_val) = GetBigIntVal(context, NULL);
break;
- }
- case TYPE_FLOAT: {
- constant_val_.reset(new FloatVal(GetFloatVal(context, NULL)));
+ case TYPE_FLOAT:
+ *reinterpret_cast<FloatVal*>(*const_val) = GetFloatVal(context, NULL);
break;
- }
- case TYPE_DOUBLE: {
- constant_val_.reset(new DoubleVal(GetDoubleVal(context, NULL)));
+ case TYPE_DOUBLE:
+ *reinterpret_cast<DoubleVal*>(*const_val) = GetDoubleVal(context, NULL);
break;
- }
case TYPE_STRING:
case TYPE_CHAR:
case TYPE_VARCHAR: {
- constant_val_.reset(new StringVal(GetStringVal(context, NULL)));
+ StringVal* sv = reinterpret_cast<StringVal*>(*const_val);
+ *sv = GetStringVal(context, NULL);
+ if (sv->len > 0) {
+ // Make sure the memory is owned by 'context'.
+ uint8_t* ptr_copy = context->pool_->TryAllocate(sv->len);
+ if (ptr_copy == NULL) {
+ return context->pool_->mem_tracker()->MemLimitExceeded(
+ state, "Could not allocate constant string value", sv->len);
+ }
+ memcpy(ptr_copy, sv->ptr, sv->len);
+ sv->ptr = ptr_copy;
+ }
break;
}
- case TYPE_TIMESTAMP: {
- constant_val_.reset(new TimestampVal(GetTimestampVal(context, NULL)));
+ case TYPE_TIMESTAMP:
+ *reinterpret_cast<TimestampVal*>(*const_val) = GetTimestampVal(context, NULL);
break;
- }
- case TYPE_DECIMAL: {
- constant_val_.reset(new DecimalVal(GetDecimalVal(context, NULL)));
+ case TYPE_DECIMAL:
+ *reinterpret_cast<DecimalVal*>(*const_val) = GetDecimalVal(context, NULL);
break;
- }
default:
DCHECK(false) << "Type not implemented: " << type();
}
- DCHECK(constant_val_.get() != NULL);
- return constant_val_.get();
+ // Errors may have been set during the GetConstVal() call.
+ return GetFnContextError(context);
}
int Expr::GetConstantInt(const FunctionContext::TypeDesc& return_type,
- const std::vector<FunctionContext::TypeDesc>& arg_types, ExprConstant c, int i) {
+ const std::vector<FunctionContext::TypeDesc>& arg_types, ExprConstant c, int i) {
switch (c) {
case RETURN_TYPE_SIZE:
DCHECK_EQ(i, -1);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/expr.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr.h b/be/src/exprs/expr.h
index 99d463d..552fee9 100644
--- a/be/src/exprs/expr.h
+++ b/be/src/exprs/expr.h
@@ -88,16 +88,17 @@
#ifndef IMPALA_EXPRS_EXPR_H
#define IMPALA_EXPRS_EXPR_H
-#include <boost/scoped_ptr.hpp>
+#include <memory>
#include <string>
#include <vector>
+#include <boost/scoped_ptr.hpp>
#include "common/global-types.h"
#include "common/status.h"
#include "impala-ir/impala-ir-functions.h"
#include "runtime/types.h"
-#include "udf/udf.h"
#include "udf/udf-internal.h" // for CollectionVal
+#include "udf/udf.h"
using namespace impala_udf;
@@ -241,10 +242,13 @@ class Expr {
virtual Status GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn) = 0;
/// If this expr is constant, evaluates the expr with no input row argument and returns
- /// the output. Returns NULL if the argument is not constant. The returned AnyVal* is
- /// owned by this expr. This should only be called after Open() has been called on this
- /// expr.
- virtual AnyVal* GetConstVal(ExprContext* context);
+ /// the result in 'const_val'. Sets 'const_val' to NULL if the argument is not constant.
+ /// The returned AnyVal and associated varlen data is owned by 'context'. This should
+ /// only be called after Open() has been called on this expr. Returns an error if there
+ /// was an error evaluating the expression or if memory could not be allocated for the
+ /// expression result.
+ virtual Status GetConstVal(
+ RuntimeState* state, ExprContext* context, AnyVal** const_val);
virtual std::string DebugString() const;
static std::string DebugString(const std::vector<Expr*>& exprs);
@@ -370,10 +374,6 @@ class Expr {
/// Cached codegened compute function. Exprs should set this in GetCodegendComputeFn().
llvm::Function* ir_compute_fn_;
- /// If this expr is constant, this will store and cache the value generated by
- /// GetConstVal().
- boost::scoped_ptr<AnyVal> constant_val_;
-
/// Helper function that calls ctx->Register(), sets fn_context_index_, and returns the
/// registered FunctionContext.
FunctionContext* RegisterFunctionContext(
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/hive-udf-call.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/hive-udf-call.cc b/be/src/exprs/hive-udf-call.cc
index 453f876..7d82431 100644
--- a/be/src/exprs/hive-udf-call.cc
+++ b/be/src/exprs/hive-udf-call.cc
@@ -54,6 +54,8 @@ struct JniContext {
uint8_t output_null_value;
bool warning_logged;
+ /// AnyVal to evaluate the expression into. Only used as temporary storage during
+ /// expression evaluation.
AnyVal* output_anyval;
JniContext()
@@ -62,13 +64,10 @@ struct JniContext {
input_nulls_buffer(NULL),
output_value_buffer(NULL),
warning_logged(false),
- output_anyval(NULL) {
- }
+ output_anyval(NULL) {}
};
-HiveUdfCall::HiveUdfCall(const TExprNode& node)
- : Expr(node),
- input_buffer_size_(0) {
+HiveUdfCall::HiveUdfCall(const TExprNode& node) : Expr(node), input_buffer_size_(0) {
DCHECK_EQ(node.node_type, TExprNodeType::FUNCTION_CALL);
DCHECK_EQ(node.fn.binary_type, TFunctionBinaryType::JAVA);
DCHECK(executor_cl_ != NULL) << "Init() was not called!";
@@ -232,8 +231,8 @@ Status HiveUdfCall::Open(RuntimeState* state, ExprContext* ctx,
RETURN_ERROR_IF_EXC(env);
RETURN_IF_ERROR(JniUtil::LocalToGlobalRef(env, jni_ctx->executor, &jni_ctx->executor));
- jni_ctx->output_anyval = CreateAnyVal(type_);
-
+ RETURN_IF_ERROR(AllocateAnyVal(state, ctx->pool_.get(), type_,
+ "Could not allocate JNI output value", &jni_ctx->output_anyval));
return Status::OK();
}
@@ -264,10 +263,7 @@ void HiveUdfCall::Close(RuntimeState* state, ExprContext* ctx,
delete[] jni_ctx->output_value_buffer;
jni_ctx->output_value_buffer = NULL;
}
- if (jni_ctx->output_anyval != NULL) {
- delete jni_ctx->output_anyval;
- jni_ctx->output_anyval = NULL;
- }
+ jni_ctx->output_anyval = NULL;
delete jni_ctx;
} else {
DCHECK(!ctx->opened_);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/in-predicate.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/in-predicate.h b/be/src/exprs/in-predicate.h
index fd53a42..52d2015 100644
--- a/be/src/exprs/in-predicate.h
+++ b/be/src/exprs/in-predicate.h
@@ -28,33 +28,32 @@
namespace impala {
-/// Predicate for evaluating expressions of the form "val [NOT] IN (x1, x2, x3...)".
-//
+/// Utilities for evaluating expressions of the form "val [NOT] IN (x1, x2, x3...)".
+/// In predicates are implemented using ScalarFnCall and the UDF interface.
+///
/// There are two strategies for evaluating the IN predicate:
//
-/// 1) SET_LOOKUP: This strategy is for when all the values in the IN list are constant. In
-/// the prepare function, we create a set of the constant values from the IN list, and
-/// use this set to lookup a given 'val'.
+/// 1) SET_LOOKUP: This strategy is for when all the values in the IN list are constant.
+/// In the prepare function, we create a set of the constant values from the IN list,
+/// and use this set to lookup a given 'val'.
//
-/// 2) ITERATE: This is the fallback strategy for when their are non-constant IN list
+/// 2) ITERATE: This is the fallback strategy for when there are non-constant IN list
/// values, or very few values in the IN list. We simply iterate through every
/// expression and compare it to val. This strategy has no prepare function.
//
-/// The FE chooses which strategy we should use by choosing the appropriate function (e.g.,
-/// InIterate() or InSetLookup()). If it chooses SET_LOOKUP, it also sets the appropriate
-/// SetLookupPrepare and SetLookupClose functions.
-//
-/// TODO: the set lookup logic is not yet implemented for TimestampVals or DecimalVals
-class InPredicate : public Predicate {
+/// The FE chooses which strategy we should use by choosing the appropriate function
+/// (e.g., InIterate() or InSetLookup()). If it chooses SET_LOOKUP, it also sets the
+/// appropriate SetLookupPrepare and SetLookupClose functions.
+class InPredicate {
public:
/// Functions for every type
- static impala_udf::BooleanVal InIterate(
- impala_udf::FunctionContext* context, const impala_udf::BooleanVal& val,
- int num_args, const impala_udf::BooleanVal* args);
+ static impala_udf::BooleanVal InIterate(impala_udf::FunctionContext* context,
+ const impala_udf::BooleanVal& val, int num_args,
+ const impala_udf::BooleanVal* args);
- static impala_udf::BooleanVal NotInIterate(
- impala_udf::FunctionContext* context, const impala_udf::BooleanVal& val,
- int num_args, const impala_udf::BooleanVal* args);
+ static impala_udf::BooleanVal NotInIterate(impala_udf::FunctionContext* context,
+ const impala_udf::BooleanVal& val, int num_args,
+ const impala_udf::BooleanVal* args);
static void SetLookupPrepare_boolean(impala_udf::FunctionContext* ctx,
impala_udf::FunctionContext::FunctionStateScope scope);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/literal.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/literal.cc b/be/src/exprs/literal.cc
index caf6c14..03bdd50 100644
--- a/be/src/exprs/literal.cc
+++ b/be/src/exprs/literal.cc
@@ -21,9 +21,9 @@
#include "codegen/codegen-anyval.h"
#include "codegen/llvm-codegen.h"
+#include "gen-cpp/Exprs_types.h"
#include "runtime/decimal-value.inline.h"
#include "runtime/runtime-state.h"
-#include "gen-cpp/Exprs_types.h"
#include "common/names.h"
@@ -414,7 +414,8 @@ Status Literal::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
case TYPE_VARCHAR:
case TYPE_CHAR:
v.SetLen(builder.getInt32(value_.string_val.len));
- v.SetPtr(codegen->CastPtrToLlvmPtr(codegen->ptr_type(), value_.string_val.ptr));
+ v.SetPtr(codegen->GetStringConstant(
+ &builder, value_.string_val.ptr, value_.string_val.len));
break;
case TYPE_DECIMAL:
switch (type().GetByteSize()) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/scalar-fn-call.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/scalar-fn-call.cc b/be/src/exprs/scalar-fn-call.cc
index 17cbd64..3a7ffb1 100644
--- a/be/src/exprs/scalar-fn-call.cc
+++ b/be/src/exprs/scalar-fn-call.cc
@@ -45,14 +45,22 @@
using namespace impala;
using namespace impala_udf;
using namespace strings;
+using llvm::ArrayType;
+using llvm::BasicBlock;
+using llvm::Function;
+using llvm::GlobalVariable;
+using llvm::PointerType;
+using llvm::Type;
+using llvm::Value;
+using std::move;
+using std::pair;
// Maximum number of arguments the interpretation path supports.
#define MAX_INTERP_ARGS 20
ScalarFnCall::ScalarFnCall(const TExprNode& node)
: Expr(node),
- vararg_start_idx_(node.__isset.vararg_start_idx ?
- node.vararg_start_idx : -1),
+ vararg_start_idx_(node.__isset.vararg_start_idx ? node.vararg_start_idx : -1),
scalar_fn_wrapper_(NULL),
prepare_fn_(NULL),
close_fn_(NULL),
@@ -84,17 +92,8 @@ Status ScalarFnCall::Prepare(RuntimeState* state, const RowDescriptor& desc,
has_char_arg_or_result |= children_[i]->type_.type == TYPE_CHAR;
}
- // Compute buffer size for varargs
- int varargs_buffer_size = 0;
- if (vararg_start_idx_ != -1) {
- DCHECK_GT(GetNumChildren(), vararg_start_idx_);
- for (int i = vararg_start_idx_; i < GetNumChildren(); ++i) {
- varargs_buffer_size += AnyValUtil::AnyValSize(children_[i]->type());
- }
- }
-
- fn_context_index_ = context->Register(state, return_type, arg_types,
- varargs_buffer_size);
+ fn_context_index_ =
+ context->Register(state, return_type, arg_types, ComputeVarArgsBufferSize());
// Use the interpreted path and call the builtin without codegen if:
// 1. codegen is disabled or
@@ -149,7 +148,7 @@ Status ScalarFnCall::Prepare(RuntimeState* state, const RowDescriptor& desc,
RETURN_IF_ERROR(codegen->LinkModule(local_path));
}
- llvm::Function* ir_udf_wrapper;
+ Function* ir_udf_wrapper;
RETURN_IF_ERROR(GetCodegendComputeFn(codegen, &ir_udf_wrapper));
// TODO: don't do this for child exprs
codegen->AddFunctionToJit(ir_udf_wrapper, &scalar_fn_wrapper_);
@@ -177,23 +176,52 @@ Status ScalarFnCall::Open(RuntimeState* state, ExprContext* ctx,
// We're in the interpreted path (i.e. no JIT). Populate our FunctionContext's
// staging_input_vals, which will be reused across calls to scalar_fn_.
DCHECK(scalar_fn_wrapper_ == NULL);
- ObjectPool* obj_pool = state->obj_pool();
vector<AnyVal*>* input_vals = fn_ctx->impl()->staging_input_vals();
for (int i = 0; i < NumFixedArgs(); ++i) {
- input_vals->push_back(CreateAnyVal(obj_pool, children_[i]->type()));
+ AnyVal* input_val;
+ RETURN_IF_ERROR(AllocateAnyVal(state, ctx->pool_.get(), children_[i]->type(),
+ "Could not allocate expression value", &input_val));
+ input_vals->push_back(input_val);
}
}
- // Only evaluate constant arguments once per fragment
+ // Only evaluate constant arguments at the top level of function contexts.
+ // If 'ctx' was cloned, the constant values were copied from the parent.
if (scope == FunctionContext::FRAGMENT_LOCAL) {
vector<AnyVal*> constant_args;
for (int i = 0; i < children_.size(); ++i) {
- constant_args.push_back(children_[i]->GetConstVal(ctx));
- // Check if any errors were set during the GetConstVal() call
- Status child_status = children_[i]->GetFnContextError(ctx);
- if (!child_status.ok()) return child_status;
+ AnyVal* const_val;
+ RETURN_IF_ERROR(children_[i]->GetConstVal(state, ctx, &const_val));
+ constant_args.push_back(const_val);
+ }
+ fn_ctx->impl()->SetConstantArgs(move(constant_args));
+ }
+
+ if (scalar_fn_ != NULL) {
+ // Now we have the constant values, cache them so that the interpreted path can
+ // call the UDF without reevaluating the arguments. 'staging_input_vals' and
+ // 'varargs_buffer' in the FunctionContext are used to pass fixed and variable-length
+ // arguments respectively. 'non_constant_args()' in the FunctionContext will contain
+ // pointers to the remaining (non-constant) children that are evaluated for every row.
+ vector<pair<Expr*, AnyVal*>> non_constant_args;
+ uint8_t* varargs_buffer = fn_ctx->impl()->varargs_buffer();
+ for (int i = 0; i < children_.size(); ++i) {
+ AnyVal* input_arg;
+ int arg_bytes = AnyValUtil::AnyValSize(children_[i]->type());
+ if (i < NumFixedArgs()) {
+ input_arg = (*fn_ctx->impl()->staging_input_vals())[i];
+ } else {
+ input_arg = reinterpret_cast<AnyVal*>(varargs_buffer);
+ varargs_buffer += arg_bytes;
+ }
+ const AnyVal* constant_arg = fn_ctx->impl()->constant_args()[i];
+ if (constant_arg == NULL) {
+ non_constant_args.emplace_back(children_[i], input_arg);
+ } else {
+ memcpy(input_arg, constant_arg, arg_bytes);
+ }
}
- fn_ctx->impl()->SetConstantArgs(constant_args);
+ fn_ctx->impl()->SetNonConstantArgs(move(non_constant_args));
}
if (prepare_fn_ != NULL) {
@@ -264,7 +292,7 @@ bool ScalarFnCall::IsConstant() const {
// i32 4,
// i64* inttoptr (i64 89111072 to i64*))
// ret { i8, double } %result
-Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn) {
+Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, Function** fn) {
if (ir_compute_fn_ != NULL) {
*fn = ir_compute_fn_;
return Status::OK();
@@ -279,62 +307,56 @@ Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function**
}
}
- llvm::Function* udf;
+ Function* udf;
RETURN_IF_ERROR(GetUdf(codegen, &udf));
// Create wrapper that computes args and calls UDF
stringstream fn_name;
fn_name << udf->getName().str() << "Wrapper";
- llvm::Value* args[2];
+ Value* args[2];
*fn = CreateIrFunctionPrototype(codegen, fn_name.str(), &args);
- llvm::Value* expr_ctx = args[0];
- llvm::Value* row = args[1];
- llvm::BasicBlock* block = llvm::BasicBlock::Create(codegen->context(), "entry", *fn);
+ Value* expr_ctx = args[0];
+ Value* row = args[1];
+ BasicBlock* block = BasicBlock::Create(codegen->context(), "entry", *fn);
LlvmCodeGen::LlvmBuilder builder(block);
// Populate UDF arguments
- vector<llvm::Value*> udf_args;
+ vector<Value*> udf_args;
// First argument is always FunctionContext*.
// Index into our registered offset in the ExprContext.
- llvm::Value* expr_ctx_gep = builder.CreateStructGEP(NULL, expr_ctx, 1, "expr_ctx_gep");
- llvm::Value* fn_ctxs_base = builder.CreateLoad(expr_ctx_gep, "fn_ctxs_base");
+ Value* expr_ctx_gep = builder.CreateStructGEP(NULL, expr_ctx, 1, "expr_ctx_gep");
+ Value* fn_ctxs_base = builder.CreateLoad(expr_ctx_gep, "fn_ctxs_base");
// Use GEP to add our index to the base pointer
- llvm::Value* fn_ctx_ptr =
+ Value* fn_ctx_ptr =
builder.CreateConstGEP1_32(fn_ctxs_base, fn_context_index_, "fn_ctx_ptr");
- llvm::Value* fn_ctx = builder.CreateLoad(fn_ctx_ptr, "fn_ctx");
+ Value* fn_ctx = builder.CreateLoad(fn_ctx_ptr, "fn_ctx");
udf_args.push_back(fn_ctx);
- // Get IR i8* pointer to varargs buffer from FunctionContext* argument
- // (if there are varargs)
- llvm::Value* varargs_buffer = NULL;
+ // Allocate a varargs array. The array's entry type is the appropriate AnyVal subclass.
+ // E.g. if the vararg type is STRING, and the function is called with 10 arguments, we
+ // allocate a StringVal[10] array. We allocate the buffer with Alloca so that LLVM can
+ // optimise out the buffer once the function call is inlined.
+ Value* varargs_buffer = NULL;
if (vararg_start_idx_ != -1) {
- // FunctionContextImpl is first field of FunctionContext
- // fn_ctx_impl_ptr has type FunctionContextImpl**
- llvm::Value* fn_ctx_impl_ptr = builder.CreateStructGEP(NULL, fn_ctx, 0, "fn_ctx_impl_ptr");
- llvm::Value* fn_ctx_impl = builder.CreateLoad(fn_ctx_impl_ptr, "fn_ctx_impl");
- // varargs_buffer is first field of FunctionContextImpl
- // varargs_buffer_ptr has type i8**
- llvm::Value* varargs_buffer_ptr = builder.CreateStructGEP(NULL, fn_ctx_impl, 0,
- "varargs_buffer");
- varargs_buffer = builder.CreateLoad(varargs_buffer_ptr);
+ Type* unlowered_varargs_type =
+ CodegenAnyVal::GetUnloweredType(codegen, VarArgsType());
+ varargs_buffer = codegen->CreateEntryBlockAlloca(builder, unlowered_varargs_type,
+ NumVarArgs(), FunctionContextImpl::VARARGS_BUFFER_ALIGNMENT, "varargs_buffer");
}
- // Tracks where to write the next vararg to
- int varargs_buffer_offset = 0;
// Call children to populate remaining arguments
for (int i = 0; i < GetNumChildren(); ++i) {
- llvm::Function* child_fn = NULL;
- vector<llvm::Value*> child_fn_args;
+ Function* child_fn = NULL;
+ vector<Value*> child_fn_args;
// Set 'child_fn' to the codegen'd function, sets child_fn = NULL if codegen fails
children_[i]->GetCodegendComputeFn(codegen, &child_fn);
-
if (child_fn == NULL) {
// Set 'child_fn' to the interpreted function
child_fn = GetStaticGetValWrapper(children_[i]->type(), codegen);
// First argument to interpreted function is children_[i]
- llvm::Type* expr_ptr_type = codegen->GetPtrType(Expr::LLVM_CLASS_NAME);
+ Type* expr_ptr_type = codegen->GetPtrType(Expr::LLVM_CLASS_NAME);
child_fn_args.push_back(codegen->CastPtrToLlvmPtr(expr_ptr_type, children_[i]));
}
child_fn_args.push_back(expr_ctx);
@@ -342,33 +364,21 @@ Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function**
// Call 'child_fn', adding the result to either 'udf_args' or 'varargs_buffer'
DCHECK(child_fn != NULL);
- llvm::Type* arg_type = CodegenAnyVal::GetUnloweredType(codegen, children_[i]->type());
- llvm::Value* arg_val_ptr;
- if (vararg_start_idx_ == -1 || i < vararg_start_idx_) {
- // Either no varargs or arguments before varargs begin. Allocate space to store
- // 'child_fn's result so we can pass the pointer to the UDF.
+ Type* arg_type = CodegenAnyVal::GetUnloweredType(codegen, children_[i]->type());
+ Value* arg_val_ptr;
+ if (i < NumFixedArgs()) {
+ // Allocate space to store 'child_fn's result so we can pass the pointer to the UDF.
arg_val_ptr = codegen->CreateEntryBlockAlloca(builder, arg_type, "arg_val_ptr");
-
- if (children_[i]->type().type == TYPE_DECIMAL) {
- // UDFs may manipulate DecimalVal arguments via SIMD instructions such as 'movaps'
- // that require 16-byte memory alignment. LLVM uses 8-byte alignment by default,
- // so explicitly set the alignment for DecimalVals.
- llvm::cast<llvm::AllocaInst>(arg_val_ptr)->setAlignment(16);
- }
udf_args.push_back(arg_val_ptr);
- } else {
- // Store the result of 'child_fn' in varargs_buffer + varargs_buffer_offset
- arg_val_ptr =
- builder.CreateConstGEP1_32(varargs_buffer, varargs_buffer_offset, "arg_val_ptr");
- varargs_buffer_offset += AnyValUtil::AnyValSize(children_[i]->type());
- // Cast arg_val_ptr from i8* to AnyVal pointer type
+ } else {
+ // Store the result of 'child_fn' in varargs_buffer[i].
arg_val_ptr =
- builder.CreateBitCast(arg_val_ptr, arg_type->getPointerTo(), "arg_val_ptr");
+ builder.CreateConstGEP1_32(varargs_buffer, i - NumFixedArgs(), "arg_val_ptr");
}
DCHECK_EQ(arg_val_ptr->getType(), arg_type->getPointerTo());
// The result of the call must be stored in a lowered AnyVal
- llvm::Value* lowered_arg_val_ptr = builder.CreateBitCast(
- arg_val_ptr, CodegenAnyVal::GetLoweredPtrType(codegen, children_[i]->type()),
+ Value* lowered_arg_val_ptr = builder.CreateBitCast(arg_val_ptr,
+ CodegenAnyVal::GetLoweredPtrType(codegen, children_[i]->type()),
"lowered_arg_val_ptr");
CodegenAnyVal::CreateCall(
codegen, &builder, child_fn, child_fn_args, "arg_val", lowered_arg_val_ptr);
@@ -379,16 +389,15 @@ Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function**
DCHECK_EQ(udf_args.size(), vararg_start_idx_ + 1);
DCHECK_GE(GetNumChildren(), 1);
// Add the number of varargs
- udf_args.push_back(codegen->GetIntConstant(
- TYPE_INT, GetNumChildren() - vararg_start_idx_));
+ udf_args.push_back(codegen->GetIntConstant(TYPE_INT, NumVarArgs()));
// Add all the accumulated vararg inputs as one input argument.
- llvm::PointerType* vararg_type = codegen->GetPtrType(
- CodegenAnyVal::GetUnloweredType(codegen, children_.back()->type()));
+ PointerType* vararg_type =
+ codegen->GetPtrType(CodegenAnyVal::GetUnloweredType(codegen, VarArgsType()));
udf_args.push_back(builder.CreateBitCast(varargs_buffer, vararg_type, "varargs"));
}
// Call UDF
- llvm::Value* result_val =
+ Value* result_val =
CodegenAnyVal::CreateCall(codegen, &builder, udf, udf_args, "result");
builder.CreateRet(result_val);
@@ -401,7 +410,7 @@ Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function**
return Status::OK();
}
-Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, llvm::Function** udf) {
+Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, Function** udf) {
// from_utc_timestamp() and to_utc_timestamp() have inline ASM that cannot be JIT'd.
// TimestampFunctions::AddSub() contains a try/catch which doesn't work in JIT'd
// code. Always use the interpreted version of these functions.
@@ -428,16 +437,16 @@ Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, llvm::Function** udf) {
// Per the x64 ABI, DecimalVals are returned via a DecmialVal* output argument.
// So, the return type is void.
bool is_decimal = type().type == TYPE_DECIMAL;
- llvm::Type* return_type = is_decimal ? codegen->void_type() :
- CodegenAnyVal::GetLoweredType(codegen, type());
+ Type* return_type = is_decimal ? codegen->void_type() :
+ CodegenAnyVal::GetLoweredType(codegen, type());
- // Convert UDF function pointer to llvm::Function*. Start by creating a function
+ // Convert UDF function pointer to Function*. Start by creating a function
// prototype for it.
LlvmCodeGen::FnPrototype prototype(codegen, fn_.scalar_fn.symbol, return_type);
if (is_decimal) {
// Per the x64 ABI, DecimalVals are returned via a DecmialVal* output argument
- llvm::Type* output_type =
+ Type* output_type =
codegen->GetPtrType(CodegenAnyVal::GetUnloweredType(codegen, type()));
prototype.AddArgument("output", output_type);
}
@@ -450,19 +459,19 @@ Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, llvm::Function** udf) {
for (int i = 0; i < NumFixedArgs(); ++i) {
stringstream arg_name;
arg_name << "fixed_arg_" << i;
- llvm::Type* arg_type = codegen->GetPtrType(
+ Type* arg_type = codegen->GetPtrType(
CodegenAnyVal::GetUnloweredType(codegen, children_[i]->type()));
prototype.AddArgument(arg_name.str(), arg_type);
}
// The varargs for the UDF function if there is any.
- if (vararg_start_idx_ >= 0) {
- llvm::Type* vararg_type = CodegenAnyVal::GetUnloweredPtrType(
+ if (NumVarArgs() > 0) {
+ Type* vararg_type = CodegenAnyVal::GetUnloweredPtrType(
codegen, children_[vararg_start_idx_]->type());
prototype.AddArgument("num_var_arg", codegen->GetType(TYPE_INT));
prototype.AddArgument("var_arg", vararg_type);
}
- // Create a llvm::Function* with the generated type. This is only a function
+ // Create a Function* with the generated type. This is only a function
// declaration, not a definition, since we do not create any basic blocks or
// instructions in it.
*udf = prototype.GeneratePrototype(NULL, NULL, false);
@@ -518,11 +527,11 @@ Status ScalarFnCall::GetFunction(RuntimeState* state, const string& symbol, void
DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::IR);
LlvmCodeGen* codegen = state->codegen();
DCHECK(codegen != NULL);
- llvm::Function* ir_fn = codegen->GetFunction(symbol);
+ Function* ir_fn = codegen->GetFunction(symbol);
if (ir_fn == NULL) {
stringstream ss;
- ss << "Unable to locate function " << symbol
- << " from LLVM module " << fn_.hdfs_location;
+ ss << "Unable to locate function " << symbol << " from LLVM module "
+ << fn_.hdfs_location;
return Status(ss.str());
}
codegen->AddFunctionToJit(ir_fn, fn);
@@ -530,21 +539,12 @@ Status ScalarFnCall::GetFunction(RuntimeState* state, const string& symbol, void
}
}
-void ScalarFnCall::EvaluateChildren(ExprContext* context, const TupleRow* row,
- vector<AnyVal*>* input_vals) {
- DCHECK_EQ(input_vals->size(), NumFixedArgs());
+void ScalarFnCall::EvaluateNonConstantChildren(
+ ExprContext* context, const TupleRow* row) {
FunctionContext* fn_ctx = context->fn_context(fn_context_index_);
- uint8_t* varargs_buffer = fn_ctx->impl()->varargs_buffer();
- for (int i = 0; i < children_.size(); ++i) {
- void* src_slot = context->GetValue(children_[i], row);
- AnyVal* dst_val;
- if (vararg_start_idx_ == -1 || i < vararg_start_idx_) {
- dst_val = (*input_vals)[i];
- } else {
- dst_val = reinterpret_cast<AnyVal*>(varargs_buffer);
- varargs_buffer += AnyValUtil::AnyValSize(children_[i]->type());
- }
- AnyValUtil::SetAnyVal(src_slot, children_[i]->type(), dst_val);
+ for (pair<Expr*, AnyVal*> child : fn_ctx->impl()->non_constant_args()) {
+ void* val = context->GetValue(child.first, row);
+ AnyValUtil::SetAnyVal(val, child.first->type(), child.second);
}
}
@@ -553,14 +553,13 @@ RETURN_TYPE ScalarFnCall::InterpretEval(ExprContext* context, const TupleRow* ro
DCHECK(scalar_fn_ != NULL) << DebugString();
FunctionContext* fn_ctx = context->fn_context(fn_context_index_);
vector<AnyVal*>* input_vals = fn_ctx->impl()->staging_input_vals();
- EvaluateChildren(context, row, input_vals);
+ EvaluateNonConstantChildren(context, row);
if (vararg_start_idx_ == -1) {
switch (children_.size()) {
-
#define ARG_DECL_ONE(z, n, data) BOOST_PP_COMMA_IF(n) const AnyVal&
#define ARG_DECL_LIST(n) \
- FunctionContext* BOOST_PP_COMMA_IF(n) BOOST_PP_REPEAT(n, ARG_DECL_ONE, unused)
+ FunctionContext* BOOST_PP_COMMA_IF(n) BOOST_PP_REPEAT(n, ARG_DECL_ONE, unused)
#define ARG_ONE(z, n, data) BOOST_PP_COMMA_IF(n) *(*input_vals)[n]
#define ARG_LIST(n) fn_ctx BOOST_PP_COMMA_IF(n) BOOST_PP_REPEAT(n, ARG_ONE, unused)
@@ -706,8 +705,15 @@ DecimalVal ScalarFnCall::GetDecimalVal(ExprContext* context, const TupleRow* row
string ScalarFnCall::DebugString() const {
stringstream out;
- out << "ScalarFnCall(udf_type=" << fn_.binary_type
- << " location=" << fn_.hdfs_location
+ out << "ScalarFnCall(udf_type=" << fn_.binary_type << " location=" << fn_.hdfs_location
<< " symbol_name=" << fn_.scalar_fn.symbol << Expr::DebugString() << ")";
return out.str();
}
+
+int ScalarFnCall::ComputeVarArgsBufferSize() const {
+ for (int i = NumFixedArgs(); i < children_.size(); ++i) {
+ // All varargs should have same type.
+ DCHECK_EQ(children_[i]->type(), VarArgsType());
+ }
+ return NumVarArgs() == 0 ? 0 : NumVarArgs() * AnyValUtil::AnyValSize(VarArgsType());
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/scalar-fn-call.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/scalar-fn-call.h b/be/src/exprs/scalar-fn-call.h
index e48b9df..85191d5 100644
--- a/be/src/exprs/scalar-fn-call.h
+++ b/be/src/exprs/scalar-fn-call.h
@@ -83,6 +83,11 @@ class ScalarFnCall: public Expr {
/// If this function does not have varargs, it is set to -1.
int vararg_start_idx_;
+ /// Vector of all non-constant children expressions that need to be evaluated for
+ /// each input row. The first element of each pair is the child expression and the
+ /// second element in the value it must be evaluated into.
+ std::vector<std::pair<Expr*, impala_udf::AnyVal*>> non_constant_children_;
+
/// Function pointer to the JIT'd function produced by GetCodegendComputeFn().
/// Has signature *Val (ExprContext*, const TupleRow*), and calls the scalar
/// function with signature like *Val (FunctionContext*, const *Val& arg1, ...)
@@ -106,6 +111,13 @@ class ScalarFnCall: public Expr {
return vararg_start_idx_ >= 0 ? vararg_start_idx_ : children_.size();
}
+ int NumVarArgs() const { return children_.size() - NumFixedArgs(); }
+
+ const ColumnType& VarArgsType() const {
+ DCHECK_GE(NumVarArgs(), 1);
+ return children_.back()->type();
+ }
+
/// Loads the native or IR function from HDFS and puts the result in *udf.
Status GetUdf(LlvmCodeGen* codegen, llvm::Function** udf);
@@ -114,16 +126,16 @@ class ScalarFnCall: public Expr {
/// has been JIT'd (i.e. after Prepare() has completed).
Status GetFunction(RuntimeState* state, const std::string& symbol, void** fn);
- /// Evaluates the children exprs and stores the results in input_vals. Used in the
- /// interpreted path.
- void EvaluateChildren(ExprContext* context, const TupleRow* row,
- std::vector<impala_udf::AnyVal*>* input_vals);
+ /// Evaluates the non-constant children exprs. Used in the interpreted path.
+ void EvaluateNonConstantChildren(ExprContext* context, const TupleRow* row);
/// Function to call scalar_fn_. Used in the interpreted path.
- template<typename RETURN_TYPE>
+ template <typename RETURN_TYPE>
RETURN_TYPE InterpretEval(ExprContext* context, const TupleRow* row);
-};
+ /// Computes the size of the varargs buffer in bytes (0 bytes if no varargs).
+ int ComputeVarArgsBufferSize() const;
+};
}
#endif
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/exprs/utility-functions-ir.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/utility-functions-ir.cc b/be/src/exprs/utility-functions-ir.cc
index ba4a371..263c4d4 100644
--- a/be/src/exprs/utility-functions-ir.cc
+++ b/be/src/exprs/utility-functions-ir.cc
@@ -57,6 +57,7 @@ BigIntVal UtilityFunctions::FnvHashDecimal(FunctionContext* ctx,
if (input_val.is_null) return BigIntVal::null();
const FunctionContext::TypeDesc& input_type = *ctx->GetArgType(0);
int byte_size = ColumnType::GetDecimalByteSize(input_type.precision);
+ // val4, val8 and val16 all start at the same memory address.
return BigIntVal(HashUtil::FnvHash64(&input_val.val16, byte_size, HashUtil::FNV_SEED));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/runtime/free-pool-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/free-pool-test.cc b/be/src/runtime/free-pool-test.cc
index f4490f0..63153c9 100644
--- a/be/src/runtime/free-pool-test.cc
+++ b/be/src/runtime/free-pool-test.cc
@@ -64,44 +64,52 @@ TEST(FreePoolTest, Basic) {
pool.Free(p2);
pool.Free(p3);
- // We know have 2 1 byte allocations. Make a two byte allocation.
+ // We know have 2 1 byte allocations, which were rounded up to 8 bytes. Make an 8
+ // byte allocation, which can reuse one of the existing ones.
uint8_t* p4 = pool.Allocate(2);
memset(p4, 2, 123);
- EXPECT_EQ(mem_pool.total_allocated_bytes(), 48);
- EXPECT_TRUE(p4 != p1);
- EXPECT_TRUE(p4 != p2);
- EXPECT_TRUE(p4 != p3);
+ EXPECT_EQ(mem_pool.total_allocated_bytes(), 32);
+ EXPECT_TRUE(p4 == p1 || p4 == p2 || p4 == p3);
pool.Free(p4);
+ // Make a 9 byte allocation, which requires a new allocation.
+ uint8_t* p5 = pool.Allocate(9);
+ memset(p5, 9, 123);
+ EXPECT_EQ(mem_pool.total_allocated_bytes(), 56);
+ pool.Free(p5);
+ EXPECT_TRUE(p5 != p1);
+ EXPECT_TRUE(p5 != p2);
+ EXPECT_TRUE(p5 != p3);
+
// Everything's freed. Try grabbing the ones that have been allocated.
p1 = pool.Allocate(1);
*p1 = 123;
p2 = pool.Allocate(1);
*p2 = 123;
- p3 = pool.Allocate(2);
- memset(p3, 123, 2);
- EXPECT_EQ(mem_pool.total_allocated_bytes(), 48);
+ p5 = pool.Allocate(9);
+ memset(p5, 123, 9);
+ EXPECT_EQ(mem_pool.total_allocated_bytes(), 56);
// Make another 1 byte allocation.
p4 = pool.Allocate(1);
*p4 = 1;
- EXPECT_EQ(mem_pool.total_allocated_bytes(), 64);
+ EXPECT_EQ(mem_pool.total_allocated_bytes(), 72);
mem_pool.FreeAll();
// Try making allocations larger than 1GB.
- uint8_t* p5 = pool.Allocate(1LL << 32);
- EXPECT_TRUE(p5 != NULL);
+ uint8_t* p6 = pool.Allocate(1LL << 32);
+ EXPECT_TRUE(p6 != NULL);
for (int64_t i = 0; i < (1LL << 32); i += (1 << 29)) {
- *(p5 + i) = i;
+ *(p6 + i) = i;
}
EXPECT_EQ(mem_pool.total_allocated_bytes(), (1LL << 32) + 8);
// Test zero-byte allocation.
- p5 = pool.Allocate(0);
- EXPECT_TRUE(p5 != NULL);
+ p6 = pool.Allocate(0);
+ EXPECT_TRUE(p6 != NULL);
EXPECT_EQ(mem_pool.total_allocated_bytes(), (1LL << 32) + 8);
- pool.Free(p5);
+ pool.Free(p6);
mem_pool.FreeAll();
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/runtime/free-pool.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/free-pool.h b/be/src/runtime/free-pool.h
index ca22c48..746b649 100644
--- a/be/src/runtime/free-pool.h
+++ b/be/src/runtime/free-pool.h
@@ -35,8 +35,8 @@ namespace impala {
/// Implementation of a free pool to recycle allocations. The pool is broken
/// up into 64 lists, one for each power of 2. Each allocation is rounded up
-/// to the next power of 2. When the allocation is freed, it is added to the
-/// corresponding free list.
+/// to the next power of 2 (or 8 bytes, whichever is larger). When the
+/// allocation is freed, it is added to the corresponding free list.
/// Each allocation has an 8 byte header that immediately precedes the actual
/// allocation. If the allocation is owned by the user, the header contains
/// the ptr to the list that it should be added to on Free().
@@ -70,6 +70,9 @@ class FreePool {
if (UNLIKELY(size == 0)) return mem_pool_->EmptyAllocPtr();
++net_allocations_;
if (FLAGS_disable_mem_pools) return reinterpret_cast<uint8_t*>(malloc(size));
+ /// MemPool allocations are 8-byte aligned, so making allocations < 8 bytes
+ /// doesn't save memory and eliminates opportunities to recycle allocations.
+ size = std::max<int64_t>(8, size);
int free_list_idx = Bits::Log2Ceiling64(size);
DCHECK_LT(free_list_idx, NUM_LISTS);
FreeListNode* allocation = lists_[free_list_idx].next;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/runtime/mem-pool-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool-test.cc b/be/src/runtime/mem-pool-test.cc
index 604923c..70fb141 100644
--- a/be/src/runtime/mem-pool-test.cc
+++ b/be/src/runtime/mem-pool-test.cc
@@ -49,15 +49,22 @@ TEST(MemPoolTest, Basic) {
MemPool p2(&tracker);
MemPool p3(&tracker);
+ uint8_t* ptr = NULL;
+
for (int iter = 0; iter < 2; ++iter) {
- // allocate a total of 24K in 32-byte pieces (for which we only request 25 bytes)
+ // Allocate 768 25 + 7 byte allocations.
for (int i = 0; i < 768; ++i) {
- // pads to 32 bytes
- p.Allocate(25);
+ ptr = p.Allocate(25);
+ EXPECT_TRUE(ptr != NULL);
+ EXPECT_EQ(0, reinterpret_cast<uintptr_t>(ptr) % MemPool::DEFAULT_ALIGNMENT)
+ << "Allocation should be aligned";
+
+ // Allocate the padding to get 32 bytes
+ ptr = p.TryAllocateAligned(7, 1);
+ EXPECT_TRUE(ptr != NULL);
}
- // we handed back 24K
+ // We allocated 24K from 28K of chunks (4, 8, 16)
EXPECT_EQ(24 * 1024, p.total_allocated_bytes());
- // .. and allocated 28K of chunks (4, 8, 16)
EXPECT_EQ(28 * 1024, p.GetTotalChunkSizes());
// we're passing on the first two chunks, containing 12K of data; we're left with
@@ -133,7 +140,7 @@ TEST(MemPoolTest, Basic) {
}
// Test zero byte allocation.
- uint8_t* ptr = p.Allocate(0);
+ ptr = p.Allocate(0);
EXPECT_TRUE(ptr != NULL);
EXPECT_EQ(0, p.GetTotalChunkSizes());
}
@@ -487,6 +494,24 @@ TEST(MemPoolTest, ReturnAllocationThenFailedAllocation) {
src.FreeAll();
}
+TEST(MemPoolTest, TryAllocateAligned) {
+ MemTracker tracker(-1);
+ MemPool pool(&tracker);
+ int alignment = 1;
+ int64_t size = 1;
+ constexpr int NUM_ALLOCATIONS = 100000;
+ constexpr int MAX_ALLOCATION_SIZE = 113;
+
+ for (int i = 0; i < NUM_ALLOCATIONS; ++i) {
+ uint8_t* ptr = pool.TryAllocateAligned(size, alignment);
+ ASSERT_TRUE(ptr != NULL);
+ ASSERT_EQ(0, reinterpret_cast<uintptr_t>(ptr) % alignment);
+ alignment = alignment == sizeof(std::max_align_t) ? 1 : alignment * 2;
+ size = (size + 1) % MAX_ALLOCATION_SIZE;
+ }
+
+ pool.FreeAll();
+}
}
IMPALA_TEST_MAIN();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/runtime/mem-pool.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.cc b/be/src/runtime/mem-pool.cc
index 185d8a3..c95953a 100644
--- a/be/src/runtime/mem-pool.cc
+++ b/be/src/runtime/mem-pool.cc
@@ -36,6 +36,7 @@ const int MemPool::INITIAL_CHUNK_SIZE;
const int MemPool::MAX_CHUNK_SIZE;
const char* MemPool::LLVM_CLASS_NAME = "class.impala::MemPool";
+const int MemPool::DEFAULT_ALIGNMENT;
uint32_t MemPool::zero_length_region_ = MEM_POOL_POISON;
MemPool::MemPool(MemTracker* mem_tracker)
@@ -101,8 +102,6 @@ void MemPool::FreeAll() {
}
bool MemPool::FindChunk(int64_t min_size, bool check_limits) noexcept {
- DCHECK(current_chunk_idx_ == -1 || chunks_[current_chunk_idx_].size <
- chunks_[current_chunk_idx_].allocated_bytes + min_size);
// Try to allocate from a free chunk. We may have free chunks after the current chunk
// if Clear() was called. The current chunk may be free if ReturnPartialAllocation()
// was called. The first free chunk (if there is one) can therefore be either the
@@ -133,7 +132,8 @@ bool MemPool::FindChunk(int64_t min_size, bool check_limits) noexcept {
if (FLAGS_disable_mem_pools) {
// Disable pooling by sizing the chunk to fit only this allocation.
- chunk_size = min_size;
+ // Make sure the alignment guarantees are respected.
+ chunk_size = std::max<int64_t>(min_size, sizeof(std::max_align_t));
} else {
DCHECK_GE(next_chunk_size_, INITIAL_CHUNK_SIZE);
chunk_size = max<int64_t>(min_size, next_chunk_size_);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/runtime/mem-pool.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.h b/be/src/runtime/mem-pool.h
index d8c1e61..8980d22 100644
--- a/be/src/runtime/mem-pool.h
+++ b/be/src/runtime/mem-pool.h
@@ -20,9 +20,11 @@
#define IMPALA_RUNTIME_MEM_POOL_H
#include <stdio.h>
+
#include <algorithm>
-#include <vector>
+#include <cstddef>
#include <string>
+#include <vector>
#include "common/logging.h"
#include "util/bit-util.h"
@@ -93,11 +95,11 @@ class MemPool {
/// from the registered limits.
~MemPool();
- /// Allocates 8-byte aligned section of memory of 'size' bytes at the end
+ /// Allocates a section of memory of 'size' bytes with DEFAULT_ALIGNMENT at the end
/// of the the current chunk. Creates a new chunk if there aren't any chunks
/// with enough capacity.
uint8_t* Allocate(int64_t size) noexcept {
- return Allocate<false>(size);
+ return Allocate<false>(size, DEFAULT_ALIGNMENT);
}
/// Same as Allocate() except the mem limit is checked before the allocation and
@@ -105,7 +107,16 @@ class MemPool {
/// The caller must handle the NULL case. This should be used for allocations
/// where the size can be very big to bound the amount by which we exceed mem limits.
uint8_t* TryAllocate(int64_t size) noexcept {
- return Allocate<true>(size);
+ return Allocate<true>(size, DEFAULT_ALIGNMENT);
+ }
+
+ /// Same as TryAllocate() except a non-default alignment can be specified. It
+ /// should be a power-of-two in [1, sizeof(std::max_align_t)].
+ uint8_t* TryAllocateAligned(int64_t size, int alignment) noexcept {
+ DCHECK_GE(alignment, 1);
+ DCHECK_LE(alignment, sizeof(std::max_align_t));
+ DCHECK_EQ(BitUtil::RoundUpToPowerOfTwo(alignment), alignment);
+ return Allocate<true>(size, alignment);
}
/// Returns 'byte_size' to the current chunk back to the mem pool. This can
@@ -151,6 +162,8 @@ class MemPool {
/// For C++/IR interop, we need to be able to look up types by name.
static const char* LLVM_CLASS_NAME;
+ static const int DEFAULT_ALIGNMENT = 8;
+
private:
friend class MemPoolTest;
static const int INITIAL_CHUNK_SIZE = 4 * 1024;
@@ -224,22 +237,37 @@ class MemPool {
}
template <bool CHECK_LIMIT_FIRST>
- uint8_t* Allocate(int64_t size) noexcept {
+ uint8_t* Allocate(int64_t size, int alignment) noexcept {
DCHECK_GE(size, 0);
- if (UNLIKELY(size == 0)) return reinterpret_cast<uint8_t *>(&zero_length_region_);
+ if (UNLIKELY(size == 0)) return reinterpret_cast<uint8_t*>(&zero_length_region_);
+
+ bool fits_in_chunk = false;
+ if (current_chunk_idx_ != -1) {
+ int64_t aligned_allocated_bytes = BitUtil::RoundUpToPowerOf2(
+ chunks_[current_chunk_idx_].allocated_bytes, alignment);
+ if (aligned_allocated_bytes + size <= chunks_[current_chunk_idx_].size) {
+ // Ensure the requested alignment is respected.
+ total_allocated_bytes_ +=
+ aligned_allocated_bytes - chunks_[current_chunk_idx_].allocated_bytes;
+ chunks_[current_chunk_idx_].allocated_bytes = aligned_allocated_bytes;
+ fits_in_chunk = true;
+ }
+ }
- int64_t num_bytes = BitUtil::RoundUp(size, 8);
- if (current_chunk_idx_ == -1
- || num_bytes + chunks_[current_chunk_idx_].allocated_bytes
- > chunks_[current_chunk_idx_].size) {
+ if (!fits_in_chunk) {
// If we couldn't allocate a new chunk, return NULL.
- if (UNLIKELY(!FindChunk(num_bytes, CHECK_LIMIT_FIRST))) return NULL;
+ // malloc() guarantees alignment of min(std::max_align_t, min_chunk_size),
+ // so we do not need to do anything additional to guarantee alignment.
+ static_assert(
+ INITIAL_CHUNK_SIZE >= sizeof(std::max_align_t), "Min chunk size too low");
+ if (UNLIKELY(!FindChunk(size, CHECK_LIMIT_FIRST))) return NULL;
}
+
ChunkInfo& info = chunks_[current_chunk_idx_];
uint8_t* result = info.data + info.allocated_bytes;
- DCHECK_LE(info.allocated_bytes + num_bytes, info.size);
- info.allocated_bytes += num_bytes;
- total_allocated_bytes_ += num_bytes;
+ DCHECK_LE(info.allocated_bytes + size, info.size);
+ info.allocated_bytes += size;
+ total_allocated_bytes_ += size;
DCHECK_LE(current_chunk_idx_, chunks_.size() - 1);
peak_allocated_bytes_ = std::max(total_allocated_bytes_, peak_allocated_bytes_);
return result;
@@ -247,9 +275,8 @@ class MemPool {
};
// Stamp out templated implementations here so they're included in IR module
-template uint8_t* MemPool::Allocate<false>(int64_t size) noexcept;
-template uint8_t* MemPool::Allocate<true>(int64_t size) noexcept;
-
+template uint8_t* MemPool::Allocate<false>(int64_t size, int alignment) noexcept;
+template uint8_t* MemPool::Allocate<true>(int64_t size, int alignment) noexcept;
}
#endif
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/testutil/test-udas.cc
----------------------------------------------------------------------
diff --git a/be/src/testutil/test-udas.cc b/be/src/testutil/test-udas.cc
index dc295b5..569853e 100644
--- a/be/src/testutil/test-udas.cc
+++ b/be/src/testutil/test-udas.cc
@@ -117,3 +117,16 @@ const DoubleVal TruncSumSerialize(FunctionContext* context, const DoubleVal& tot
BigIntVal TruncSumFinalize(FunctionContext* context, const DoubleVal& total) {
return BigIntVal(static_cast<int64_t>(total.val));
}
+
+// Defines aggregate function for testing constant argument handling. The UDA returns
+// true if its second argument is constant for all calls to Update().
+void ArgIsConstInit(FunctionContext* context, BooleanVal* is_const) {
+ *is_const = BooleanVal(context->IsArgConstant(1));
+}
+
+void ArgIsConstUpdate(FunctionContext* context, const IntVal& val,
+ const IntVal& const_arg, BooleanVal* is_const) {}
+
+void ArgIsConstMerge(FunctionContext* context, const BooleanVal& src, BooleanVal* dst) {
+ dst->val |= src.val;
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/udf/udf-internal.h
----------------------------------------------------------------------
diff --git a/be/src/udf/udf-internal.h b/be/src/udf/udf-internal.h
index eca62ab..2fd7415 100644
--- a/be/src/udf/udf-internal.h
+++ b/be/src/udf/udf-internal.h
@@ -15,15 +15,15 @@
// specific language governing permissions and limitations
// under the License.
-
#ifndef IMPALA_UDF_UDF_INTERNAL_H
#define IMPALA_UDF_UDF_INTERNAL_H
-#include <boost/cstdint.hpp>
+#include <string.h>
#include <map>
#include <string>
-#include <string.h>
+#include <utility>
#include <vector>
+#include <boost/cstdint.hpp>
/// Be very careful when adding Impala includes in this file. We don't want to pull
/// in unnecessary dependencies for the development libs.
@@ -31,14 +31,15 @@
namespace impala {
-#define RETURN_IF_NULL(ctx, ptr) \
- do { \
- if (UNLIKELY(ptr == NULL)) { \
+#define RETURN_IF_NULL(ctx, ptr) \
+ do { \
+ if (UNLIKELY(ptr == NULL)) { \
DCHECK(!ctx->impl()->state()->GetQueryStatus().ok()); \
- return; \
- } \
+ return; \
+ } \
} while (false)
+class Expr;
class FreePool;
class MemPool;
class RuntimeState;
@@ -71,7 +72,8 @@ class FunctionContextImpl {
/// Returns a new FunctionContext with the same constant args, fragment-local state, and
/// debug flag as this FunctionContext. The caller is responsible for calling delete on
- /// it.
+ /// it. The cloned FunctionContext cannot be used after the original FunctionContext is
+ /// destroyed because it may reference fragment-local state from the original.
impala_udf::FunctionContext* Clone(MemPool* pool);
/// Allocates a buffer of 'byte_size' with "local" memory management.
@@ -90,8 +92,21 @@ class FunctionContextImpl {
/// Returns true if there are any allocations returned by AllocateLocal().
bool HasLocalAllocations() const { return !local_allocations_.empty(); }
- /// Sets constant_args_. The AnyVal* values are owned by the caller.
- void SetConstantArgs(const std::vector<impala_udf::AnyVal*>& constant_args);
+ /// Sets the constant arg list. The vector should contain one entry per argument,
+ /// with a non-NULL entry if the argument is constant. The AnyVal* values are
+ /// owned by the caller and must be allocated from the ExprContext's MemPool.
+ void SetConstantArgs(std::vector<impala_udf::AnyVal*>&& constant_args);
+
+ /// Sets the non-constant args. Contains one entry per non-constant argument. All
+ /// pointers should be non-NULL. The Expr* and AnyVal* values are owned by the caller.
+ /// The AnyVal* values must be allocated from the ExprContext's MemPool.
+ void SetNonConstantArgs(
+ std::vector<std::pair<Expr*, impala_udf::AnyVal*>>&& non_constant_args);
+
+ const std::vector<impala_udf::AnyVal*>& constant_args() const { return constant_args_; }
+ const std::vector<std::pair<Expr*, impala_udf::AnyVal*>>& non_constant_args() const {
+ return non_constant_args_;
+ }
uint8_t* varargs_buffer() { return varargs_buffer_; }
@@ -111,6 +126,9 @@ class FunctionContextImpl {
return arg_types_;
}
+ // UDFs may manipulate DecimalVal arguments via SIMD instructions such as 'movaps'
+ // that require 16-byte memory alignment.
+ static const int VARARGS_BUFFER_ALIGNMENT = 16;
static const char* LLVM_FUNCTIONCONTEXT_NAME;
RuntimeState* state() { return state_; }
@@ -127,10 +145,8 @@ class FunctionContextImpl {
bool CheckAllocResult(const char* fn_name, uint8_t* buf, int64_t byte_size);
/// Preallocated buffer for storing varargs (if the function has any). Allocated and
- /// owned by this object, but populated by an Expr function.
- //
- /// This is the first field in the class so it's easy to access in codegen'd functions.
- /// Don't move it or add fields above unless you know what you're doing.
+ /// owned by this object, but populated by an Expr function. The buffer is interpreted
+ /// as an array of the appropriate AnyVal subclass.
uint8_t* varargs_buffer_;
int varargs_buffer_size_;
@@ -186,13 +202,20 @@ class FunctionContextImpl {
/// Contains an AnyVal* for each argument of the function. If the AnyVal* is NULL,
/// indicates that the corresponding argument is non-constant. Otherwise contains the
- /// value of the argument.
+ /// value of the argument. The AnyVal* objects and associated data are owned by the
+ /// ExprContext provided when opening the FRAGMENT_LOCAL expression contexts.
std::vector<impala_udf::AnyVal*> constant_args_;
- /// Used by ScalarFnCall to store the arguments when running without codegen. Allows us
- /// to pass AnyVal* arguments to the scalar function directly, rather than codegening a
- /// call that passes the correct AnyVal subclass pointer type. Note that this is only
- /// used for non-variadic arguments; varargs are always stored in varargs_buffer_.
+ /// Vector of all non-constant children expressions that need to be evaluated for
+ /// each input row. The first element of each pair is the child expression and the
+ /// second element is the value it must be evaluated into.
+ std::vector<std::pair<Expr*, impala_udf::AnyVal*>> non_constant_args_;
+
+ /// Used by ScalarFnCall to temporarily store arguments for a UDF when running without
+ /// codegen. Allows us to pass AnyVal* arguments to the scalar function directly,
+ /// rather than codegening a call that passes the correct AnyVal subclass pointer type.
+ /// Note that this is only used for non-variadic arguments; varargs are always stored
+ /// in varargs_buffer_.
std::vector<impala_udf::AnyVal*> staging_input_vals_;
/// Indicates whether this context has been closed. Used for verification/debugging.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/udf/udf-test-harness.cc
----------------------------------------------------------------------
diff --git a/be/src/udf/udf-test-harness.cc b/be/src/udf/udf-test-harness.cc
index cfefdf7..1c3737d 100644
--- a/be/src/udf/udf-test-harness.cc
+++ b/be/src/udf/udf-test-harness.cc
@@ -37,7 +37,7 @@ void UdfTestHarness::SetConstantArgs(
context->SetError("SetConstantArgs() called on non-test FunctionContext");
return;
}
- context->impl()->SetConstantArgs(constant_args);
+ context->impl()->SetConstantArgs(vector<AnyVal*>(constant_args));
}
void UdfTestHarness::CloseContext(FunctionContext* context) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/udf/udf.cc
----------------------------------------------------------------------
diff --git a/be/src/udf/udf.cc b/be/src/udf/udf.cc
index bfdbccc..cd29f6f 100644
--- a/be/src/udf/udf.cc
+++ b/be/src/udf/udf.cc
@@ -109,12 +109,17 @@ class RuntimeState {
using namespace impala;
using namespace impala_udf;
+using std::pair;
+const int FunctionContextImpl::VARARGS_BUFFER_ALIGNMENT;
const char* FunctionContextImpl::LLVM_FUNCTIONCONTEXT_NAME =
"class.impala_udf::FunctionContext";
static const int MAX_WARNINGS = 1000;
+static_assert(__BYTE_ORDER == __LITTLE_ENDIAN,
+ "DecimalVal memory layout assumes little-endianness");
+
FunctionContext* FunctionContextImpl::CreateContext(RuntimeState* state, MemPool* pool,
const FunctionContext::TypeDesc& return_type,
const vector<FunctionContext::TypeDesc>& arg_types,
@@ -138,14 +143,11 @@ FunctionContext* FunctionContextImpl::CreateContext(RuntimeState* state, MemPool
ctx->impl_->intermediate_type_ = intermediate_type;
ctx->impl_->return_type_ = return_type;
ctx->impl_->arg_types_ = arg_types;
- // UDFs may manipulate DecimalVal arguments via SIMD instructions such as 'movaps'
- // that require 16-byte memory alignment.
- ctx->impl_->varargs_buffer_ =
- reinterpret_cast<uint8_t*>(aligned_malloc(varargs_buffer_size, 16));
+ ctx->impl_->varargs_buffer_ = reinterpret_cast<uint8_t*>(
+ aligned_malloc(varargs_buffer_size, VARARGS_BUFFER_ALIGNMENT));
ctx->impl_->varargs_buffer_size_ = varargs_buffer_size;
ctx->impl_->debug_ = debug;
- VLOG_ROW << "Created FunctionContext: " << ctx
- << " with pool " << ctx->impl_->pool_;
+ VLOG_ROW << "Created FunctionContext: " << ctx << " with pool " << ctx->impl_->pool_;
return ctx;
}
@@ -450,18 +452,22 @@ void FunctionContextImpl::FreeLocalAllocations() noexcept {
local_allocations_.clear();
}
-void FunctionContextImpl::SetConstantArgs(const vector<AnyVal*>& constant_args) {
+void FunctionContextImpl::SetConstantArgs(vector<AnyVal*>&& constant_args) {
constant_args_ = constant_args;
}
+void FunctionContextImpl::SetNonConstantArgs(
+ vector<pair<Expr*, AnyVal*>>&& non_constant_args) {
+ non_constant_args_ = non_constant_args;
+}
+
// Note: this function crashes LLVM's JIT in expr-test if it's xcompiled. Do not move to
// expr-ir.cc. This could probably use further investigation.
-StringVal::StringVal(FunctionContext* context, int len) noexcept
- : len(len), ptr(NULL) {
+StringVal::StringVal(FunctionContext* context, int len) noexcept : len(len), ptr(NULL) {
if (UNLIKELY(len > StringVal::MAX_LENGTH)) {
std::cout << "MAX_LENGTH, Trying to allocate " << len;
context->SetError("String length larger than allowed limit of "
- "1 GB character data.");
+ "1 GB character data.");
len = 0;
is_null = true;
} else {
[20/50] [abbrv] incubator-impala git commit: Add -build_shared_libs
for default build for speed.
Posted by ta...@apache.org.
Add -build_shared_libs for default build for speed.
This is already recommended by the wiki:
https://cwiki.apache.org/confluence/display/IMPALA/Building+Impala
Change-Id: Ic83db07e59ff339dcce7362bd296ebcfd60b71d6
Reviewed-on: http://gerrit.cloudera.org:8080/4970
Reviewed-by: Jim Apple <jb...@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/ae24bf28
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/ae24bf28
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/ae24bf28
Branch: refs/heads/hadoop-next
Commit: ae24bf28509c8af6137f89cb425e3d163f8de12a
Parents: 08d89a5
Author: Jim Apple <jb...@cloudera.com>
Authored: Sat Nov 5 16:54:21 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 00:36:28 2016 +0000
----------------------------------------------------------------------
bin/bootstrap_development.sh | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ae24bf28/bin/bootstrap_development.sh
----------------------------------------------------------------------
diff --git a/bin/bootstrap_development.sh b/bin/bootstrap_development.sh
index 8c4f742..b643368 100755
--- a/bin/bootstrap_development.sh
+++ b/bin/bootstrap_development.sh
@@ -76,5 +76,5 @@ pushd "$(dirname $0)/.."
export IMPALA_HOME="$(pwd)"
export MAX_PYTEST_FAILURES=0
source bin/impala-config.sh
-./buildall.sh -noclean -format -testdata
+./buildall.sh -noclean -format -testdata -build_shared_libs
popd
[22/50] [abbrv] incubator-impala git commit: IMPALA-4258: Remove
duplicated and unused test macros
Posted by ta...@apache.org.
IMPALA-4258: Remove duplicated and unused test macros
Macros defined in test-macros.h are either duplicated in gtest-util.h
or are unused anywhere in the code. This change deletes test-macros.h
Change-Id: I08539d7e46b89d7e0a4338510b65f9867814c275
Reviewed-on: http://gerrit.cloudera.org:8080/4917
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/f3d23be4
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/f3d23be4
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/f3d23be4
Branch: refs/heads/hadoop-next
Commit: f3d23be47871a4abefebca1f035d98ecc9203208
Parents: 4af2ea4
Author: aphadke <ap...@cloudera.com>
Authored: Wed Nov 2 11:57:15 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 01:23:41 2016 +0000
----------------------------------------------------------------------
be/src/runtime/tmp-file-mgr-test.cc | 2 +-
be/src/testutil/test-macros.h | 55 --------------------------------
2 files changed, 1 insertion(+), 56 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/f3d23be4/be/src/runtime/tmp-file-mgr-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/tmp-file-mgr-test.cc b/be/src/runtime/tmp-file-mgr-test.cc
index cdd0d2d..828e637 100644
--- a/be/src/runtime/tmp-file-mgr-test.cc
+++ b/be/src/runtime/tmp-file-mgr-test.cc
@@ -24,7 +24,7 @@
#include "common/init.h"
#include "runtime/tmp-file-mgr.h"
#include "service/fe-support.h"
-#include "testutil/test-macros.h"
+#include "testutil/gtest-util.h"
#include "util/filesystem-util.h"
#include "util/metrics.h"
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/f3d23be4/be/src/testutil/test-macros.h
----------------------------------------------------------------------
diff --git a/be/src/testutil/test-macros.h b/be/src/testutil/test-macros.h
deleted file mode 100644
index 1cd2f45..0000000
--- a/be/src/testutil/test-macros.h
+++ /dev/null
@@ -1,55 +0,0 @@
-// Licensed to the Apache Software Foundation (ASF) under one
-// or more contributor license agreements. See the NOTICE file
-// distributed with this work for additional information
-// regarding copyright ownership. The ASF licenses this file
-// to you under the Apache License, Version 2.0 (the
-// "License"); you may not use this file except in compliance
-// with the License. You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing,
-// software distributed under the License is distributed on an
-// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-// KIND, either express or implied. See the License for the
-// specific language governing permissions and limitations
-// under the License.
-
-#ifndef IMPALA_TESTUTIL_TEST_MACROS_H
-#define IMPALA_TESTUTIL_TEST_MACROS_H
-
-#include <string>
-
-// Helper macros for tests.
-// Follows conventions on gtest.h.
-
-// On a non-OK status, adds a failure but doesn't fail the test immediately.
-#define EXPECT_OK(status) do { \
- Status _s = status; \
- if (_s.ok()) { \
- SUCCEED(); \
- } else { \
- ADD_FAILURE() << "Bad status: " << _s.GetDetail(); \
- } \
- } while (0);
-
-// On a non-OK status, fails the test immediately. On an OK status records
-// success.
-#define ASSERT_OK(status) do { \
- Status _s = status; \
- if (_s.ok()) { \
- SUCCEED(); \
- } else { \
- FAIL() << "Bad status: " << _s.GetDetail(); \
- } \
- } while (0);
-
-// Like the above, but doesn't record successful tests.
-#define ASSERT_OK_FAST(status) do { \
- Status _s = status; \
- if (!_s.ok()) { \
- FAIL() << "Bad status: " << _s.GetDetail(); \
- } \
- } while (0);
-
-#endif
[09/50] [abbrv] incubator-impala git commit: Minor fixes to remove
more "cloudera"s from the code.
Posted by ta...@apache.org.
Minor fixes to remove more "cloudera"s from the code.
Change-Id: I27687a3b677def72f1867df54c8e50c93d5cab3a
Reviewed-on: http://gerrit.cloudera.org:8080/4774
Reviewed-by: Jim Apple <jb...@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/9bc90fac
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/9bc90fac
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/9bc90fac
Branch: refs/heads/hadoop-next
Commit: 9bc90faca3df19500151ecd94fa51ab3b27a8ae5
Parents: 5cc1339
Author: Jim Apple <jb...@cloudera.com>
Authored: Thu Oct 20 11:54:33 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 7 22:39:55 2016 +0000
----------------------------------------------------------------------
tests/benchmark/report_benchmark_results.py | 2 +-
.../java/org/apache/impala/UnresolvedUdf.java | 25 +++++++++++---------
2 files changed, 15 insertions(+), 12 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9bc90fac/tests/benchmark/report_benchmark_results.py
----------------------------------------------------------------------
diff --git a/tests/benchmark/report_benchmark_results.py b/tests/benchmark/report_benchmark_results.py
index 068fbf9..5acfd2d 100755
--- a/tests/benchmark/report_benchmark_results.py
+++ b/tests/benchmark/report_benchmark_results.py
@@ -246,7 +246,7 @@ def all_query_results(grouped):
def get_commit_date(commit_sha):
import urllib2
- url = 'https://api.github.com/repos/cloudera/Impala/commits/' + commit_sha
+ url = 'https://api.github.com/repos/apache/incubator-impala/commits/' + commit_sha
try:
request = urllib2.Request(url)
response = urllib2.urlopen(request).read()
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9bc90fac/tests/test-hive-udfs/src/main/java/org/apache/impala/UnresolvedUdf.java
----------------------------------------------------------------------
diff --git a/tests/test-hive-udfs/src/main/java/org/apache/impala/UnresolvedUdf.java b/tests/test-hive-udfs/src/main/java/org/apache/impala/UnresolvedUdf.java
index 2857c04..4ecc468 100644
--- a/tests/test-hive-udfs/src/main/java/org/apache/impala/UnresolvedUdf.java
+++ b/tests/test-hive-udfs/src/main/java/org/apache/impala/UnresolvedUdf.java
@@ -1,16 +1,19 @@
-// Copyright 2016 Cloudera Inc.
+// 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
//
-// Licensed 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
//
-// 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.
+// 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;
[11/50] [abbrv] incubator-impala git commit: IMPALA-4442: Fix FE
ParserTests UnsatisfiedLinkError
Posted by ta...@apache.org.
IMPALA-4442: Fix FE ParserTests UnsatisfiedLinkError
In some development environments, the ParserTests may always fail with an
java.lang.UnsatisfiedLinkError:
org.apache.impala.service.FeSupport.NativeGetStartupOptions()[B
at o.a.i.service.FeSupport.NativeGetStartupOptions(Native Method)
at o.a.i.service.FeSupport.GetStartupOptions(FeSupport.java:268)
at o.a.i.common.RuntimeEnv.<init>(RuntimeEnv.java:47)
at o.a.i.common.RuntimeEnv.<clinit>(RuntimeEnv.java:34)
at o.a.i.testutil.TestUtils.assumeKuduIsSupported(TestUtils.java:288)
at o.a.i.analysis.ParserTest.TestKuduUpdate(ParserTest.java:1697)
I believe the issue is related to some static loading of
classes and/or libraries in Java because changing the
ParserTest to initialize the Frontend makes the error go
away. I haven't been able to pin-point the exact issue with
loading, but it makes sense that the ParserTest should
initialize the Frontend static state if it will be called by
libfesupport later since it seems to be an issue affecting
some environments and not others, i.e. subject to
environmental factors.
This fixes the issue by changing ParserTest to extend
FrontendTestBase which initializes the Frontend class
statically.
Change-Id: I1828504f79c51679f9ca07176bffbe248d450e87
Reviewed-on: http://gerrit.cloudera.org:8080/4976
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/1a99b782
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/1a99b782
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/1a99b782
Branch: refs/heads/hadoop-next
Commit: 1a99b78227dc37e2ab10d8b117fbc6930b703efb
Parents: 3be4b3e
Author: Matthew Jacobs <mj...@cloudera.com>
Authored: Mon Nov 7 11:50:24 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 00:31:35 2016 +0000
----------------------------------------------------------------------
.../org/apache/impala/analysis/ParserTest.java | 22 ++------------------
1 file changed, 2 insertions(+), 20 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/1a99b782/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
index 092e146..98863ce 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
@@ -18,7 +18,6 @@
package org.apache.impala.analysis;
import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -30,37 +29,20 @@ import java.util.List;
import org.apache.hadoop.hive.metastore.MetaStoreUtils;
import org.apache.impala.analysis.TimestampArithmeticExpr.TimeUnit;
import org.apache.impala.common.AnalysisException;
+import org.apache.impala.common.FrontendTestBase;
import org.apache.impala.testutil.TestUtils;
import org.junit.Test;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
-public class ParserTest {
+public class ParserTest extends FrontendTestBase {
// Representative operands for testing.
private final static String[] operands_ =
new String[] {"i", "5", "true", "NULL", "'a'", "(1.5 * 8)" };
/**
- * Asserts in case of parser error.
- */
- public Object ParsesOk(String stmt) {
- SqlScanner input = new SqlScanner(new StringReader(stmt));
- SqlParser parser = new SqlParser(input);
- Object result = null;
- try {
- result = parser.parse().value;
- } catch (Exception e) {
- System.err.println(parser.getErrorMsg(stmt));
- e.printStackTrace();
- fail("\n" + parser.getErrorMsg(stmt));
- }
- assertNotNull(result);
- return result;
- }
-
- /**
* Attempts to parse the given select statement, and asserts in case of parser error.
* Also asserts that the first select-list expression is of given class.
*/
[13/50] [abbrv] incubator-impala git commit: IMPALA-4302,
IMPALA-2379: constant expr arg fixes
Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/udf/udf.h
----------------------------------------------------------------------
diff --git a/be/src/udf/udf.h b/be/src/udf/udf.h
index e6ec07c..461482c 100644
--- a/be/src/udf/udf.h
+++ b/be/src/udf/udf.h
@@ -606,17 +606,18 @@ struct StringVal : public AnyVal {
struct DecimalVal : public impala_udf::AnyVal {
/// Decimal data is stored as an unscaled integer value. For example, the decimal 1.00
- /// (precison 3, scale 2) is stored as 100. The byte size necessary to store the decimal
- /// depends on the precision, which determines which field of the union should be used to
- /// store and manipulate the unscaled value.
- //
+ /// (precision 3, scale 2) is stored as 100. The byte size necessary to store the
+ /// decimal depends on the precision, which determines which field of the union should
+ /// be used to store and manipulate the unscaled value.
+ ///
/// precision between 0-9: val4 (4 bytes)
/// precision between 10-18: val8 (8 bytes)
/// precision between 19-38: val16 (16 bytes)
- //
+ ///
/// While it is always safe to use a larger field than necessary, it may result in worse
- /// performance. For example, a UDF that only uses val16 can handle any precision but may
- /// be slower than one that uses val4 or val8.
+ /// performance. For example, a UDF that only uses val16 can handle any precision but
+ /// may be slower than one that uses val4 or val8. This is because the least-significant
+ /// bits of all three union fields are the same (assuming a little-endian architecture).
union {
int32_t val4;
int64_t val8;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/be/src/util/bit-util.h
----------------------------------------------------------------------
diff --git a/be/src/util/bit-util.h b/be/src/util/bit-util.h
index 9a5c4a4..deb16a9 100644
--- a/be/src/util/bit-util.h
+++ b/be/src/util/bit-util.h
@@ -72,7 +72,7 @@ class BitUtil {
/// Returns 'value' rounded up to the nearest multiple of 'factor' when factor is
/// a power of two
- static inline int RoundUpToPowerOf2(int value, int factor) {
+ static inline int64_t RoundUpToPowerOf2(int64_t value, int64_t factor) {
DCHECK((factor > 0) && ((factor & (factor - 1)) == 0));
return (value + (factor - 1)) & ~(factor - 1);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/testdata/workloads/functional-query/queries/QueryTest/exprs.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/exprs.test b/testdata/workloads/functional-query/queries/QueryTest/exprs.test
index 3c7f5d5..ba8d4fb 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/exprs.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/exprs.test
@@ -803,6 +803,35 @@ NULL
boolean
====
---- QUERY
+# In predicate with strings
+select int_col, string_col from alltypesagg
+where string_col in ('212', '768', '1242', '124141', '0000', '99999')
+order by int_col limit 20
+---- RESULTS
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+212,'212'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+768,'768'
+---- TYPES
+int,string
+====
+---- QUERY
select count(*) from alltypesagg
where true in (bool_col, tinyint_col)
---- RESULTS
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/testdata/workloads/functional-query/queries/QueryTest/uda.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/uda.test b/testdata/workloads/functional-query/queries/QueryTest/uda.test
index 8572e8c..21877cf 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/uda.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/uda.test
@@ -34,3 +34,10 @@ select trunc_sum(double_col),sum(double_col) from functional_parquet.alltypes wh
---- TYPES
bigint,double
====
+---- QUERY
+select arg_is_const(int_col, 1) from functional_parquet.alltypes;
+---- RESULTS
+true
+---- TYPES
+boolean
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/testdata/workloads/targeted-perf/queries/primitive_filter_in_predicate.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/targeted-perf/queries/primitive_filter_in_predicate.test b/testdata/workloads/targeted-perf/queries/primitive_filter_in_predicate.test
new file mode 100644
index 0000000..c10b48a
--- /dev/null
+++ b/testdata/workloads/targeted-perf/queries/primitive_filter_in_predicate.test
@@ -0,0 +1,10 @@
+====
+---- QUERY: primitive_filter_in_predicate
+-- Description : Scan fact table while applying selective in predicate filter.
+-- Target test case : Basic scan and filter.
+SELECT count(*)
+FROM lineitem
+WHERE l_partkey in (1,6,11,16,21,26,31,36,41,46,51,56,61,66,71,76,81,86,91,96,101,106,111,116,121,126,131,136,141,146,151,156,161,166,171,176,181,186,191,196,201,206,211,216,221,226,231,236,241,246,251,256,261,266,271,276,281,286,291,296,301,306,311,316,321,326,331,336,341,346,351,356,361,366,371,376,381,386,391,396,401,406,411,416,421,426,431,436,441,446,451,456,461,466,471,476,481,486,491,496,501,506,511,516,521,526,531,536,541,546,551,556,561,566,571,576,581,586,591,596,601,606,611,616,621,626,631,636,641,646,651,656,661,666,671,676,681,686,691,696,701,706,711,716,721,726,731,736,741,746,751,756,761,766,771,776,781,786,791,796,801,806,811,816,821,826,831,836,841,846,851,856,861,866,871,876,881,886,891,896,901,906,911,916,921,926,931,936,941,946,951,956,961,966,971,976,981,986,991,996,1001,1006,1011,1016,1021,1026,1031,1036,1041,1046,1051,1056,1061,1066,1071,1076,1081,1086,1091,1096,1101,1106,1111,1116,1121,1126,1131,1136,1141,1146,1151,1156,1161,1166,1171,1176,1181,1186,1191,1196
,1201,1206,1211,1216,1221,1226,1231,1236,1241,1246,1251,1256,1261,1266,1271,1276,1281,1286,1291,1296,1301,1306,1311,1316,1321,1326,1331,1336,1341,1346,1351,1356,1361,1366,1371,1376,1381,1386,1391,1396,1401,1406,1411,1416,1421,1426,1431,1436,1441,1446,1451,1456,1461,1466,1471,1476,1481,1486,1491,1496,1501,1506,1511,1516,1521,1526,1531,1536,1541,1546,1551,1556,1561,1566,1571,1576,1581,1586,1591,1596,1601,1606,1611,1616,1621,1626,1631,1636,1641,1646,1651,1656,1661,1666,1671,1676,1681,1686,1691,1696,1701,1706,1711,1716,1721,1726,1731,1736,1741,1746,1751,1756,1761,1766,1771,1776,1781,1786,1791,1796,1801,1806,1811,1816,1821,1826,1831,1836,1841,1846,1851,1856,1861,1866,1871,1876,1881,1886,1891,1896,1901,1906,1911,1916,1921,1926,1931,1936,1941,1946,1951,1956,1961,1966,1971,1976,1981,1986,1991,1996,2001,2006,2011,2016,2021,2026,2031,2036,2041,2046,2051,2056,2061,2066,2071,2076,2081,2086,2091,2096,2101,2106,2111,2116,2121,2126,2131,2136,2141,2146,2151,2156,2161,2166,2171,2176,2181,2186,2191,2
196,2201,2206,2211,2216,2221,2226,2231,2236,2241,2246,2251,2256,2261,2266,2271,2276,2281,2286)
+---- RESULTS
+---- TYPES
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/10fa472f/tests/query_test/test_udfs.py
----------------------------------------------------------------------
diff --git a/tests/query_test/test_udfs.py b/tests/query_test/test_udfs.py
index 2658351..0497cbd 100644
--- a/tests/query_test/test_udfs.py
+++ b/tests/query_test/test_udfs.py
@@ -329,6 +329,7 @@ returns decimal(9,2) location '{location}' update_fn='SumSmallDecimalUpdate';
# Create test UDA functions in {database} from library {location}
create_test_udas_template = """
drop function if exists {database}.trunc_sum(double);
+drop function if exists {database}.arg_is_const(int, int);
create database if not exists {database};
@@ -336,6 +337,10 @@ create aggregate function {database}.trunc_sum(double)
returns bigint intermediate double location '{location}'
update_fn='TruncSumUpdate' merge_fn='TruncSumMerge'
serialize_fn='TruncSumSerialize' finalize_fn='TruncSumFinalize';
+
+create aggregate function {database}.arg_is_const(int, int)
+returns boolean location '{location}'
+init_fn='ArgIsConstInit' update_fn='ArgIsConstUpdate' merge_fn='ArgIsConstMerge';
"""
# Create test UDF functions in {database} from library {location}
[49/50] [abbrv] incubator-impala git commit: Run MT_DOP tests on all
file formats.
Posted by ta...@apache.org.
Run MT_DOP tests on all file formats.
Change-Id: I28d5bcc48bbe32fb970b41daa919096061a05beb
Reviewed-on: http://gerrit.cloudera.org:8080/5025
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/0a654b31
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/0a654b31
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/0a654b31
Branch: refs/heads/hadoop-next
Commit: 0a654b31869c77d667cd692a5f36cf0748b31c64
Parents: 9434e38
Author: Alex Behm <al...@cloudera.com>
Authored: Wed Nov 9 12:06:26 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 23:47:40 2016 +0000
----------------------------------------------------------------------
tests/query_test/test_mt_dop.py | 44 ++++++++++++++++++++++++------------
1 file changed, 30 insertions(+), 14 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/0a654b31/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 4bc5179..d05d6b4 100644
--- a/tests/query_test/test_mt_dop.py
+++ b/tests/query_test/test_mt_dop.py
@@ -31,11 +31,6 @@ class TestMtDop(ImpalaTestSuite):
def add_test_dimensions(cls):
super(TestMtDop, cls).add_test_dimensions()
cls.TestMatrix.add_dimension(TestDimension('mt_dop', *MT_DOP_VALUES))
- # IMPALA-4332: The MT scheduler does not work for Kudu or HBase tables.
- cls.TestMatrix.add_constraint(\
- lambda v: v.get_value('table_format').file_format != 'hbase')
- cls.TestMatrix.add_constraint(\
- lambda v: v.get_value('table_format').file_format != 'kudu')
@classmethod
def get_workload(cls):
@@ -46,16 +41,37 @@ class TestMtDop(ImpalaTestSuite):
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)
+ file_format = vector.get_value('table_format').file_format
+ fq_table_name = "%s.mt_dop" % unique_database
+
+ # Different formats need different DDL for creating a test table, and also
+ # have different expected results for compute stats.
+ expected_results = None
+ if file_format == 'kudu':
+ # CREATE TABLE LIKE is currently not supported for Kudu tables.
+ self.execute_query("create external table %s stored as kudu "
+ "tblproperties('kudu.table_name'='impala::functional_kudu.alltypes')"
+ % fq_table_name)
+ expected_results = "Updated 1 partition(s) and 13 column(s)."
+ elif file_format == 'hbase':
+ self.execute_query(
+ "create external table %s like functional_hbase.alltypes" % fq_table_name)
+ expected_results = "Updated 1 partition(s) and 13 column(s)."
+ else:
+ # Create a second table in the same format pointing to the same data files.
+ # This function switches to the format-specific DB in 'vector'.
+ table_loc = self._get_table_location("alltypes", vector)
+ self.execute_query_using_client(self.client,
+ "create external table %s like alltypes location '%s'"
+ % (fq_table_name, table_loc), vector)
+ # Recover partitions for HDFS tables.
+ self.execute_query("alter table %s recover partitions" % fq_table_name)
+ expected_results = "Updated 24 partition(s) and 11 column(s)."
+
+ results = self.execute_query("compute stats %s" % fq_table_name,
+ vector.get_value('exec_option'))
+ assert expected_results in results.data
class TestMtDopParquet(ImpalaTestSuite):
@classmethod
[33/50] [abbrv] incubator-impala git commit: IMPALA-4477: Upgrade
Kudu version to latest master
Posted by ta...@apache.org.
IMPALA-4477: Upgrade Kudu version to latest master
Change the toolchain build and Kudu version to use the
latest master, using Kudu commit 88b023.
Change-Id: I21c5bc0d28df83cd2e57cd30b6ab416e0d430775
Reviewed-on: http://gerrit.cloudera.org:8080/5054
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/4258b9f0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/4258b9f0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/4258b9f0
Branch: refs/heads/hadoop-next
Commit: 4258b9f09e1a0175ba00e7e273484f8f85aeddf0
Parents: d15f86c
Author: Matthew Jacobs <mj...@cloudera.com>
Authored: Fri Nov 11 09:45:28 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sun Nov 13 02:52:33 2016 +0000
----------------------------------------------------------------------
bin/impala-config.sh | 4 ++--
1 file changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/4258b9f0/bin/impala-config.sh
----------------------------------------------------------------------
diff --git a/bin/impala-config.sh b/bin/impala-config.sh
index 4e848c1..f1c867d 100755
--- a/bin/impala-config.sh
+++ b/bin/impala-config.sh
@@ -56,7 +56,7 @@ fi
# native-toolchain build when publishing its build artifacts. This should be changed when
# moving to a different build of the toolchain, e.g. when a version is bumped or a
# compile option is changed.
-: ${IMPALA_TOOLCHAIN_BUILD_ID=249-2267164200}
+: ${IMPALA_TOOLCHAIN_BUILD_ID=264-e9d44349ba}
# This flag is used in $IMPALA_HOME/cmake_modules/toolchain.cmake.
# If it's 0, Impala will be built with the compiler in the toolchain directory.
@@ -265,7 +265,7 @@ export IMPALA_GFLAGS_VERSION=2.0
export IMPALA_GLOG_VERSION=0.3.2-p2
export IMPALA_GPERFTOOLS_VERSION=2.5
export IMPALA_GTEST_VERSION=1.6.0
-export IMPALA_KUDU_VERSION=1.0.0-RC1
+export IMPALA_KUDU_VERSION=88b023
export IMPALA_LLVM_VERSION=3.8.0-p1
export IMPALA_LLVM_ASAN_VERSION=3.8.0-p1
# Debug builds should use the release+asserts build to get additional coverage.
[03/50] [abbrv] incubator-impala git commit: IMPALA-3202: DiskIoMgr
improvements for new buffer pool
Posted by ta...@apache.org.
IMPALA-3202: DiskIoMgr improvements for new buffer pool
The main goal of this patch is to add support to the DiskIoMgr
to read into client-provided buffers, instead of the DiskIoMgr
allocating intermediate buffers. This is important for the new
buffer pool because we want it to entirely manage its own memory,
rather than delegating part of its memory management to the DiskIoMgr.
Also do some cleanup:
* Consolidate some correlated ScanRange parameters into a parameter
struct.
* Remove the "untracked" buffers mem tracker, which is no longer
necessary.
* Change the buffer type in DiskIoMgr to use uint8_t* to be consistent
with the rest of Impala.
Testing:
Added a unit test. We also get coverage from the BufferedBlockMgr unit
tests, any spilling tests and the Parquet tests with large footers.
Change-Id: I913fbb8ae6c242f1585992eb2a622509344dccec
Reviewed-on: http://gerrit.cloudera.org:8080/4631
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/120f34b0
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/120f34b0
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/120f34b0
Branch: refs/heads/hadoop-next
Commit: 120f34b0b171a0194f734f49acae4ab56f0361f3
Parents: ac51667
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Wed Sep 21 09:37:59 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Sun Nov 6 00:32:06 2016 +0000
----------------------------------------------------------------------
be/src/exec/base-sequence-scanner.cc | 6 +-
be/src/exec/hdfs-parquet-scanner.cc | 71 +++++------
be/src/exec/hdfs-scan-node-base.cc | 23 ++--
be/src/exec/hdfs-scan-node-base.h | 11 +-
be/src/exec/hdfs-text-scanner.cc | 8 +-
be/src/exec/scanner-context.cc | 2 +-
be/src/runtime/buffered-block-mgr.cc | 27 ++--
be/src/runtime/disk-io-mgr-internal.h | 3 +-
be/src/runtime/disk-io-mgr-scan-range.cc | 75 ++++++++----
be/src/runtime/disk-io-mgr-stress-test.cc | 1 +
be/src/runtime/disk-io-mgr-stress.cc | 16 ++-
be/src/runtime/disk-io-mgr-stress.h | 8 +-
be/src/runtime/disk-io-mgr-test.cc | 64 ++++++++--
be/src/runtime/disk-io-mgr.cc | 154 ++++++++++++-----------
be/src/runtime/disk-io-mgr.h | 163 +++++++++++++++++++------
15 files changed, 406 insertions(+), 226 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/base-sequence-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/base-sequence-scanner.cc b/be/src/exec/base-sequence-scanner.cc
index cc0722d..432dac8 100644
--- a/be/src/exec/base-sequence-scanner.cc
+++ b/be/src/exec/base-sequence-scanner.cc
@@ -55,9 +55,9 @@ Status BaseSequenceScanner::IssueInitialRanges(HdfsScanNodeBase* scan_node,
// it is not cached.
// TODO: add remote disk id and plumb that through to the io mgr. It should have
// 1 queue for each NIC as well?
- DiskIoMgr::ScanRange* header_range = scan_node->AllocateScanRange(
- files[i]->fs, files[i]->filename.c_str(), header_size, 0, metadata->partition_id,
- -1, false, false, files[i]->mtime);
+ DiskIoMgr::ScanRange* header_range = scan_node->AllocateScanRange(files[i]->fs,
+ files[i]->filename.c_str(), header_size, 0, metadata->partition_id, -1, false,
+ DiskIoMgr::BufferOpts::Uncached());
header_ranges.push_back(header_range);
}
// Issue the header ranges only. ProcessSplit() will issue the files' scan ranges
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/hdfs-parquet-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-parquet-scanner.cc b/be/src/exec/hdfs-parquet-scanner.cc
index 79925a4..bd5d65c 100644
--- a/be/src/exec/hdfs-parquet-scanner.cc
+++ b/be/src/exec/hdfs-parquet-scanner.cc
@@ -108,13 +108,14 @@ Status HdfsParquetScanner::IssueInitialRanges(HdfsScanNodeBase* scan_node,
footer_range = scan_node->AllocateScanRange(files[i]->fs,
files[i]->filename.c_str(), footer_size, footer_start,
split_metadata->partition_id, footer_split->disk_id(),
- footer_split->try_cache(), footer_split->expected_local(), files[i]->mtime,
- split);
+ footer_split->expected_local(),
+ DiskIoMgr::BufferOpts(footer_split->try_cache(), files[i]->mtime), split);
} else {
// If we did not find the last split, we know it is going to be a remote read.
- footer_range = scan_node->AllocateScanRange(files[i]->fs,
- files[i]->filename.c_str(), footer_size, footer_start,
- split_metadata->partition_id, -1, false, false, files[i]->mtime, split);
+ footer_range =
+ scan_node->AllocateScanRange(files[i]->fs, files[i]->filename.c_str(),
+ footer_size, footer_start, split_metadata->partition_id, -1, false,
+ DiskIoMgr::BufferOpts::Uncached(), split);
}
footer_ranges.push_back(footer_range);
@@ -841,8 +842,8 @@ Status HdfsParquetScanner::ProcessFooter() {
uint8_t* metadata_size_ptr = magic_number_ptr - sizeof(int32_t);
uint32_t metadata_size = *reinterpret_cast<uint32_t*>(metadata_size_ptr);
uint8_t* metadata_ptr = metadata_size_ptr - metadata_size;
- // If the metadata was too big, we need to stitch it before deserializing it.
- // In that case, we stitch the data in this buffer.
+ // If the metadata was too big, we need to read it into a contiguous buffer before
+ // deserializing it.
ScopedBuffer metadata_buffer(scan_node_->mem_tracker());
DCHECK(metadata_range_ != NULL);
@@ -854,45 +855,34 @@ Status HdfsParquetScanner::ProcessFooter() {
DCHECK(file_desc != NULL);
// The start of the metadata is:
// file_length - 4-byte metadata size - footer-size - metadata size
- int64_t metadata_start = file_desc->file_length -
- sizeof(int32_t) - sizeof(PARQUET_VERSION_NUMBER) - metadata_size;
- int64_t metadata_bytes_to_read = metadata_size;
+ int64_t metadata_start = file_desc->file_length - sizeof(int32_t)
+ - sizeof(PARQUET_VERSION_NUMBER) - metadata_size;
if (metadata_start < 0) {
return Status(Substitute("File '$0' is invalid. Invalid metadata size in file "
"footer: $1 bytes. File size: $2 bytes.", filename(), metadata_size,
file_desc->file_length));
}
- // IoMgr can only do a fixed size Read(). The metadata could be larger
- // so we stitch it here.
- // TODO: consider moving this stitching into the scanner context. The scanner
- // context usually handles the stitching but no other scanner need this logic
- // now.
if (!metadata_buffer.TryAllocate(metadata_size)) {
return Status(Substitute("Could not allocate buffer of $0 bytes for Parquet "
"metadata for file '$1'.", metadata_size, filename()));
}
metadata_ptr = metadata_buffer.buffer();
- int64_t copy_offset = 0;
DiskIoMgr* io_mgr = scan_node_->runtime_state()->io_mgr();
- while (metadata_bytes_to_read > 0) {
- int64_t to_read = ::min<int64_t>(io_mgr->max_read_buffer_size(),
- metadata_bytes_to_read);
- DiskIoMgr::ScanRange* range = scan_node_->AllocateScanRange(
- metadata_range_->fs(), filename(), to_read, metadata_start + copy_offset, -1,
- metadata_range_->disk_id(), metadata_range_->try_cache(),
- metadata_range_->expected_local(), file_desc->mtime);
-
- DiskIoMgr::BufferDescriptor* io_buffer = NULL;
- RETURN_IF_ERROR(io_mgr->Read(scan_node_->reader_context(), range, &io_buffer));
- memcpy(metadata_ptr + copy_offset, io_buffer->buffer(), io_buffer->len());
- io_buffer->Return();
-
- metadata_bytes_to_read -= to_read;
- copy_offset += to_read;
- }
- DCHECK_EQ(metadata_bytes_to_read, 0);
+ // Read the header into the metadata buffer.
+ DiskIoMgr::ScanRange* metadata_range = scan_node_->AllocateScanRange(
+ metadata_range_->fs(), filename(), metadata_size, metadata_start, -1,
+ metadata_range_->disk_id(), metadata_range_->expected_local(),
+ DiskIoMgr::BufferOpts::ReadInto(metadata_buffer.buffer(), metadata_size));
+
+ DiskIoMgr::BufferDescriptor* io_buffer;
+ RETURN_IF_ERROR(
+ io_mgr->Read(scan_node_->reader_context(), metadata_range, &io_buffer));
+ DCHECK_EQ(io_buffer->buffer(), metadata_buffer.buffer());
+ DCHECK_EQ(io_buffer->len(), metadata_size);
+ DCHECK(io_buffer->eosr());
+ io_buffer->Return();
}
// Deserialize file header
@@ -1153,14 +1143,13 @@ Status HdfsParquetScanner::InitColumns(
static_cast<ScanRangeMetadata*>(metadata_range_->meta_data())->original_split;
// Determine if the column is completely contained within a local split.
- bool column_range_local = split_range->expected_local() &&
- col_start >= split_range->offset() &&
- col_end <= split_range->offset() + split_range->len();
-
- DiskIoMgr::ScanRange* col_range = scan_node_->AllocateScanRange(
- metadata_range_->fs(), filename(), col_len, col_start, scalar_reader->col_idx(),
- split_range->disk_id(), split_range->try_cache(), column_range_local,
- file_desc->mtime);
+ bool col_range_local = split_range->expected_local()
+ && col_start >= split_range->offset()
+ && col_end <= split_range->offset() + split_range->len();
+ DiskIoMgr::ScanRange* col_range = scan_node_->AllocateScanRange(metadata_range_->fs(),
+ filename(), col_len, col_start, scalar_reader->col_idx(), split_range->disk_id(),
+ col_range_local,
+ DiskIoMgr::BufferOpts(split_range->try_cache(), file_desc->mtime));
col_ranges.push_back(col_range);
// Get the stream that will be used for this column
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/hdfs-scan-node-base.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-scan-node-base.cc b/be/src/exec/hdfs-scan-node-base.cc
index bf0697c..d31c6d1 100644
--- a/be/src/exec/hdfs-scan-node-base.cc
+++ b/be/src/exec/hdfs-scan-node-base.cc
@@ -277,8 +277,8 @@ Status HdfsScanNodeBase::Prepare(RuntimeState* state) {
}
file_desc->splits.push_back(
AllocateScanRange(file_desc->fs, file_desc->filename.c_str(), split.length,
- split.offset, split.partition_id, params.volume_id,
- try_cache, expected_local, file_desc->mtime));
+ split.offset, split.partition_id, params.volume_id, expected_local,
+ DiskIoMgr::BufferOpts(try_cache, file_desc->mtime)));
}
// Update server wide metrics for number of scan ranges and ranges that have
@@ -554,9 +554,9 @@ bool HdfsScanNodeBase::WaitForRuntimeFilters(int32_t time_ms) {
return false;
}
-DiskIoMgr::ScanRange* HdfsScanNodeBase::AllocateScanRange(
- hdfsFS fs, const char* file, int64_t len, int64_t offset, int64_t partition_id,
- int disk_id, bool try_cache, bool expected_local, int64_t mtime,
+DiskIoMgr::ScanRange* HdfsScanNodeBase::AllocateScanRange(hdfsFS fs, const char* file,
+ int64_t len, int64_t offset, int64_t partition_id, int disk_id, bool expected_local,
+ const DiskIoMgr::BufferOpts& buffer_opts,
const DiskIoMgr::ScanRange* original_split) {
DCHECK_GE(disk_id, -1);
// Require that the scan range is within [0, file_length). While this cannot be used
@@ -573,15 +573,20 @@ DiskIoMgr::ScanRange* HdfsScanNodeBase::AllocateScanRange(
new ScanRangeMetadata(partition_id, original_split));
DiskIoMgr::ScanRange* range =
runtime_state_->obj_pool()->Add(new DiskIoMgr::ScanRange());
- range->Reset(fs, file, len, offset, disk_id, try_cache, expected_local,
- mtime, metadata);
+ range->Reset(fs, file, len, offset, disk_id, expected_local, buffer_opts, metadata);
return range;
}
+DiskIoMgr::ScanRange* HdfsScanNodeBase::AllocateScanRange(hdfsFS fs, const char* file,
+ int64_t len, int64_t offset, int64_t partition_id, int disk_id, bool try_cache,
+ bool expected_local, int mtime, const DiskIoMgr::ScanRange* original_split) {
+ return AllocateScanRange(fs, file, len, offset, partition_id, disk_id, expected_local,
+ DiskIoMgr::BufferOpts(try_cache, mtime), original_split);
+}
+
Status HdfsScanNodeBase::AddDiskIoRanges(const vector<DiskIoMgr::ScanRange*>& ranges,
int num_files_queued) {
- RETURN_IF_ERROR(
- runtime_state_->io_mgr()->AddScanRanges(reader_context_, ranges));
+ RETURN_IF_ERROR(runtime_state_->io_mgr()->AddScanRanges(reader_context_, ranges));
num_unqueued_files_.Add(-num_files_queued);
DCHECK_GE(num_unqueued_files_.Load(), 0);
return Status::OK();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/hdfs-scan-node-base.h
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-scan-node-base.h b/be/src/exec/hdfs-scan-node-base.h
index 3531c9e..785674c 100644
--- a/be/src/exec/hdfs-scan-node-base.h
+++ b/be/src/exec/hdfs-scan-node-base.h
@@ -189,11 +189,16 @@ class HdfsScanNodeBase : public ScanNode {
/// If not NULL, the 'original_split' pointer is stored for reference in the scan range
/// metadata of the scan range that is to be allocated.
/// This is thread safe.
- DiskIoMgr::ScanRange* AllocateScanRange(
- hdfsFS fs, const char* file, int64_t len, int64_t offset, int64_t partition_id,
- int disk_id, bool try_cache, bool expected_local, int64_t mtime,
+ DiskIoMgr::ScanRange* AllocateScanRange(hdfsFS fs, const char* file, int64_t len,
+ int64_t offset, int64_t partition_id, int disk_id, bool expected_local,
+ const DiskIoMgr::BufferOpts& buffer_opts,
const DiskIoMgr::ScanRange* original_split = NULL);
+ /// Old API for compatibility with text scanners (e.g. LZO text scanner).
+ DiskIoMgr::ScanRange* AllocateScanRange(hdfsFS fs, const char* file, int64_t len,
+ int64_t offset, int64_t partition_id, int disk_id, bool try_cache,
+ bool expected_local, int mtime, const DiskIoMgr::ScanRange* original_split = NULL);
+
/// Adds ranges to the io mgr queue. 'num_files_queued' indicates how many file's scan
/// ranges have been added completely. A file's scan ranges are added completely if no
/// new scanner threads will be needed to process that file besides the additional
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/hdfs-text-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-text-scanner.cc b/be/src/exec/hdfs-text-scanner.cc
index fa267b4..6757815 100644
--- a/be/src/exec/hdfs-text-scanner.cc
+++ b/be/src/exec/hdfs-text-scanner.cc
@@ -108,10 +108,10 @@ Status HdfsTextScanner::IssueInitialRanges(HdfsScanNodeBase* scan_node,
DCHECK_GT(files[i]->file_length, 0);
ScanRangeMetadata* metadata =
static_cast<ScanRangeMetadata*>(split->meta_data());
- DiskIoMgr::ScanRange* file_range = scan_node->AllocateScanRange(
- files[i]->fs, files[i]->filename.c_str(), files[i]->file_length, 0,
- metadata->partition_id, split->disk_id(), split->try_cache(),
- split->expected_local(), files[i]->mtime);
+ DiskIoMgr::ScanRange* file_range = scan_node->AllocateScanRange(files[i]->fs,
+ files[i]->filename.c_str(), files[i]->file_length, 0,
+ metadata->partition_id, split->disk_id(), split->expected_local(),
+ DiskIoMgr::BufferOpts(split->try_cache(), files[i]->mtime));
compressed_text_scan_ranges.push_back(file_range);
scan_node->max_compressed_text_file_length()->Set(files[i]->file_length);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/exec/scanner-context.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/scanner-context.cc b/be/src/exec/scanner-context.cc
index 033ab82..8e8e84c 100644
--- a/be/src/exec/scanner-context.cc
+++ b/be/src/exec/scanner-context.cc
@@ -180,7 +180,7 @@ Status ScannerContext::Stream::GetNextBuffer(int64_t read_past_size) {
}
DiskIoMgr::ScanRange* range = parent_->scan_node_->AllocateScanRange(
scan_range_->fs(), filename(), read_past_buffer_size, offset, -1,
- scan_range_->disk_id(), false, false, scan_range_->mtime());
+ scan_range_->disk_id(), false, DiskIoMgr::BufferOpts::Uncached());
RETURN_IF_ERROR(parent_->state_->io_mgr()->Read(
parent_->scan_node_->reader_context(), range, &io_buffer_));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/buffered-block-mgr.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/buffered-block-mgr.cc b/be/src/runtime/buffered-block-mgr.cc
index f1d947e..b7a48a9 100644
--- a/be/src/runtime/buffered-block-mgr.cc
+++ b/be/src/runtime/buffered-block-mgr.cc
@@ -671,25 +671,16 @@ Status BufferedBlockMgr::PinBlock(Block* block, bool* pinned, Block* release_blo
DiskIoMgr::ScanRange* scan_range =
obj_pool_.Add(new DiskIoMgr::ScanRange());
scan_range->Reset(NULL, block->write_range_->file(), block->write_range_->len(),
- block->write_range_->offset(), block->write_range_->disk_id(), false, block,
- DiskIoMgr::ScanRange::NEVER_CACHE);
- vector<DiskIoMgr::ScanRange*> ranges(1, scan_range);
- status = io_mgr_->AddScanRanges(io_request_context_, ranges, true);
+ block->write_range_->offset(), block->write_range_->disk_id(), false,
+ DiskIoMgr::BufferOpts::ReadInto(block->buffer(), block->buffer_len()));
+ DiskIoMgr::BufferDescriptor* io_mgr_buffer;
+ status = io_mgr_->Read(io_request_context_, scan_range, &io_mgr_buffer);
if (!status.ok()) goto error;
- // Read from the io mgr buffer into the block's assigned buffer.
- int64_t offset = 0;
- bool buffer_eosr;
- do {
- DiskIoMgr::BufferDescriptor* io_mgr_buffer;
- status = scan_range->GetNext(&io_mgr_buffer);
- if (!status.ok()) goto error;
- memcpy(block->buffer() + offset, io_mgr_buffer->buffer(), io_mgr_buffer->len());
- offset += io_mgr_buffer->len();
- buffer_eosr = io_mgr_buffer->eosr();
- io_mgr_buffer->Return();
- } while (!buffer_eosr);
- DCHECK_EQ(offset, block->write_range_->len());
+ DCHECK_EQ(io_mgr_buffer->buffer(), block->buffer());
+ DCHECK_EQ(io_mgr_buffer->len(), block->valid_data_len());
+ DCHECK(io_mgr_buffer->eosr());
+ io_mgr_buffer->Return();
}
if (FLAGS_disk_spill_encryption) {
@@ -1285,7 +1276,7 @@ void BufferedBlockMgr::Init(DiskIoMgr* io_mgr, RuntimeProfile* parent_profile,
unique_lock<mutex> l(lock_);
if (initialized_) return;
- io_mgr->RegisterContext(&io_request_context_);
+ io_mgr->RegisterContext(&io_request_context_, NULL);
profile_.reset(new RuntimeProfile(&obj_pool_, "BlockMgr"));
parent_profile->AddChild(profile_.get());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-internal.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-internal.h b/be/src/runtime/disk-io-mgr-internal.h
index 0b279b5..17b02af 100644
--- a/be/src/runtime/disk-io-mgr-internal.h
+++ b/be/src/runtime/disk-io-mgr-internal.h
@@ -250,7 +250,8 @@ class DiskIoRequestContext {
/// The number of buffers that are being used for this reader. This is the sum
/// of all buffers in ScanRange queues and buffers currently being read into (i.e. about
- /// to be queued).
+ /// to be queued). This includes both IOMgr-allocated buffers and client-provided
+ /// buffers.
AtomicInt32 num_used_buffers_;
/// The total number of ready buffers across all ranges. Ready buffers are buffers
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-scan-range.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-scan-range.cc b/be/src/runtime/disk-io-mgr-scan-range.cc
index 8ebe7a5..bc676bf 100644
--- a/be/src/runtime/disk-io-mgr-scan-range.cc
+++ b/be/src/runtime/disk-io-mgr-scan-range.cc
@@ -162,7 +162,7 @@ void DiskIoMgr::ScanRange::Cancel(const Status& status) {
// For cached buffers, we can't close the range until the cached buffer is returned.
// Close() is called from DiskIoMgr::ReturnBuffer().
- if (cached_buffer_ == NULL) Close();
+ if (external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER) Close();
}
void DiskIoMgr::ScanRange::CleanupQueuedBuffers() {
@@ -205,36 +205,57 @@ bool DiskIoMgr::ScanRange::Validate() {
}
DiskIoMgr::ScanRange::ScanRange(int capacity)
- : ready_buffers_capacity_(capacity) {
- request_type_ = RequestType::READ;
- Reset(NULL, "", -1, -1, -1, false, false, NEVER_CACHE);
-}
+ : RequestRange(RequestType::READ),
+ meta_data_(NULL),
+ try_cache_(false),
+ expected_local_(false),
+ io_mgr_(NULL),
+ reader_(NULL),
+ hdfs_file_(NULL),
+ external_buffer_tag_(ExternalBufferTag::NO_BUFFER),
+ ready_buffers_capacity_(capacity),
+ mtime_(-1) {}
DiskIoMgr::ScanRange::~ScanRange() {
DCHECK(hdfs_file_ == NULL) << "File was not closed.";
- DCHECK(cached_buffer_ == NULL) << "Cached buffer was not released.";
+ DCHECK(external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER)
+ << "Cached buffer was not released.";
}
void DiskIoMgr::ScanRange::Reset(hdfsFS fs, const char* file, int64_t len, int64_t offset,
- int disk_id, bool try_cache, bool expected_local, int64_t mtime, void* meta_data) {
+ int disk_id, bool expected_local, const BufferOpts& buffer_opts, void* meta_data) {
DCHECK(ready_buffers_.empty());
+ DCHECK(file != NULL);
+ DCHECK_GE(len, 0);
+ DCHECK_GE(offset, 0);
+ DCHECK(buffer_opts.client_buffer_ == NULL || buffer_opts.client_buffer_len_ >= len_);
fs_ = fs;
file_ = file;
len_ = len;
offset_ = offset;
disk_id_ = disk_id;
- try_cache_ = try_cache;
+ try_cache_ = buffer_opts.try_cache_;
+ mtime_ = buffer_opts.mtime_;
expected_local_ = expected_local;
meta_data_ = meta_data;
- cached_buffer_ = NULL;
+ if (buffer_opts.client_buffer_ != NULL) {
+ external_buffer_tag_ = ExternalBufferTag::CLIENT_BUFFER;
+ client_buffer_.data = buffer_opts.client_buffer_;
+ client_buffer_.len = buffer_opts.client_buffer_len_;
+ } else {
+ external_buffer_tag_ = ExternalBufferTag::NO_BUFFER;
+ }
io_mgr_ = NULL;
reader_ = NULL;
hdfs_file_ = NULL;
- mtime_ = mtime;
}
void DiskIoMgr::ScanRange::InitInternal(DiskIoMgr* io_mgr, DiskIoRequestContext* reader) {
DCHECK(hdfs_file_ == NULL);
+ DCHECK(local_file_ == NULL);
+ // Reader must provide MemTracker or a buffer.
+ DCHECK(external_buffer_tag_ == ExternalBufferTag::CLIENT_BUFFER
+ || reader->mem_tracker_ != NULL);
io_mgr_ = io_mgr;
reader_ = reader;
local_file_ = NULL;
@@ -321,9 +342,10 @@ void DiskIoMgr::ScanRange::Close() {
hdfsFileFreeReadStatistics(stats);
}
}
- if (cached_buffer_ != NULL) {
+ if (external_buffer_tag_ == ExternalBufferTag::CACHED_BUFFER) {
hadoopRzBufferFree(hdfs_file_->file(), cached_buffer_);
cached_buffer_ = NULL;
+ external_buffer_tag_ = ExternalBufferTag::NO_BUFFER;
}
io_mgr_->CacheOrCloseFileHandle(file(), hdfs_file_, false);
VLOG_FILE << "Cache HDFS file handle file=" << file();
@@ -349,23 +371,22 @@ int64_t DiskIoMgr::ScanRange::MaxReadChunkSize() const {
DCHECK(IsS3APath(file()));
return 128 * 1024;
}
- return numeric_limits<int64_t>::max();
+ // The length argument of hdfsRead() is an int. Ensure we don't overflow it.
+ return numeric_limits<int>::max();
}
// TODO: how do we best use the disk here. e.g. is it good to break up a
// 1MB read into 8 128K reads?
// TODO: look at linux disk scheduling
-Status DiskIoMgr::ScanRange::Read(char* buffer, int64_t* bytes_read, bool* eosr) {
+Status DiskIoMgr::ScanRange::Read(
+ uint8_t* buffer, int64_t buffer_len, int64_t* bytes_read, bool* eosr) {
unique_lock<mutex> hdfs_lock(hdfs_lock_);
if (is_cancelled_) return Status::CANCELLED;
*eosr = false;
*bytes_read = 0;
- // hdfsRead() length argument is an int. Since max_buffer_size_ type is no bigger
- // than an int, this min() will ensure that we don't overflow the length argument.
- DCHECK_LE(sizeof(io_mgr_->max_buffer_size_), sizeof(int));
- int bytes_to_read =
- min(static_cast<int64_t>(io_mgr_->max_buffer_size_), len_ - bytes_read_);
+ // Read until the end of the scan range or the end of the buffer.
+ int bytes_to_read = min(len_ - bytes_read_, buffer_len);
DCHECK_GE(bytes_to_read, 0);
if (fs_ != NULL) {
@@ -373,6 +394,9 @@ Status DiskIoMgr::ScanRange::Read(char* buffer, int64_t* bytes_read, bool* eosr)
int64_t max_chunk_size = MaxReadChunkSize();
while (*bytes_read < bytes_to_read) {
int chunk_size = min(bytes_to_read - *bytes_read, max_chunk_size);
+ DCHECK_GE(chunk_size, 0);
+ // The hdfsRead() length argument is an int.
+ DCHECK_LE(chunk_size, numeric_limits<int>::max());
int last_read = hdfsRead(fs_, hdfs_file_->file(), buffer + *bytes_read, chunk_size);
if (last_read == -1) {
return Status(GetHdfsErrorMsg("Error reading from HDFS file: ", file_));
@@ -423,14 +447,15 @@ Status DiskIoMgr::ScanRange::ReadFromCache(bool* read_succeeded) {
if (is_cancelled_) return Status::CANCELLED;
DCHECK(hdfs_file_ != NULL);
- DCHECK(cached_buffer_ == NULL);
- cached_buffer_ = hadoopReadZero(hdfs_file_->file(),
- io_mgr_->cached_read_options_, len());
+ DCHECK(external_buffer_tag_ == ExternalBufferTag::NO_BUFFER);
+ cached_buffer_ =
+ hadoopReadZero(hdfs_file_->file(), io_mgr_->cached_read_options_, len());
+ if (cached_buffer_ != NULL) external_buffer_tag_ = ExternalBufferTag::CACHED_BUFFER;
}
// Data was not cached, caller will fall back to normal read path.
- if (cached_buffer_ == NULL) {
+ if (external_buffer_tag_ != ExternalBufferTag::CACHED_BUFFER) {
VLOG_QUERY << "Cache read failed for scan range: " << DebugString()
- << ". Switching to disk read path.";
+ << ". Switching to disk read path.";
// Clean up the scan range state before re-issuing it.
Close();
return Status::OK();
@@ -455,8 +480,8 @@ Status DiskIoMgr::ScanRange::ReadFromCache(bool* read_succeeded) {
// Create a single buffer desc for the entire scan range and enqueue that.
// 'mem_tracker' is NULL because the memory is owned by the HDFS java client,
// not the Impala backend.
- BufferDescriptor* desc = io_mgr_->GetBufferDesc(
- reader_, NULL, this, reinterpret_cast<char*>(buffer), 0);
+ BufferDescriptor* desc =
+ io_mgr_->GetBufferDesc(reader_, NULL, this, reinterpret_cast<uint8_t*>(buffer), 0);
desc->len_ = bytes_read;
desc->scan_range_offset_ = 0;
desc->eosr_ = true;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-stress-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-stress-test.cc b/be/src/runtime/disk-io-mgr-stress-test.cc
index 4b67abb..7ae9515 100644
--- a/be/src/runtime/disk-io-mgr-stress-test.cc
+++ b/be/src/runtime/disk-io-mgr-stress-test.cc
@@ -36,6 +36,7 @@ const bool TEST_CANCELLATION = true;
int main(int argc, char** argv) {
google::InitGoogleLogging(argv[0]);
CpuInfo::Init();
+ OsInfo::Init();
impala::InitThreading();
int duration_sec = DEFAULT_DURATION_SEC;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-stress.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-stress.cc b/be/src/runtime/disk-io-mgr-stress.cc
index 16fbd39..73e055d 100644
--- a/be/src/runtime/disk-io-mgr-stress.cc
+++ b/be/src/runtime/disk-io-mgr-stress.cc
@@ -73,7 +73,7 @@ DiskIoMgrStress::DiskIoMgrStress(int num_disks, int num_threads_per_disk,
io_mgr_.reset(new DiskIoMgr(
num_disks, num_threads_per_disk, MIN_READ_BUFFER_SIZE, MAX_READ_BUFFER_SIZE));
- Status status = io_mgr_->Init(&dummy_tracker_);
+ Status status = io_mgr_->Init(&mem_tracker_);
CHECK(status.ok());
// Initialize some data files. It doesn't really matter how many there are.
@@ -87,6 +87,7 @@ DiskIoMgrStress::DiskIoMgrStress(int num_disks, int num_threads_per_disk,
}
clients_ = new Client[num_clients_];
+ client_mem_trackers_.resize(num_clients_);
for (int i = 0; i < num_clients_; ++i) {
NewClient(i);
}
@@ -127,7 +128,8 @@ void DiskIoMgrStress::ClientThread(int client_id) {
// Validate the bytes read
CHECK_LE(file_offset + len, expected.size());
- CHECK_EQ(strncmp(buffer->buffer(), &expected.c_str()[file_offset], len), 0);
+ CHECK_EQ(strncmp(reinterpret_cast<char*>(buffer->buffer()),
+ &expected.c_str()[file_offset], len), 0);
// Copy the bytes from this read into the result buffer.
memcpy(read_buffer + file_offset, buffer->buffer(), buffer->len());
@@ -228,13 +230,15 @@ void DiskIoMgrStress::NewClient(int i) {
int range_len = rand() % (MAX_READ_LEN - MIN_READ_LEN) + MIN_READ_LEN;
range_len = min(range_len, file_len - assigned_len);
- DiskIoMgr::ScanRange* range = new DiskIoMgr::ScanRange();;
- range->Reset(NULL, files_[client.file_idx].filename.c_str(), range_len,
- assigned_len, 0, false, false, DiskIoMgr::ScanRange::NEVER_CACHE);
+ DiskIoMgr::ScanRange* range = new DiskIoMgr::ScanRange();
+ range->Reset(NULL, files_[client.file_idx].filename.c_str(), range_len, assigned_len,
+ 0, false, DiskIoMgr::BufferOpts::Uncached());
client.scan_ranges.push_back(range);
assigned_len += range_len;
}
- Status status = io_mgr_->RegisterContext(&client.reader, NULL);
+
+ client_mem_trackers_[i].reset(new MemTracker(-1, "", &mem_tracker_));
+ Status status = io_mgr_->RegisterContext(&client.reader, client_mem_trackers_[i].get());
CHECK(status.ok());
status = io_mgr_->AddScanRanges(client.reader, client.scan_ranges);
CHECK(status.ok());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-stress.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-stress.h b/be/src/runtime/disk-io-mgr-stress.h
index cf81969..6d7549e 100644
--- a/be/src/runtime/disk-io-mgr-stress.h
+++ b/be/src/runtime/disk-io-mgr-stress.h
@@ -19,6 +19,7 @@
#ifndef IMPALA_RUNTIME_DISK_IO_MGR_STRESS_H
#define IMPALA_RUNTIME_DISK_IO_MGR_STRESS_H
+#include <memory>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/mutex.hpp>
@@ -57,8 +58,8 @@ class DiskIoMgrStress {
/// during the test
std::vector<File> files_;
- /// Dummy mem tracker
- MemTracker dummy_tracker_;
+ /// Root mem tracker.
+ MemTracker mem_tracker_;
/// io manager
boost::scoped_ptr<DiskIoMgr> io_mgr_;
@@ -70,6 +71,9 @@ class DiskIoMgrStress {
int num_clients_;
Client* clients_;
+ /// Client MemTrackers, one per client.
+ std::vector<std::unique_ptr<MemTracker>> client_mem_trackers_;
+
/// If true, tests cancelling readers
bool includes_cancellation_;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-test.cc b/be/src/runtime/disk-io-mgr-test.cc
index 0f93875..ef7e12f 100644
--- a/be/src/runtime/disk-io-mgr-test.cc
+++ b/be/src/runtime/disk-io-mgr-test.cc
@@ -62,7 +62,7 @@ class DiskIoMgrTest : public testing::Test {
if (status.ok()) {
DiskIoMgr::ScanRange* scan_range = pool_->Add(new DiskIoMgr::ScanRange());
scan_range->Reset(NULL, (*written_range)->file(), (*written_range)->len(),
- (*written_range)->offset(), 0, false, false, DiskIoMgr::ScanRange::NEVER_CACHE);
+ (*written_range)->offset(), 0, false, DiskIoMgr::BufferOpts::Uncached());
ValidateSyncRead(io_mgr, reader, scan_range, reinterpret_cast<const char*>(data),
sizeof(int32_t));
}
@@ -161,10 +161,16 @@ class DiskIoMgrTest : public testing::Test {
}
}
+ DiskIoMgr::ScanRange* AllocateRange(int num_buffers) {
+ return pool_->Add(new DiskIoMgr::ScanRange(num_buffers));
+ }
+
DiskIoMgr::ScanRange* InitRange(int num_buffers, const char* file_path, int offset,
- int len, int disk_id, int64_t mtime, void* meta_data = NULL, bool is_cached = false) {
- DiskIoMgr::ScanRange* range = pool_->Add(new DiskIoMgr::ScanRange(num_buffers));
- range->Reset(NULL, file_path, len, offset, disk_id, is_cached, true, mtime, meta_data);
+ int len, int disk_id, int64_t mtime, void* meta_data = NULL,
+ bool is_cached = false) {
+ DiskIoMgr::ScanRange* range = AllocateRange(num_buffers);
+ range->Reset(NULL, file_path, len, offset, disk_id, true,
+ DiskIoMgr::BufferOpts(is_cached, mtime), meta_data);
EXPECT_EQ(mtime, range->mtime());
return range;
}
@@ -242,7 +248,7 @@ TEST_F(DiskIoMgrTest, InvalidWrite) {
DiskIoMgr io_mgr(1, 1, 1, 10);
ASSERT_OK(io_mgr.Init(&mem_tracker));
DiskIoRequestContext* writer;
- ASSERT_OK(io_mgr.RegisterContext(&writer));
+ ASSERT_OK(io_mgr.RegisterContext(&writer, NULL));
int32_t* data = pool_->Add(new int32_t);
*data = rand();
@@ -784,7 +790,7 @@ TEST_F(DiskIoMgrTest, MultipleReaderWriter) {
DiskIoMgr io_mgr(num_disks, threads_per_disk, MIN_BUFFER_SIZE, MAX_BUFFER_SIZE);
io_mgr.Init(&mem_tracker);
for (int file_index = 0; file_index < num_contexts; ++file_index) {
- ASSERT_OK(io_mgr.RegisterContext(&contexts[file_index]));
+ ASSERT_OK(io_mgr.RegisterContext(&contexts[file_index], &mem_tracker));
}
pool_.reset(new ObjectPool);
int read_offset = 0;
@@ -898,7 +904,7 @@ TEST_F(DiskIoMgrTest, MultipleReader) {
EXPECT_OK(io_mgr.Init(&mem_tracker));
for (int i = 0; i < NUM_READERS; ++i) {
- ASSERT_OK(io_mgr.RegisterContext(&readers[i], NULL));
+ ASSERT_OK(io_mgr.RegisterContext(&readers[i], &mem_tracker));
vector<DiskIoMgr::ScanRange*> ranges;
for (int j = 0; j < DATA_LEN; ++j) {
@@ -1042,9 +1048,51 @@ TEST_F(DiskIoMgrTest, PartialRead) {
EXPECT_EQ(mem_tracker.consumption(), 0);
}
+// Test reading into a client-allocated buffer.
+TEST_F(DiskIoMgrTest, ReadIntoClientBuffer) {
+ MemTracker mem_tracker(LARGE_MEM_LIMIT);
+ const char* tmp_file = "/tmp/disk_io_mgr_test.txt";
+ const char* data = "the quick brown fox jumped over the lazy dog";
+ int len = strlen(data);
+ int read_len = 4; // Make buffer size smaller than client-provided buffer.
+ CreateTempFile(tmp_file, data);
+
+ scoped_ptr<DiskIoMgr> io_mgr(new DiskIoMgr(1, 1, read_len, read_len));
+
+ ASSERT_OK(io_mgr->Init(&mem_tracker));
+ // Reader doesn't need to provide mem tracker if it's providing buffers.
+ MemTracker* reader_mem_tracker = NULL;
+ DiskIoRequestContext* reader;
+ ASSERT_OK(io_mgr->RegisterContext(&reader, reader_mem_tracker));
+
+ for (int buffer_len : vector<int>({len - 1, len, len + 1})) {
+ vector<uint8_t> client_buffer(buffer_len);
+ int scan_len = min(len, buffer_len);
+ DiskIoMgr::ScanRange* range = AllocateRange(1);
+ range->Reset(NULL, tmp_file, scan_len, 0, 0, true,
+ DiskIoMgr::BufferOpts::ReadInto(&client_buffer[0], buffer_len));
+ ASSERT_OK(io_mgr->AddScanRange(reader, range, true));
+
+ DiskIoMgr::BufferDescriptor* io_buffer;
+ ASSERT_OK(range->GetNext(&io_buffer));
+ ASSERT_TRUE(io_buffer->eosr());
+ ASSERT_EQ(scan_len, io_buffer->len());
+ ASSERT_EQ(client_buffer.data(), io_buffer->buffer());
+ ASSERT_EQ(memcmp(io_buffer->buffer(), data, scan_len), 0);
+
+ // DiskIoMgr should not have allocated memory.
+ EXPECT_EQ(mem_tracker.consumption(), 0);
+ io_buffer->Return();
+ }
+
+ io_mgr->UnregisterContext(reader);
+ pool_.reset();
+ io_mgr.reset();
+ EXPECT_EQ(mem_tracker.consumption(), 0);
+}
}
-int main(int argc, char **argv) {
+int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
impala::InitCommonRuntime(argc, argv, true, impala::TestInfo::BE_TEST);
return RUN_ALL_TESTS();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr.cc b/be/src/runtime/disk-io-mgr.cc
index dd45932..7c5620a 100644
--- a/be/src/runtime/disk-io-mgr.cc
+++ b/be/src/runtime/disk-io-mgr.cc
@@ -223,14 +223,15 @@ void DiskIoMgr::BufferDescriptor::Reset() {
scan_range_offset_ = 0;
}
-void DiskIoMgr::BufferDescriptor::Reset(DiskIoRequestContext* reader,
- ScanRange* range, char* buffer, int64_t buffer_len, MemTracker* mem_tracker) {
+void DiskIoMgr::BufferDescriptor::Reset(DiskIoRequestContext* reader, ScanRange* range,
+ uint8_t* buffer, int64_t buffer_len, MemTracker* mem_tracker) {
DCHECK(io_mgr_ != NULL);
DCHECK(buffer_ == NULL);
DCHECK(range != NULL);
DCHECK(buffer != NULL);
DCHECK_GE(buffer_len, 0);
- DCHECK_NE(range->cached_buffer_ == NULL, mem_tracker == NULL);
+ DCHECK_NE(range->external_buffer_tag_ == ScanRange::ExternalBufferTag::NO_BUFFER,
+ mem_tracker == NULL);
reader_ = reader;
scan_range_ = range;
mem_tracker_ = mem_tracker;
@@ -244,6 +245,7 @@ void DiskIoMgr::BufferDescriptor::Reset(DiskIoRequestContext* reader,
void DiskIoMgr::BufferDescriptor::TransferOwnership(MemTracker* dst) {
DCHECK(dst != NULL);
+ DCHECK(!is_client_buffer());
// Memory of cached buffers is not tracked against a tracker.
if (is_cached()) return;
DCHECK(mem_tracker_ != NULL);
@@ -257,13 +259,12 @@ void DiskIoMgr::BufferDescriptor::Return() {
io_mgr_->ReturnBuffer(this);
}
-DiskIoMgr::WriteRange::WriteRange(const string& file, int64_t file_offset, int disk_id,
- WriteDoneCallback callback) {
+DiskIoMgr::WriteRange::WriteRange(
+ const string& file, int64_t file_offset, int disk_id, WriteDoneCallback callback)
+ : RequestRange(RequestType::WRITE), callback_(callback) {
file_ = file;
offset_ = file_offset;
disk_id_ = disk_id;
- callback_ = callback;
- request_type_ = RequestType::WRITE;
}
void DiskIoMgr::WriteRange::SetData(const uint8_t* buffer, int64_t len) {
@@ -360,9 +361,6 @@ DiskIoMgr::~DiskIoMgr() {
}
if (free_buffer_mem_tracker_ != NULL) free_buffer_mem_tracker_->UnregisterFromParent();
- if (unowned_buffer_mem_tracker_ != NULL) {
- unowned_buffer_mem_tracker_->UnregisterFromParent();
- }
if (cached_read_options_ != NULL) hadoopRzOptionsFree(cached_read_options_);
}
@@ -371,8 +369,6 @@ Status DiskIoMgr::Init(MemTracker* process_mem_tracker) {
DCHECK(process_mem_tracker != NULL);
free_buffer_mem_tracker_.reset(
new MemTracker(-1, "Free Disk IO Buffers", process_mem_tracker, false));
- unowned_buffer_mem_tracker_.reset(
- new MemTracker(-1, "Untracked Disk IO Buffers", process_mem_tracker, false));
// If we hit the process limit, see if we can reclaim some memory by removing
// previously allocated (but unused) io buffers.
process_mem_tracker->AddGcFunction(bind(&DiskIoMgr::GcIoBuffers, this));
@@ -573,6 +569,11 @@ Status DiskIoMgr::AddScanRanges(DiskIoRequestContext* reader,
return Status::OK();
}
+Status DiskIoMgr::AddScanRange(
+ DiskIoRequestContext* reader, ScanRange* range, bool schedule_immediately) {
+ return AddScanRanges(reader, vector<ScanRange*>({range}), schedule_immediately);
+}
+
// This function returns the next scan range the reader should work on, checking
// for eos and error cases. If there isn't already a cached scan range or a scan
// range prepared by the disk threads, the caller waits on the disk threads.
@@ -636,9 +637,11 @@ Status DiskIoMgr::Read(DiskIoRequestContext* reader,
DCHECK(buffer != NULL);
*buffer = NULL;
- if (range->len() > max_buffer_size_) {
- return Status(Substitute("Cannot perform sync read larger than $0. Request was $1",
- max_buffer_size_, range->len()));
+ if (range->len() > max_buffer_size_
+ && range->external_buffer_tag_ != ScanRange::ExternalBufferTag::CLIENT_BUFFER) {
+ return Status(Substitute("Internal error: cannot perform sync read of '$0' bytes "
+ "that is larger than the max read buffer size '$1'.",
+ range->len(), max_buffer_size_));
}
vector<DiskIoMgr::ScanRange*> ranges;
@@ -656,8 +659,8 @@ void DiskIoMgr::ReturnBuffer(BufferDescriptor* buffer_desc) {
DiskIoRequestContext* reader = buffer_desc->reader_;
if (buffer_desc->buffer_ != NULL) {
- if (!buffer_desc->is_cached()) {
- // Cached buffers are not allocated by DiskIoMgr so don't need to be freed.
+ if (!buffer_desc->is_cached() && !buffer_desc->is_client_buffer()) {
+ // Buffers the were not allocated by DiskIoMgr don't need to be freed.
FreeBufferMemory(buffer_desc);
}
num_buffers_in_readers_.Add(-1);
@@ -686,7 +689,7 @@ void DiskIoMgr::ReturnBufferDesc(BufferDescriptor* desc) {
}
DiskIoMgr::BufferDescriptor* DiskIoMgr::GetBufferDesc(DiskIoRequestContext* reader,
- MemTracker* mem_tracker, ScanRange* range, char* buffer, int64_t buffer_size) {
+ MemTracker* mem_tracker, ScanRange* range, uint8_t* buffer, int64_t buffer_size) {
BufferDescriptor* buffer_desc;
{
unique_lock<mutex> lock(free_buffers_lock_);
@@ -713,14 +716,10 @@ DiskIoMgr::BufferDescriptor* DiskIoMgr::GetFreeBuffer(DiskIoRequestContext* read
// Track memory against the reader. This is checked the next time we start
// a read for the next reader in DiskIoMgr::GetNextScanRange().
- // TODO: IMPALA-3200: BufferedBlockMgr does not expect read buffers to be tracked
- // against its MemTracker. Once BufferedBlockMgr is removed, we can expect that
- // all readers provide a MemTracker and remove this NULL check.
- MemTracker* buffer_mem_tracker = reader->mem_tracker_ != NULL ? reader->mem_tracker_ :
- unowned_buffer_mem_tracker_.get();
- buffer_mem_tracker->Consume(buffer_size);
-
- char* buffer = NULL;
+ DCHECK(reader->mem_tracker_ != NULL);
+ reader->mem_tracker_->Consume(buffer_size);
+
+ uint8_t* buffer = NULL;
{
unique_lock<mutex> lock(free_buffers_lock_);
if (free_buffers_[idx].empty()) {
@@ -732,7 +731,7 @@ DiskIoMgr::BufferDescriptor* DiskIoMgr::GetFreeBuffer(DiskIoRequestContext* read
ImpaladMetrics::IO_MGR_TOTAL_BYTES->Increment(buffer_size);
}
// We already tracked this memory against the reader's MemTracker.
- buffer = new char[buffer_size];
+ buffer = new uint8_t[buffer_size];
} else {
if (ImpaladMetrics::IO_MGR_NUM_UNUSED_BUFFERS != NULL) {
ImpaladMetrics::IO_MGR_NUM_UNUSED_BUFFERS->Increment(-1L);
@@ -747,7 +746,7 @@ DiskIoMgr::BufferDescriptor* DiskIoMgr::GetFreeBuffer(DiskIoRequestContext* read
DCHECK(range != NULL);
DCHECK(reader != NULL);
DCHECK(buffer != NULL);
- return GetBufferDesc(reader, buffer_mem_tracker, range, buffer, buffer_size);
+ return GetBufferDesc(reader, reader->mem_tracker_, range, buffer, buffer_size);
}
void DiskIoMgr::GcIoBuffers() {
@@ -755,7 +754,7 @@ void DiskIoMgr::GcIoBuffers() {
int buffers_freed = 0;
int bytes_freed = 0;
for (int idx = 0; idx < free_buffers_.size(); ++idx) {
- for (char* buffer: free_buffers_[idx]) {
+ for (uint8_t* buffer : free_buffers_[idx]) {
int64_t buffer_size = (1LL << idx) * min_buffer_size_;
delete[] buffer;
free_buffer_mem_tracker_->Release(buffer_size);
@@ -780,7 +779,8 @@ void DiskIoMgr::GcIoBuffers() {
void DiskIoMgr::FreeBufferMemory(BufferDescriptor* desc) {
DCHECK(!desc->is_cached());
- char* buffer = desc->buffer_;
+ DCHECK(!desc->is_client_buffer());
+ uint8_t* buffer = desc->buffer_;
int64_t buffer_size = desc->buffer_len_;
int idx = free_buffers_idx(buffer_size);
DCHECK_EQ(BitUtil::Ceil(buffer_size, min_buffer_size_) & ~(1LL << idx), 0)
@@ -1062,46 +1062,16 @@ void DiskIoMgr::ReadRange(DiskQueue* disk_queue, DiskIoRequestContext* reader,
ScanRange* range) {
int64_t bytes_remaining = range->len_ - range->bytes_read_;
DCHECK_GT(bytes_remaining, 0);
- int64_t buffer_size = ::min(bytes_remaining, static_cast<int64_t>(max_buffer_size_));
- bool enough_memory = true;
- if (reader->mem_tracker_ != NULL) {
- enough_memory = reader->mem_tracker_->SpareCapacity() > LOW_MEMORY;
- if (!enough_memory) {
- // Low memory, GC and try again.
- GcIoBuffers();
- enough_memory = reader->mem_tracker_->SpareCapacity() > LOW_MEMORY;
- }
- }
-
- if (!enough_memory) {
- DiskIoRequestContext::PerDiskState& state = reader->disk_states_[disk_queue->disk_id];
- unique_lock<mutex> reader_lock(reader->lock_);
-
- // Just grabbed the reader lock, check for cancellation.
- if (reader->state_ == DiskIoRequestContext::Cancelled) {
- DCHECK(reader->Validate()) << endl << reader->DebugString();
- state.DecrementRequestThreadAndCheckDone(reader);
- range->Cancel(reader->status_);
- DCHECK(reader->Validate()) << endl << reader->DebugString();
- return;
- }
-
- if (!range->ready_buffers_.empty()) {
- // We have memory pressure and this range doesn't need another buffer
- // (it already has one queued). Skip this range and pick it up later.
- range->blocked_on_queue_ = true;
- reader->blocked_ranges_.Enqueue(range);
- state.DecrementRequestThread();
- return;
- } else {
- // We need to get a buffer anyway since there are none queued. The query
- // is likely to fail due to mem limits but there's nothing we can do about that
- // now.
- }
+ BufferDescriptor* buffer_desc = NULL;
+ if (range->external_buffer_tag_ == ScanRange::ExternalBufferTag::CLIENT_BUFFER) {
+ buffer_desc = GetBufferDesc(
+ reader, NULL, range, range->client_buffer_.data, range->client_buffer_.len);
+ } else {
+ // Need to allocate a buffer to read into.
+ int64_t buffer_size = ::min(bytes_remaining, static_cast<int64_t>(max_buffer_size_));
+ buffer_desc = TryAllocateNextBufferForRange(disk_queue, reader, range, buffer_size);
+ if (buffer_desc == NULL) return;
}
-
- BufferDescriptor* buffer_desc = GetFreeBuffer(reader, range, buffer_size);
- DCHECK(buffer_desc != NULL);
reader->num_used_buffers_.Add(1);
// No locks in this section. Only working on local vars. We don't want to hold a
@@ -1119,8 +1089,8 @@ void DiskIoMgr::ReadRange(DiskQueue* disk_queue, DiskIoRequestContext* reader,
SCOPED_TIMER(&read_timer_);
SCOPED_TIMER(reader->read_timer_);
- buffer_desc->status_ = range->Read(buffer_desc->buffer_, &buffer_desc->len_,
- &buffer_desc->eosr_);
+ buffer_desc->status_ = range->Read(buffer_desc->buffer_, buffer_desc->buffer_len_,
+ &buffer_desc->len_, &buffer_desc->eosr_);
buffer_desc->scan_range_offset_ = range->bytes_read_ - buffer_desc->len_;
if (reader->bytes_read_counter_ != NULL) {
@@ -1137,6 +1107,48 @@ void DiskIoMgr::ReadRange(DiskQueue* disk_queue, DiskIoRequestContext* reader,
HandleReadFinished(disk_queue, reader, buffer_desc);
}
+DiskIoMgr::BufferDescriptor* DiskIoMgr::TryAllocateNextBufferForRange(
+ DiskQueue* disk_queue, DiskIoRequestContext* reader, ScanRange* range,
+ int64_t buffer_size) {
+ DCHECK(reader->mem_tracker_ != NULL);
+ bool enough_memory = reader->mem_tracker_->SpareCapacity() > LOW_MEMORY;
+ if (!enough_memory) {
+ // Low memory, GC and try again.
+ GcIoBuffers();
+ enough_memory = reader->mem_tracker_->SpareCapacity() > LOW_MEMORY;
+ }
+
+ if (!enough_memory) {
+ DiskIoRequestContext::PerDiskState& state = reader->disk_states_[disk_queue->disk_id];
+ unique_lock<mutex> reader_lock(reader->lock_);
+
+ // Just grabbed the reader lock, check for cancellation.
+ if (reader->state_ == DiskIoRequestContext::Cancelled) {
+ DCHECK(reader->Validate()) << endl << reader->DebugString();
+ state.DecrementRequestThreadAndCheckDone(reader);
+ range->Cancel(reader->status_);
+ DCHECK(reader->Validate()) << endl << reader->DebugString();
+ return NULL;
+ }
+
+ if (!range->ready_buffers_.empty()) {
+ // We have memory pressure and this range doesn't need another buffer
+ // (it already has one queued). Skip this range and pick it up later.
+ range->blocked_on_queue_ = true;
+ reader->blocked_ranges_.Enqueue(range);
+ state.DecrementRequestThread();
+ return NULL;
+ } else {
+ // We need to get a buffer anyway since there are none queued. The query
+ // is likely to fail due to mem limits but there's nothing we can do about that
+ // now.
+ }
+ }
+ BufferDescriptor* buffer_desc = GetFreeBuffer(reader, range, buffer_size);
+ DCHECK(buffer_desc != NULL);
+ return buffer_desc;
+}
+
void DiskIoMgr::Write(DiskIoRequestContext* writer_context, WriteRange* write_range) {
FILE* file_handle = fopen(write_range->file(), "rb+");
Status ret_status;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/120f34b0/be/src/runtime/disk-io-mgr.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr.h b/be/src/runtime/disk-io-mgr.h
index 0baac59..4b650a8 100644
--- a/be/src/runtime/disk-io-mgr.h
+++ b/be/src/runtime/disk-io-mgr.h
@@ -140,12 +140,15 @@ class MemTracker;
/// regardless of how many concurrent readers are running.
//
/// Buffer Management:
-/// Buffers are allocated by the IoMgr as necessary to service reads. These buffers
-/// are directly returned to the caller. The caller must call Return() on the buffer
-/// when it is done, at which point the buffer will be recycled for another read. In error
-/// cases, the IoMgr will recycle the buffers more promptly but regardless, the caller
-/// must always call Return()
-//
+/// Buffers for reads are either a) allocated by the IoMgr and transferred to the caller,
+/// b) cached HDFS buffers if the scan range uses HDFS caching, or c) provided by the
+/// caller when constructing the scan range.
+///
+/// As a caller reads from a scan range, these buffers are wrapped in BufferDescriptors
+/// and returned to the caller. The caller must always call Return() on the buffer
+/// descriptor when it when it is done to allow recycling of the buffer descriptor and
+/// the associated buffer (if there is an IoMgr-allocated or HDFS cached buffer).
+///
/// Caching support:
/// Scan ranges contain metadata on whether or not it is cached on the DN. In that
/// case, we use the HDFS APIs to read the cached data without doing any copies. For these
@@ -232,7 +235,7 @@ class DiskIoMgr {
class BufferDescriptor {
public:
ScanRange* scan_range() { return scan_range_; }
- char* buffer() { return buffer_; }
+ uint8_t* buffer() { return buffer_; }
int64_t buffer_len() { return buffer_len_; }
int64_t len() { return len_; }
bool eosr() { return eosr_; }
@@ -240,10 +243,11 @@ class DiskIoMgr {
/// Returns the offset within the scan range that this buffer starts at
int64_t scan_range_offset() const { return scan_range_offset_; }
- /// Transfer ownership of buffer memory from 'mem_tracker_' to 'dst' and
- /// set 'mem_tracker_' to 'dst'. 'mem_tracker_' and 'dst' must be non-NULL.
- /// Does not check memory limits on 'dst': the caller should check the memory limit
- /// if a different memory limit may apply to 'dst'.
+ /// Transfer ownership of buffer memory from 'mem_tracker_' to 'dst' and set
+ /// 'mem_tracker_' to 'dst'. 'mem_tracker_' and 'dst' must be non-NULL. Does not
+ /// check memory limits on 'dst': the caller should check the memory limit if a
+ /// different memory limit may apply to 'dst'. If the buffer was a client-provided
+ /// buffer, transferring is not allowed.
/// TODO: IMPALA-3209: revisit this as part of scanner memory usage revamp.
void TransferOwnership(MemTracker* dst);
@@ -257,14 +261,25 @@ class DiskIoMgr {
friend class DiskIoRequestContext;
BufferDescriptor(DiskIoMgr* io_mgr);
- bool is_cached() { return scan_range_->cached_buffer_ != NULL; }
+ /// Return true if this is a cached buffer owned by HDFS.
+ bool is_cached() const {
+ return scan_range_->external_buffer_tag_
+ == ScanRange::ExternalBufferTag::CACHED_BUFFER;
+ }
+
+ /// Return true if this is a buffer owner by the client that was provided when
+ /// constructing the scan range.
+ bool is_client_buffer() const {
+ return scan_range_->external_buffer_tag_
+ == ScanRange::ExternalBufferTag::CLIENT_BUFFER;
+ }
/// Reset the buffer descriptor to an uninitialized state.
void Reset();
/// Resets the buffer descriptor state for a new reader, range and data buffer.
/// The buffer memory should already be accounted against MemTracker
- void Reset(DiskIoRequestContext* reader, ScanRange* range, char* buffer,
+ void Reset(DiskIoRequestContext* reader, ScanRange* range, uint8_t* buffer,
int64_t buffer_len, MemTracker* mem_tracker);
DiskIoMgr* const io_mgr_;
@@ -280,7 +295,7 @@ class DiskIoMgr {
ScanRange* scan_range_;
/// buffer with the read contents
- char* buffer_;
+ uint8_t* buffer_;
/// length of buffer_. For buffers from cached reads, the length is 0.
int64_t buffer_len_;
@@ -318,6 +333,9 @@ class DiskIoMgr {
RequestType::type request_type() const { return request_type_; }
protected:
+ RequestRange(RequestType::type request_type)
+ : fs_(NULL), offset_(-1), len_(-1), disk_id_(-1), request_type_(request_type) {}
+
/// Hadoop filesystem that contains file_, or set to NULL for local filesystem.
hdfsFS fs_;
@@ -337,25 +355,76 @@ class DiskIoMgr {
RequestType::type request_type_;
};
+ /// Param struct for different combinations of buffering.
+ struct BufferOpts {
+ public:
+ // Set options for a read into an IoMgr-allocated or HDFS-cached buffer. Caching is
+ // enabled if 'try_cache' is true, the file is in the HDFS cache and 'mtime' matches
+ // the modified time of the cached file in the HDFS cache.
+ BufferOpts(bool try_cache, int64_t mtime)
+ : try_cache_(try_cache),
+ mtime_(mtime),
+ client_buffer_(NULL),
+ client_buffer_len_(-1) {}
+
+ /// Set options for an uncached read into an IoMgr-allocated buffer.
+ static BufferOpts Uncached() {
+ return BufferOpts(false, NEVER_CACHE, NULL, -1);
+ }
+
+ /// Set options to read the entire scan range into 'client_buffer'. The length of the
+ /// buffer, 'client_buffer_len', must fit the entire scan range. HDFS caching is not
+ /// enabled in this case.
+ static BufferOpts ReadInto(uint8_t* client_buffer, int64_t client_buffer_len) {
+ return BufferOpts(false, NEVER_CACHE, client_buffer, client_buffer_len);
+ }
+
+ private:
+ friend class ScanRange;
+
+ BufferOpts(
+ bool try_cache, int64_t mtime, uint8_t* client_buffer, int64_t client_buffer_len)
+ : try_cache_(try_cache),
+ mtime_(mtime),
+ client_buffer_(client_buffer),
+ client_buffer_len_(client_buffer_len) {}
+
+ /// If 'mtime_' is set to NEVER_CACHE, the file handle will never be cached, because
+ /// the modification time won't match.
+ const static int64_t NEVER_CACHE = -1;
+
+ /// If true, read from HDFS cache if possible.
+ const bool try_cache_;
+
+ /// Last modified time of the file associated with the scan range. If set to
+ /// NEVER_CACHE, caching is disabled.
+ const int64_t mtime_;
+
+ /// A destination buffer provided by the client, NULL and -1 if no buffer.
+ uint8_t* const client_buffer_;
+ const int64_t client_buffer_len_;
+ };
+
/// ScanRange description. The caller must call Reset() to initialize the fields
/// before calling AddScanRanges(). The private fields are used internally by
/// the IoMgr.
class ScanRange : public RequestRange {
public:
-
- /// If the mtime is set to NEVER_CACHE, the file handle should never be cached.
- const static int64_t NEVER_CACHE = -1;
-
/// The initial queue capacity for this. Specify -1 to use IoMgr default.
ScanRange(int initial_capacity = -1);
virtual ~ScanRange();
- /// Resets this scan range object with the scan range description. The scan range
- /// must fall within the file bounds (offset >= 0 and offset + len <= file_length).
- /// Resets this scan range object with the scan range description.
+ /// Resets this scan range object with the scan range description. The scan range
+ /// is for bytes [offset, offset + len) in 'file' on 'fs' (which is NULL for the
+ /// local filesystem). The scan range must fall within the file bounds (offset >= 0
+ /// and offset + len <= file_length). 'disk_id' is the disk queue to add the range
+ /// to. If 'expected_local' is true, a warning is generated if the read did not
+ /// come from a local disk. 'buffer_opts' specifies buffer management options -
+ /// see the DiskIoMgr class comment and the BufferOpts comments for details.
+ /// 'meta_data' is an arbitrary client-provided pointer for any auxiliary data.
void Reset(hdfsFS fs, const char* file, int64_t len, int64_t offset, int disk_id,
- bool try_cache, bool expected_local, int64_t mtime, void* metadata = NULL);
+ bool expected_local, const BufferOpts& buffer_opts, void* meta_data = NULL);
void* meta_data() const { return meta_data_; }
bool try_cache() const { return try_cache_; }
@@ -410,9 +479,9 @@ class DiskIoMgr {
/// Closes the file for this range. This function only modifies state in this range.
void Close();
- /// Reads from this range into 'buffer'. Buffer is preallocated. Returns the number
- /// of bytes read. Updates range to keep track of where in the file we are.
- Status Read(char* buffer, int64_t* bytes_read, bool* eosr);
+ /// Reads from this range into 'buffer', which has length 'buffer_len' bytes. Returns
+ /// the number of bytes read. The read position in this scan range is updated.
+ Status Read(uint8_t* buffer, int64_t buffer_len, int64_t* bytes_read, bool* eosr);
/// Reads from the DN cache. On success, sets cached_buffer_ to the DN buffer
/// and *read_succeeded to true.
@@ -450,9 +519,24 @@ class DiskIoMgr {
HdfsCachedFileHandle* hdfs_file_;
};
- /// If non-null, this is DN cached buffer. This means the cached read succeeded
- /// and all the bytes for the range are in this buffer.
- struct hadoopRzBuffer* cached_buffer_;
+ /// Tagged union that holds a buffer for the cases when there is a buffer allocated
+ /// externally from DiskIoMgr that is associated with the scan range.
+ enum class ExternalBufferTag { CLIENT_BUFFER, CACHED_BUFFER, NO_BUFFER };
+ ExternalBufferTag external_buffer_tag_;
+ union {
+ /// Valid if the 'external_buffer_tag_' is CLIENT_BUFFER.
+ struct {
+ /// Client-provided buffer to read the whole scan range into.
+ uint8_t* data;
+
+ /// Length of the client-provided buffer.
+ int64_t len;
+ } client_buffer_;
+
+ /// Valid and non-NULL if the external_buffer_tag_ is CACHED_BUFFER, which means
+ /// that a cached read succeeded and all the bytes for the range are in this buffer.
+ struct hadoopRzBuffer* cached_buffer_;
+ };
/// Lock protecting fields below.
/// This lock should not be taken during Open/Read/Close.
@@ -564,7 +648,7 @@ class DiskIoMgr {
/// the reader will be cancelled and MEM_LIMIT_EXCEEDED will be returned via
/// GetNext().
Status RegisterContext(DiskIoRequestContext** request_context,
- MemTracker* reader_mem_tracker = NULL);
+ MemTracker* reader_mem_tracker);
/// Unregisters context from the disk IoMgr. This must be called for every
/// RegisterContext() regardless of cancellation and must be called in the
@@ -590,8 +674,10 @@ class DiskIoMgr {
/// (i.e. the caller should not/cannot call GetNextRange for these ranges).
/// This can be used to do synchronous reads as well as schedule dependent ranges,
/// as in the case for columnar formats.
- Status AddScanRanges(DiskIoRequestContext* reader, const std::vector<ScanRange*>& ranges,
- bool schedule_immediately = false);
+ Status AddScanRanges(DiskIoRequestContext* reader,
+ const std::vector<ScanRange*>& ranges, bool schedule_immediately = false);
+ Status AddScanRange(
+ DiskIoRequestContext* reader, ScanRange* range, bool schedule_immediately = false);
/// Add a WriteRange for the writer. This is non-blocking and schedules the context
/// on the IoMgr disk queue. Does not create any files.
@@ -609,6 +695,8 @@ class DiskIoMgr {
/// is read. This can be called while there are outstanding ScanRanges and is
/// thread safe. Multiple threads can be calling Read() per reader at a time.
/// range *cannot* have already been added via AddScanRanges.
+ /// This can only be used if the scan range fits in a single IO buffer (i.e. is smaller
+ /// than max_read_buffer_size()) or if reading into a client-provided buffer.
Status Read(DiskIoRequestContext* reader, ScanRange* range, BufferDescriptor** buffer);
/// Determine which disk queue this file should be assigned to. Returns an index into
@@ -751,7 +839,7 @@ class DiskIoMgr {
/// free_buffers_[10] => list of free buffers with size 1 MB
/// free_buffers_[13] => list of free buffers with size 8 MB
/// free_buffers_[n] => list of free buffers with size 2^n * 1024 B
- std::vector<std::list<char*>> free_buffers_;
+ std::vector<std::list<uint8_t*>> free_buffers_;
/// List of free buffer desc objects that can be handed out to clients
std::list<BufferDescriptor*> free_buffer_descs_;
@@ -787,8 +875,8 @@ class DiskIoMgr {
/// Gets a BufferDescriptor initialized with the provided parameters. The object may be
/// recycled or newly allocated. Does not do anything aside from initialize the
/// descriptor's fields.
- BufferDescriptor* GetBufferDesc(DiskIoRequestContext* reader,
- MemTracker* mem_tracker, ScanRange* range, char* buffer, int64_t buffer_size);
+ BufferDescriptor* GetBufferDesc(DiskIoRequestContext* reader, MemTracker* mem_tracker,
+ ScanRange* range, uint8_t* buffer, int64_t buffer_size);
/// Returns the buffer desc and underlying buffer to the disk IoMgr. This also updates
/// the reader and disk queue state.
@@ -849,6 +937,13 @@ class DiskIoMgr {
/// Reads the specified scan range and calls HandleReadFinished when done.
void ReadRange(DiskQueue* disk_queue, DiskIoRequestContext* reader,
ScanRange* range);
+
+ /// Try to allocate the next buffer for the scan range, returning the new buffer
+ /// if successful. If 'reader' is cancelled, cancels the range and returns NULL.
+ /// If there is memory pressure and buffers are already queued, adds the range
+ /// to the blocked ranges and returns NULL.
+ BufferDescriptor* TryAllocateNextBufferForRange(DiskQueue* disk_queue,
+ DiskIoRequestContext* reader, ScanRange* range, int64_t buffer_size);
};
}
[26/50] [abbrv] incubator-impala git commit: IMPALA-1430,
IMPALA-4108: codegen all builtin aggregate functions
Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/partitioned-aggregation-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/partitioned-aggregation-node.cc b/be/src/exec/partitioned-aggregation-node.cc
index 17fbb6c..56db26f 100644
--- a/be/src/exec/partitioned-aggregation-node.cc
+++ b/be/src/exec/partitioned-aggregation-node.cc
@@ -17,21 +17,20 @@
#include "exec/partitioned-aggregation-node.h"
-#include <algorithm>
#include <math.h>
+#include <algorithm>
#include <set>
#include <sstream>
-#include <gutil/strings/substitute.h>
-#include <thrift/protocol/TDebugProtocol.h>
#include "codegen/codegen-anyval.h"
#include "codegen/llvm-codegen.h"
#include "exec/hash-table.inline.h"
#include "exprs/agg-fn-evaluator.h"
#include "exprs/anyval-util.h"
-#include "exprs/expr.h"
#include "exprs/expr-context.h"
+#include "exprs/expr.h"
#include "exprs/slot-ref.h"
+#include "gutil/strings/substitute.h"
#include "runtime/buffered-tuple-stream.inline.h"
#include "runtime/descriptors.h"
#include "runtime/mem-pool.h"
@@ -40,8 +39,8 @@
#include "runtime/row-batch.h"
#include "runtime/runtime-state.h"
#include "runtime/string-value.inline.h"
-#include "runtime/tuple.h"
#include "runtime/tuple-row.h"
+#include "runtime/tuple.h"
#include "udf/udf-internal.h"
#include "util/debug-util.h"
#include "util/runtime-profile-counters.h"
@@ -150,21 +149,20 @@ Status PartitionedAggregationNode::Init(const TPlanNode& tnode, RuntimeState* st
Expr::CreateExprTrees(pool_, tnode.agg_node.grouping_exprs, &grouping_expr_ctxs_));
for (int i = 0; i < tnode.agg_node.aggregate_functions.size(); ++i) {
AggFnEvaluator* evaluator;
- RETURN_IF_ERROR(AggFnEvaluator::Create(
- pool_, tnode.agg_node.aggregate_functions[i], &evaluator));
+ RETURN_IF_ERROR(
+ AggFnEvaluator::Create(pool_, tnode.agg_node.aggregate_functions[i], &evaluator));
aggregate_evaluators_.push_back(evaluator);
- ExprContext* agg_expr_ctx;
- if (evaluator->input_expr_ctxs().size() == 1) {
- agg_expr_ctx = evaluator->input_expr_ctxs()[0];
+ ExprContext* const* agg_expr_ctxs;
+ if (evaluator->input_expr_ctxs().size() > 0) {
+ agg_expr_ctxs = evaluator->input_expr_ctxs().data();
} else {
- // CodegenUpdateSlot() can only support aggregate operator with only one ExprContext
- // so it doesn't support operator such as group_concat. There are also aggregate
- // operators with no ExprContext (e.g. count(*)). In cases above, 'agg_expr_ctxs_'
- // will contain NULL for that entry.
+ // Some aggregate functions have no input expressions and therefore no ExprContext
+ // (e.g. count(*)). In those cases, 'agg_expr_ctxs_' will contain NULL for that
+ // entry.
DCHECK(evaluator->agg_op() == AggFnEvaluator::OTHER || evaluator->is_count_star());
- agg_expr_ctx = NULL;
+ agg_expr_ctxs = NULL;
}
- agg_expr_ctxs_.push_back(agg_expr_ctx);
+ agg_expr_ctxs_.push_back(agg_expr_ctxs);
}
return Status::OK();
}
@@ -1059,32 +1057,31 @@ void PartitionedAggregationNode::InitAggSlots(
intermediate_tuple_desc_->slots().begin() + grouping_expr_ctxs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++slot_desc) {
AggFnEvaluator* evaluator = aggregate_evaluators_[i];
+ // To minimize branching on the UpdateTuple path, initialize the result value so that
+ // the Add() UDA function can ignore the NULL bit of its destination value. E.g. for
+ // SUM(), if we initialize the destination value to 0 (with the NULL bit set), we can
+ // just start adding to the destination value (rather than repeatedly checking the
+ // destination NULL bit. The codegen'd version of UpdateSlot() exploits this to
+ // eliminate a branch per value.
+ //
+ // For boolean and numeric types, the default values are false/0, so the nullable
+ // aggregate functions SUM() and AVG() produce the correct result. For MIN()/MAX(),
+ // initialize the value to max/min possible value for the same effect.
evaluator->Init(agg_fn_ctxs[i], intermediate_tuple);
- // Codegen specific path for min/max.
- // To minimize branching on the UpdateTuple path, initialize the result value
- // so that UpdateTuple doesn't have to check if the aggregation
- // dst slot is null.
- // TODO: remove when we don't use the irbuilder for codegen here. This optimization
- // will no longer be necessary when all aggregates are implemented with the UDA
- // interface.
- if ((*slot_desc)->type().type != TYPE_STRING &&
- (*slot_desc)->type().type != TYPE_VARCHAR &&
- (*slot_desc)->type().type != TYPE_TIMESTAMP &&
- (*slot_desc)->type().type != TYPE_CHAR) {
+
+ AggFnEvaluator::AggregationOp agg_op = evaluator->agg_op();
+ if ((agg_op == AggFnEvaluator::MIN || agg_op == AggFnEvaluator::MAX)
+ && !evaluator->intermediate_type().IsStringType()
+ && !evaluator->intermediate_type().IsTimestampType()) {
ExprValue default_value;
void* default_value_ptr = NULL;
- switch (evaluator->agg_op()) {
- case AggFnEvaluator::MIN:
- default_value_ptr = default_value.SetToMax((*slot_desc)->type());
- RawValue::Write(default_value_ptr, intermediate_tuple, *slot_desc, NULL);
- break;
- case AggFnEvaluator::MAX:
- default_value_ptr = default_value.SetToMin((*slot_desc)->type());
- RawValue::Write(default_value_ptr, intermediate_tuple, *slot_desc, NULL);
- break;
- default:
- break;
+ if (evaluator->agg_op() == AggFnEvaluator::MIN) {
+ default_value_ptr = default_value.SetToMax((*slot_desc)->type());
+ } else {
+ DCHECK_EQ(evaluator->agg_op(), AggFnEvaluator::MAX);
+ default_value_ptr = default_value.SetToMin((*slot_desc)->type());
}
+ RawValue::Write(default_value_ptr, intermediate_tuple, *slot_desc, NULL);
}
}
}
@@ -1450,111 +1447,123 @@ Status PartitionedAggregationNode::QueryMaintenance(RuntimeState* state) {
// void UpdateSlot(FunctionContext* agg_fn_ctx, ExprContext* agg_expr_ctx,
// AggTuple* agg_tuple, char** row)
//
-// The IR for sum(double_col) is:
+// The IR for sum(double_col), which is constructed directly with the IRBuilder, is:
//
// define void @UpdateSlot(%"class.impala_udf::FunctionContext"* %agg_fn_ctx,
-// %"class.impala::ExprContext"* %agg_expr_ctx,
-// { i8, [7 x i8], double }* %agg_tuple,
-// %"class.impala::TupleRow"* %row) #34 {
-//
+// %"class.impala::ExprContext"** %agg_expr_ctxs,
+// { i8, [7 x i8], double }* %agg_tuple, %"class.impala::TupleRow"* %row) #34 {
// entry:
-// %src = call { i8, double } @GetSlotRef(%"class.impala::ExprContext"* %agg_expr_ctx,
-// %"class.impala::TupleRow"* %row)
-// %0 = extractvalue { i8, double } %src, 0
-// %is_null = trunc i8 %0 to i1
-// br i1 %is_null, label %ret, label %src_not_null
-//
-// src_not_null: ; preds = %entry
+// %expr_ctx_ptr = getelementptr %"class.impala::ExprContext"*,
+// %"class.impala::ExprContext"** %agg_expr_ctxs, i32 0
+// %expr_ctx = load %"class.impala::ExprContext"*,
+// %"class.impala::ExprContext"** %expr_ctx_ptr
+// %input0 = call { i8, double } @GetSlotRef(%"class.impala::ExprContext"* %expr_ctx,
+// %"class.impala::TupleRow"* %row)
// %dst_slot_ptr = getelementptr inbounds { i8, [7 x i8], double },
// { i8, [7 x i8], double }* %agg_tuple, i32 0, i32 2
-// call void @SetNotNull({ i8, [7 x i8], double }* %agg_tuple)
// %dst_val = load double, double* %dst_slot_ptr
-// %val = extractvalue { i8, double } %src, 1
+// %0 = extractvalue { i8, double } %input0, 0
+// %is_null = trunc i8 %0 to i1
+// br i1 %is_null, label %ret, label %not_null
+//
+// ret: ; preds = %not_null, %entry
+// ret void
+//
+// not_null: ; preds = %entry
+// %val = extractvalue { i8, double } %input0, 1
// %1 = fadd double %dst_val, %val
+// %2 = bitcast { i8, [7 x i8], double }* %agg_tuple to i8*
+// %null_byte_ptr = getelementptr i8, i8* %2, i32 0
+// %null_byte = load i8, i8* %null_byte_ptr
+// %null_bit_cleared = and i8 %null_byte, -2
+// store i8 %null_bit_cleared, i8* %null_byte_ptr
// store double %1, double* %dst_slot_ptr
// br label %ret
-//
-// ret: ; preds = %src_not_null, %entry
-// ret void
// }
//
-// The IR for ndv(double_col) is:
+// The IR for min(timestamp_col), which uses the UDA interface, is:
//
// define void @UpdateSlot(%"class.impala_udf::FunctionContext"* %agg_fn_ctx,
-// %"class.impala::ExprContext"* %agg_expr_ctx,
-// { i8, [7 x i8], %"struct.impala::StringValue" }* %agg_tuple,
-// %"class.impala::TupleRow"* %row) #34 {
+// %"class.impala::ExprContext"** %agg_expr_ctxs,
+// { i8, [7 x i8], %"class.impala::TimestampValue" }* %agg_tuple,
+// %"class.impala::TupleRow"* %row) #34 {
// entry:
-// %dst_lowered_ptr = alloca { i64, i8* }
-// %src_lowered_ptr = alloca { i8, double }
-// %src = call { i8, double } @GetSlotRef(%"class.impala::ExprContext"* %agg_expr_ctx,
-// %"class.impala::TupleRow"* %row)
-// %0 = extractvalue { i8, double } %src, 0
-// %is_null = trunc i8 %0 to i1
-// br i1 %is_null, label %ret, label %src_not_null
-//
-// src_not_null: ; preds = %entry
-// %dst_slot_ptr = getelementptr inbounds { i8, [7 x i8], %"struct.impala::StringValue" },
-// { i8, [7 x i8], %"struct.impala::StringValue" }* %agg_tuple, i32 0, i32 2
-// call void @SetNotNull({ i8, [7 x i8], %"struct.impala::StringValue" }* %agg_tuple)
-// %dst_val =
-// load %"struct.impala::StringValue", %"struct.impala::StringValue"* %dst_slot_ptr
-// store { i8, double } %src, { i8, double }* %src_lowered_ptr
-// %src_unlowered_ptr =
-// bitcast { i8, double }* %src_lowered_ptr to %"struct.impala_udf::DoubleVal"*
-// %ptr = extractvalue %"struct.impala::StringValue" %dst_val, 0
-// %dst = insertvalue { i64, i8* } zeroinitializer, i8* %ptr, 1
-// %len = extractvalue %"struct.impala::StringValue" %dst_val, 1
-// %1 = extractvalue { i64, i8* } %dst, 0
-// %2 = zext i32 %len to i64
-// %3 = shl i64 %2, 32
-// %4 = and i64 %1, 4294967295
-// %5 = or i64 %4, %3
-// %dst1 = insertvalue { i64, i8* } %dst, i64 %5, 0
-// store { i64, i8* } %dst1, { i64, i8* }* %dst_lowered_ptr
-// %dst_unlowered_ptr =
-// bitcast { i64, i8* }* %dst_lowered_ptr to %"struct.impala_udf::StringVal"*
-// call void @HllUpdate(%"class.impala_udf::FunctionContext"* %agg_fn_ctx,
-// %"struct.impala_udf::DoubleVal"* %src_unlowered_ptr,
-// %"struct.impala_udf::StringVal"* %dst_unlowered_ptr)
-// %anyval_result = load { i64, i8* }, { i64, i8* }* %dst_lowered_ptr
-// %6 = extractvalue { i64, i8* } %anyval_result, 0
-// %7 = ashr i64 %6, 32
-// %8 = trunc i64 %7 to i32
-// %9 = insertvalue %"struct.impala::StringValue" zeroinitializer, i32 %8, 1
-// %10 = extractvalue { i64, i8* } %anyval_result, 1
-// %11 = insertvalue %"struct.impala::StringValue" %9, i8* %10, 0
-// store %"struct.impala::StringValue" %11, %"struct.impala::StringValue"* %dst_slot_ptr
+// %dst_lowered_ptr = alloca { i64, i64 }
+// %input_lowered_ptr = alloca { i64, i64 }
+// %expr_ctx_ptr = getelementptr %"class.impala::ExprContext"*,
+// %"class.impala::ExprContext"** %agg_expr_ctxs, i32 0
+// %expr_ctx = load %"class.impala::ExprContext"*,
+// %"class.impala::ExprContext"** %expr_ctx_ptr
+// %input0 = call { i64, i64 } @GetSlotRef(%"class.impala::ExprContext"* %expr_ctx,
+// %"class.impala::TupleRow"* %row)
+// %dst_slot_ptr = getelementptr inbounds { i8, [7 x i8],
+// %"class.impala::TimestampValue" }, { i8, [7 x i8],
+// %"class.impala::TimestampValue" }* %agg_tuple, i32 0, i32 2
+// %dst_val = load %"class.impala::TimestampValue",
+// %"class.impala::TimestampValue"* %dst_slot_ptr
+// %0 = bitcast { i8, [7 x i8], %"class.impala::TimestampValue" }* %agg_tuple to i8*
+// %null_byte_ptr = getelementptr i8, i8* %0, i32 0
+// %null_byte = load i8, i8* %null_byte_ptr
+// %null_mask = and i8 %null_byte, 1
+// %is_null = icmp ne i8 %null_mask, 0
+// %is_null_ext = zext i1 %is_null to i64
+// %1 = or i64 0, %is_null_ext
+// %dst = insertvalue { i64, i64 } zeroinitializer, i64 %1, 0
+// %time_of_day = extractvalue %"class.impala::TimestampValue" %dst_val, 0, 0, 0, 0
+// %dst1 = insertvalue { i64, i64 } %dst, i64 %time_of_day, 1
+// %date = extractvalue %"class.impala::TimestampValue" %dst_val, 1, 0, 0
+// %2 = extractvalue { i64, i64 } %dst1, 0
+// %3 = zext i32 %date to i64
+// %4 = shl i64 %3, 32
+// %5 = and i64 %2, 4294967295
+// %6 = or i64 %5, %4
+// %dst2 = insertvalue { i64, i64 } %dst1, i64 %6, 0
+// store { i64, i64 } %input0, { i64, i64 }* %input_lowered_ptr
+// %input_unlowered_ptr = bitcast { i64, i64 }* %input_lowered_ptr
+// to %"struct.impala_udf::TimestampVal"*
+// store { i64, i64 } %dst2, { i64, i64 }* %dst_lowered_ptr
+// %dst_unlowered_ptr = bitcast { i64, i64 }* %dst_lowered_ptr
+// to %"struct.impala_udf::TimestampVal"*
+// call void
+// @_ZN6impala18AggregateFunctions3MinIN10impala_udf12TimestampValEEEvPNS2_15FunctionContextERKT_PS6_.2(
+// %"class.impala_udf::FunctionContext"* %agg_fn_ctx,
+// %"struct.impala_udf::TimestampVal"* %input_unlowered_ptr,
+// %"struct.impala_udf::TimestampVal"* %dst_unlowered_ptr)
+// %anyval_result = load { i64, i64 }, { i64, i64 }* %dst_lowered_ptr
+// %7 = extractvalue { i64, i64 } %anyval_result, 1
+// %8 = insertvalue %"class.impala::TimestampValue" zeroinitializer, i64 %7, 0, 0, 0, 0
+// %9 = extractvalue { i64, i64 } %anyval_result, 0
+// %10 = ashr i64 %9, 32
+// %11 = trunc i64 %10 to i32
+// %12 = insertvalue %"class.impala::TimestampValue" %8, i32 %11, 1, 0, 0
+// %13 = extractvalue { i64, i64 } %anyval_result, 0
+// %result_is_null = trunc i64 %13 to i1
+// %14 = bitcast { i8, [7 x i8], %"class.impala::TimestampValue" }* %agg_tuple to i8*
+// %null_byte_ptr3 = getelementptr i8, i8* %14, i32 0
+// %null_byte4 = load i8, i8* %null_byte_ptr3
+// %null_bit_cleared = and i8 %null_byte4, -2
+// %15 = sext i1 %result_is_null to i8
+// %null_bit = and i8 %15, 1
+// %null_bit_set = or i8 %null_bit_cleared, %null_bit
+// store i8 %null_bit_set, i8* %null_byte_ptr3
+// store %"class.impala::TimestampValue" %12,
+// %"class.impala::TimestampValue"* %dst_slot_ptr
// br label %ret
//
-// ret: ; preds = %src_not_null, %entry
+// ret: ; preds = %entry
// ret void
// }
+//
Status PartitionedAggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
AggFnEvaluator* evaluator, SlotDescriptor* slot_desc, Function** fn) {
- // TODO: Fix this DCHECK and Init() once CodegenUpdateSlot() can handle AggFnEvaluator
- // with multiple input expressions (e.g. group_concat).
- DCHECK_EQ(evaluator->input_expr_ctxs().size(), 1);
- ExprContext* agg_expr_ctx = evaluator->input_expr_ctxs()[0];
- Expr* agg_expr = agg_expr_ctx->root();
-
- // TODO: implement timestamp
- if (agg_expr->type().type == TYPE_TIMESTAMP &&
- evaluator->agg_op() != AggFnEvaluator::AVG) {
- return Status("PartitionedAggregationNode::CodegenUpdateSlot(): timestamp input type "
- "NYI");
- }
-
- Function* agg_expr_fn;
- RETURN_IF_ERROR(agg_expr->GetCodegendComputeFn(codegen, &agg_expr_fn));
-
PointerType* fn_ctx_type =
codegen->GetPtrType(FunctionContextImpl::LLVM_FUNCTIONCONTEXT_NAME);
- PointerType* expr_ctx_type = codegen->GetPtrType(ExprContext::LLVM_CLASS_NAME);
+ PointerType* expr_ctxs_type =
+ codegen->GetPtrPtrType(codegen->GetType(ExprContext::LLVM_CLASS_NAME));
StructType* tuple_struct = intermediate_tuple_desc_->GetLlvmStruct(codegen);
if (tuple_struct == NULL) {
return Status("PartitionedAggregationNode::CodegenUpdateSlot(): failed to generate "
- "intermediate tuple desc");
+ "intermediate tuple desc");
}
PointerType* tuple_ptr_type = codegen->GetPtrType(tuple_struct);
PointerType* tuple_row_ptr_type = codegen->GetPtrType(TupleRow::LLVM_CLASS_NAME);
@@ -1562,129 +1571,129 @@ Status PartitionedAggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
// Create UpdateSlot prototype
LlvmCodeGen::FnPrototype prototype(codegen, "UpdateSlot", codegen->void_type());
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_fn_ctx", fn_ctx_type));
- prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_expr_ctx", expr_ctx_type));
+ prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_expr_ctxs", expr_ctxs_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_tuple", tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[4];
*fn = prototype.GeneratePrototype(&builder, &args[0]);
Value* agg_fn_ctx_arg = args[0];
- Value* agg_expr_ctx_arg = args[1];
+ Value* agg_expr_ctxs_arg = args[1];
Value* agg_tuple_arg = args[2];
Value* row_arg = args[3];
- BasicBlock* src_not_null_block =
- BasicBlock::Create(codegen->context(), "src_not_null", *fn);
- BasicBlock* ret_block = BasicBlock::Create(codegen->context(), "ret", *fn);
-
- // Call expr function to get src slot value
- Value* agg_expr_fn_args[] = { agg_expr_ctx_arg, row_arg };
- CodegenAnyVal src = CodegenAnyVal::CreateCallWrapped(
- codegen, &builder, agg_expr->type(), agg_expr_fn, agg_expr_fn_args, "src");
+ DCHECK_GE(evaluator->input_expr_ctxs().size(), 1);
+ vector<CodegenAnyVal> input_vals;
+ for (int i = 0; i < evaluator->input_expr_ctxs().size(); ++i) {
+ ExprContext* agg_expr_ctx = evaluator->input_expr_ctxs()[i];
+ Expr* agg_expr = agg_expr_ctx->root();
+ Function* agg_expr_fn;
+ RETURN_IF_ERROR(agg_expr->GetCodegendComputeFn(codegen, &agg_expr_fn));
+ DCHECK(agg_expr_fn != NULL);
+
+ // Call expr function with the matching expr context to get src slot value.
+ Value* expr_ctx_ptr = builder.CreateInBoundsGEP(
+ agg_expr_ctxs_arg, codegen->GetIntConstant(TYPE_INT, i), "expr_ctx_ptr");
+ Value* expr_ctx = builder.CreateLoad(expr_ctx_ptr, "expr_ctx");
+ string input_name = Substitute("input$0", i);
+ input_vals.push_back(
+ CodegenAnyVal::CreateCallWrapped(codegen, &builder, agg_expr->type(), agg_expr_fn,
+ ArrayRef<Value*>({expr_ctx, row_arg}), input_name.c_str()));
+ }
+
+ AggFnEvaluator::AggregationOp agg_op = evaluator->agg_op();
+ const ColumnType& dst_type = evaluator->intermediate_type();
+ bool dst_is_int_or_float_or_bool = dst_type.IsIntegerType()
+ || dst_type.IsFloatingPointType() || dst_type.IsBooleanType();
+ bool dst_is_numeric_or_bool = dst_is_int_or_float_or_bool || dst_type.IsDecimalType();
- Value* src_is_null = src.GetIsNull();
- builder.CreateCondBr(src_is_null, ret_block, src_not_null_block);
+ BasicBlock* ret_block = BasicBlock::Create(codegen->context(), "ret", *fn);
- // Src slot is not null, update dst_slot
- builder.SetInsertPoint(src_not_null_block);
- Value* dst_ptr = builder.CreateStructGEP(NULL, agg_tuple_arg, slot_desc->llvm_field_idx(),
- "dst_slot_ptr");
+ // Emit the code to compute 'result' and set the NULL indicator if needed. First check
+ // for special cases where we can emit a very simple instruction sequence, then fall
+ // back to the general-purpose approach of calling the cross-compiled builtin UDA.
+ CodegenAnyVal& src = input_vals[0];
+ // 'dst_slot_ptr' points to the slot in the aggregate tuple to update.
+ Value* dst_slot_ptr = builder.CreateStructGEP(
+ NULL, agg_tuple_arg, slot_desc->llvm_field_idx(), "dst_slot_ptr");
Value* result = NULL;
-
- if (slot_desc->is_nullable()) {
- // Dst is NULL, just update dst slot to src slot and clear null bit
- Function* clear_null_fn = slot_desc->GetUpdateNullFn(codegen, false);
- builder.CreateCall(clear_null_fn, ArrayRef<Value*>({agg_tuple_arg}));
- }
-
- // Update the slot
- Value* dst_value = builder.CreateLoad(dst_ptr, "dst_val");
- switch (evaluator->agg_op()) {
- case AggFnEvaluator::COUNT:
- if (evaluator->is_merge()) {
- result = builder.CreateAdd(dst_value, src.GetVal(), "count_sum");
- } else {
- result = builder.CreateAdd(dst_value,
- codegen->GetIntConstant(TYPE_BIGINT, 1), "count_inc");
- }
- break;
- case AggFnEvaluator::MIN: {
- Function* min_fn = codegen->CodegenMinMax(slot_desc->type(), true);
- Value* min_args[] = { dst_value, src.GetVal() };
- result = builder.CreateCall(min_fn, min_args, "min_value");
- break;
+ Value* dst_value = builder.CreateLoad(dst_slot_ptr, "dst_val");
+ if (agg_op == AggFnEvaluator::COUNT) {
+ src.CodegenBranchIfNull(&builder, ret_block);
+ if (evaluator->is_merge()) {
+ result = builder.CreateAdd(dst_value, src.GetVal(), "count_sum");
+ } else {
+ result = builder.CreateAdd(
+ dst_value, codegen->GetIntConstant(TYPE_BIGINT, 1), "count_inc");
}
- case AggFnEvaluator::MAX: {
- Function* max_fn = codegen->CodegenMinMax(slot_desc->type(), false);
- Value* max_args[] = { dst_value, src.GetVal() };
- result = builder.CreateCall(max_fn, max_args, "max_value");
- break;
+ DCHECK(!slot_desc->is_nullable());
+ } else if ((agg_op == AggFnEvaluator::MIN || agg_op == AggFnEvaluator::MAX)
+ && dst_is_numeric_or_bool) {
+ bool is_min = agg_op == AggFnEvaluator::MIN;
+ src.CodegenBranchIfNull(&builder, ret_block);
+ Function* min_max_fn = codegen->CodegenMinMax(slot_desc->type(), is_min);
+ Value* min_max_args[] = {dst_value, src.GetVal()};
+ result =
+ builder.CreateCall(min_max_fn, min_max_args, is_min ? "min_value" : "max_value");
+ // Dst may have been NULL, make sure to unset the NULL bit.
+ DCHECK(slot_desc->is_nullable());
+ slot_desc->CodegenSetNullIndicator(
+ codegen, &builder, agg_tuple_arg, codegen->false_value());
+ } else if (agg_op == AggFnEvaluator::SUM && dst_is_int_or_float_or_bool) {
+ src.CodegenBranchIfNull(&builder, ret_block);
+ if (dst_type.IsFloatingPointType()) {
+ result = builder.CreateFAdd(dst_value, src.GetVal());
+ } else {
+ result = builder.CreateAdd(dst_value, src.GetVal());
}
- case AggFnEvaluator::SUM:
- if (slot_desc->type().type != TYPE_DECIMAL) {
- if (slot_desc->type().type == TYPE_FLOAT ||
- slot_desc->type().type == TYPE_DOUBLE) {
- result = builder.CreateFAdd(dst_value, src.GetVal());
- } else {
- result = builder.CreateAdd(dst_value, src.GetVal());
- }
- break;
+ // Dst may have been NULL, make sure to unset the NULL bit.
+ DCHECK(slot_desc->is_nullable());
+ slot_desc->CodegenSetNullIndicator(
+ codegen, &builder, agg_tuple_arg, codegen->false_value());
+ } else {
+ // The remaining cases are implemented using the UDA interface.
+ // Create intermediate argument 'dst' from 'dst_value'
+ CodegenAnyVal dst = CodegenAnyVal::GetNonNullVal(codegen, &builder, dst_type, "dst");
+
+ // For a subset of builtins we generate a different code sequence that exploits two
+ // properties of the builtins. First, NULL input values can be skipped. Second, the
+ // value of the slot was initialized in the right way in InitAggSlots() (e.g. 0 for
+ // SUM) that we get the right result if UpdateSlot() pretends that the NULL bit of
+ // 'dst' is unset. Empirically this optimisation makes TPC-H Q1 5-10% faster.
+ bool special_null_handling = !evaluator->intermediate_type().IsStringType()
+ && !evaluator->intermediate_type().IsTimestampType()
+ && (agg_op == AggFnEvaluator::MIN || agg_op == AggFnEvaluator::MAX
+ || agg_op == AggFnEvaluator::SUM || agg_op == AggFnEvaluator::AVG
+ || agg_op == AggFnEvaluator::NDV);
+ if (slot_desc->is_nullable()) {
+ if (special_null_handling) {
+ src.CodegenBranchIfNull(&builder, ret_block);
+ slot_desc->CodegenSetNullIndicator(
+ codegen, &builder, agg_tuple_arg, codegen->false_value());
+ } else {
+ dst.SetIsNull(slot_desc->CodegenIsNull(codegen, &builder, agg_tuple_arg));
}
- DCHECK_EQ(slot_desc->type().type, TYPE_DECIMAL);
- // Fall through to xcompiled case
- case AggFnEvaluator::AVG:
- case AggFnEvaluator::NDV: {
- // Get xcompiled update/merge function from IR module
- const string& symbol = evaluator->is_merge() ?
- evaluator->merge_symbol() : evaluator->update_symbol();
- const ColumnType& dst_type = evaluator->intermediate_type();
- Function* ir_fn = codegen->GetFunction(symbol);
- DCHECK(ir_fn != NULL);
-
- // Clone and replace constants.
- ir_fn = codegen->CloneFunction(ir_fn);
- vector<FunctionContext::TypeDesc> arg_types;
- arg_types.push_back(AnyValUtil::ColumnTypeToTypeDesc(agg_expr->type()));
- Expr::InlineConstants(AnyValUtil::ColumnTypeToTypeDesc(dst_type), arg_types,
- codegen, ir_fn);
-
- // Create pointer to src to pass to ir_fn. We must use the unlowered type.
- Value* src_lowered_ptr = codegen->CreateEntryBlockAlloca(
- *fn, LlvmCodeGen::NamedVariable("src_lowered_ptr", src.value()->getType()));
- builder.CreateStore(src.value(), src_lowered_ptr);
- Type* unlowered_ptr_type =
- CodegenAnyVal::GetUnloweredPtrType(codegen, agg_expr->type());
- Value* src_unlowered_ptr =
- builder.CreateBitCast(src_lowered_ptr, unlowered_ptr_type, "src_unlowered_ptr");
-
- // Create intermediate argument 'dst' from 'dst_value'
- CodegenAnyVal dst = CodegenAnyVal::GetNonNullVal(
- codegen, &builder, dst_type, "dst");
- dst.SetFromRawValue(dst_value);
- // Create pointer to dst to pass to ir_fn. We must use the unlowered type.
- Value* dst_lowered_ptr = codegen->CreateEntryBlockAlloca(
- *fn, LlvmCodeGen::NamedVariable("dst_lowered_ptr", dst.value()->getType()));
- builder.CreateStore(dst.value(), dst_lowered_ptr);
- unlowered_ptr_type = CodegenAnyVal::GetUnloweredPtrType(codegen, dst_type);
- Value* dst_unlowered_ptr =
- builder.CreateBitCast(dst_lowered_ptr, unlowered_ptr_type, "dst_unlowered_ptr");
-
- // Call 'ir_fn'
- builder.CreateCall(ir_fn,
- ArrayRef<Value*>({agg_fn_ctx_arg, src_unlowered_ptr, dst_unlowered_ptr}));
-
- // Convert StringVal intermediate 'dst_arg' back to StringValue
- Value* anyval_result = builder.CreateLoad(dst_lowered_ptr, "anyval_result");
- result = CodegenAnyVal(codegen, &builder, dst_type, anyval_result).ToNativeValue();
- break;
}
- default:
- DCHECK(false) << "bad aggregate operator: " << evaluator->agg_op();
+ dst.SetFromRawValue(dst_value);
+
+ // Call the UDA to update/merge 'src' into 'dst', with the result stored in
+ // 'updated_dst_val'.
+ CodegenAnyVal updated_dst_val;
+ RETURN_IF_ERROR(CodegenCallUda(
+ codegen, &builder, evaluator, agg_fn_ctx_arg, input_vals, dst, &updated_dst_val));
+ result = updated_dst_val.ToNativeValue();
+
+ if (slot_desc->is_nullable() && !special_null_handling) {
+ // Set NULL bit in the slot based on the return value.
+ Value* result_is_null = updated_dst_val.GetIsNull("result_is_null");
+ slot_desc->CodegenSetNullIndicator(
+ codegen, &builder, agg_tuple_arg, result_is_null);
+ }
}
// TODO: Store to register in the loop and store once to memory at the end of the loop.
- builder.CreateStore(result, dst_ptr);
+ builder.CreateStore(result, dst_slot_ptr);
builder.CreateBr(ret_block);
builder.SetInsertPoint(ret_block);
@@ -1698,6 +1707,58 @@ Status PartitionedAggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
return Status::OK();
}
+Status PartitionedAggregationNode::CodegenCallUda(LlvmCodeGen* codegen,
+ LlvmBuilder* builder, AggFnEvaluator* evaluator, Value* agg_fn_ctx,
+ const vector<CodegenAnyVal>& input_vals, const CodegenAnyVal& dst,
+ CodegenAnyVal* updated_dst_val) {
+ DCHECK_EQ(evaluator->input_expr_ctxs().size(), input_vals.size());
+ const string& symbol =
+ evaluator->is_merge() ? evaluator->merge_symbol() : evaluator->update_symbol();
+ const ColumnType& dst_type = evaluator->intermediate_type();
+
+ // TODO: to support actual UDAs, not just builtin functions using the UDA interface,
+ // we need to load the function at this point.
+ Function* uda_fn = codegen->GetFunction(symbol, true);
+ DCHECK(uda_fn != NULL);
+
+ vector<FunctionContext::TypeDesc> arg_types;
+ for (int i = 0; i < evaluator->input_expr_ctxs().size(); ++i) {
+ arg_types.push_back(AnyValUtil::ColumnTypeToTypeDesc(
+ evaluator->input_expr_ctxs()[i]->root()->type()));
+ }
+ Expr::InlineConstants(
+ AnyValUtil::ColumnTypeToTypeDesc(dst_type), arg_types, codegen, uda_fn);
+
+ // Set up arguments for call to UDA, which are the FunctionContext*, followed by
+ // pointers to all input values, followed by a pointer to the destination value.
+ vector<Value*> uda_fn_args;
+ uda_fn_args.push_back(agg_fn_ctx);
+
+ // Create pointers to input args to pass to uda_fn. We must use the unlowered type,
+ // e.g. IntVal, because the UDA interface expects the values to be passed as const
+ // references to the classes.
+ for (int i = 0; i < evaluator->input_expr_ctxs().size(); ++i) {
+ uda_fn_args.push_back(input_vals[i].GetUnloweredPtr("input_unlowered_ptr"));
+ }
+
+ // Create pointer to dst to pass to uda_fn. We must use the unlowered type for the
+ // same reason as above.
+ Value* dst_lowered_ptr = dst.GetLoweredPtr("dst_lowered_ptr");
+ Type* dst_unlowered_ptr_type = CodegenAnyVal::GetUnloweredPtrType(codegen, dst_type);
+ Value* dst_unlowered_ptr = builder->CreateBitCast(
+ dst_lowered_ptr, dst_unlowered_ptr_type, "dst_unlowered_ptr");
+ uda_fn_args.push_back(dst_unlowered_ptr);
+
+ // Call 'uda_fn'
+ builder->CreateCall(uda_fn, uda_fn_args);
+
+ // Convert intermediate 'dst_arg' back to the native type.
+ Value* anyval_result = builder->CreateLoad(dst_lowered_ptr, "anyval_result");
+
+ *updated_dst_val = CodegenAnyVal(codegen, builder, dst_type, anyval_result);
+ return Status::OK();
+}
+
// IR codegen for the UpdateTuple loop. This loop is query specific and based on the
// aggregate functions. The function signature must match the non- codegen'd UpdateTuple
// exactly.
@@ -1706,78 +1767,60 @@ Status PartitionedAggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
//
// ; Function Attrs: alwaysinline
// define void @UpdateTuple(%"class.impala::PartitionedAggregationNode"* %this_ptr,
-// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs,
-// %"class.impala::Tuple"* %tuple,
-// %"class.impala::TupleRow"* %row,
-// i1 %is_merge) #34 {
+// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs, %"class.impala::Tuple"*
+// %tuple,
+// %"class.impala::TupleRow"* %row, i1 %is_merge) #34 {
// entry:
// %tuple1 =
-// bitcast %"class.impala::Tuple"* %tuple to { i8, [7 x i8], i64, i64, double }*
+// bitcast %"class.impala::Tuple"* %tuple to { i8, [7 x i8], i64, i64, double }*
// %src_slot = getelementptr inbounds { i8, [7 x i8], i64, i64, double },
-// { i8, [7 x i8], i64, i64, double }* %tuple1, i32 0, i32 2
+// { i8, [7 x i8], i64, i64, double }* %tuple1, i32 0, i32 2
// %count_star_val = load i64, i64* %src_slot
// %count_star_inc = add i64 %count_star_val, 1
// store i64 %count_star_inc, i64* %src_slot
// %0 = getelementptr %"class.impala_udf::FunctionContext"*,
-// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs, i32 1
+// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs, i32 1
// %agg_fn_ctx = load %"class.impala_udf::FunctionContext"*,
-// %"class.impala_udf::FunctionContext"** %0
-// %1 = call %"class.impala::ExprContext"*
-// @_ZNK6impala26PartitionedAggregationNode17GetAggExprContextEi(
-// %"class.impala::PartitionedAggregationNode"* %this_ptr, i32 1)
+// %"class.impala_udf::FunctionContext"** %0
+// %1 = call %"class.impala::ExprContext"**
+// @_ZNK6impala26PartitionedAggregationNode18GetAggExprContextsEi(
+// %"class.impala::PartitionedAggregationNode"* %this_ptr, i32 1)
// call void @UpdateSlot(%"class.impala_udf::FunctionContext"* %agg_fn_ctx,
-// %"class.impala::ExprContext"* %1,
-// { i8, [7 x i8], i64, i64, double }* %tuple1,
-// %"class.impala::TupleRow"* %row)
+// %"class.impala::ExprContext"** %1, { i8, [7 x i8], i64, i64, double }* %tuple1,
+// %"class.impala::TupleRow"* %row)
// %2 = getelementptr %"class.impala_udf::FunctionContext"*,
-// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs, i32 2
+// %"class.impala_udf::FunctionContext"** %agg_fn_ctxs, i32 2
// %agg_fn_ctx2 = load %"class.impala_udf::FunctionContext"*,
-// %"class.impala_udf::FunctionContext"** %2
-// %3 = call %"class.impala::ExprContext"*
-// @_ZNK6impala26PartitionedAggregationNode17GetAggExprContextEi(
-// %"class.impala::PartitionedAggregationNode"* %this_ptr, i32 2)
-// call void @UpdateSlot.3(%"class.impala_udf::FunctionContext"* %agg_fn_ctx2,
-// %"class.impala::ExprContext"* %3,
-// { i8, [7 x i8], i64, i64, double }* %tuple1,
-// %"class.impala::TupleRow"* %row)
+// %"class.impala_udf::FunctionContext"** %2
+// %3 = call %"class.impala::ExprContext"**
+// @_ZNK6impala26PartitionedAggregationNode18GetAggExprContextsEi(
+// %"class.impala::PartitionedAggregationNode"* %this_ptr, i32 2)
+// call void @UpdateSlot.4(%"class.impala_udf::FunctionContext"* %agg_fn_ctx2,
+// %"class.impala::ExprContext"** %3, { i8, [7 x i8], i64, i64, double }* %tuple1,
+// %"class.impala::TupleRow"* %row)
// ret void
// }
-Status PartitionedAggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen,
- Function** fn) {
+Status PartitionedAggregationNode::CodegenUpdateTuple(
+ LlvmCodeGen* codegen, Function** fn) {
SCOPED_TIMER(codegen->codegen_timer());
- int j = grouping_expr_ctxs_.size();
- for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
- SlotDescriptor* slot_desc = intermediate_tuple_desc_->slots()[j];
- AggFnEvaluator* evaluator = aggregate_evaluators_[i];
-
- // Don't codegen things that aren't builtins (for now)
- if (!evaluator->is_builtin()) {
- return Status("PartitionedAggregationNode::CodegenUpdateTuple(): UDA codegen NYI");
- }
-
- bool supported = true;
- AggFnEvaluator::AggregationOp op = evaluator->agg_op();
- PrimitiveType type = slot_desc->type().type;
- // Char and timestamp intermediates aren't supported
- if (type == TYPE_TIMESTAMP || type == TYPE_CHAR) supported = false;
- // Only AVG and NDV support string intermediates
- if ((type == TYPE_STRING || type == TYPE_VARCHAR) &&
- !(op == AggFnEvaluator::AVG || op == AggFnEvaluator::NDV)) {
- supported = false;
- }
- if (!supported) {
- stringstream ss;
- ss << "Could not codegen PartitionedAggregationNode::UpdateTuple because "
- << "intermediate type " << slot_desc->type() << " is not yet supported for "
- << "aggregate function \"" << evaluator->fn_name() << "()\"";
- return Status(ss.str());
+ for (const SlotDescriptor* slot_desc : intermediate_tuple_desc_->slots()) {
+ if (slot_desc->type().type == TYPE_CHAR) {
+ return Status("PartitionedAggregationNode::CodegenUpdateTuple(): cannot codegen"
+ "CHAR in aggregations");
}
}
if (intermediate_tuple_desc_->GetLlvmStruct(codegen) == NULL) {
return Status("PartitionedAggregationNode::CodegenUpdateTuple(): failed to generate "
- "intermediate tuple desc");
+ "intermediate tuple desc");
+ }
+
+ for (AggFnEvaluator* evaluator : aggregate_evaluators_) {
+ // Don't codegen things that aren't builtins (for now)
+ if (!evaluator->is_builtin()) {
+ return Status("PartitionedAggregationNode::CodegenUpdateTuple(): UDA codegen NYI");
+ }
}
// Get the types to match the UpdateTuple signature
@@ -1800,7 +1843,7 @@ Status PartitionedAggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen,
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("is_merge", codegen->boolean_type()));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[5];
*fn = prototype.GeneratePrototype(&builder, &args[0]);
Value* this_arg = args[0];
@@ -1812,13 +1855,13 @@ Status PartitionedAggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen,
// TODO: get rid of this by using right type in function signature
tuple_arg = builder.CreateBitCast(tuple_arg, tuple_ptr, "tuple");
- Function* get_expr_ctx_fn =
- codegen->GetFunction(IRFunction::PART_AGG_NODE_GET_EXPR_CTX, false);
- DCHECK(get_expr_ctx_fn != NULL);
+ Function* get_expr_ctxs_fn =
+ codegen->GetFunction(IRFunction::PART_AGG_NODE_GET_EXPR_CTXS, false);
+ DCHECK(get_expr_ctxs_fn != NULL);
// Loop over each expr and generate the IR for that slot. If the expr is not
// count(*), generate a helper IR function to update the slot and call that.
- j = grouping_expr_ctxs_.size();
+ int j = grouping_expr_ctxs_.size();
for (int i = 0; i < aggregate_evaluators_.size(); ++i, ++j) {
SlotDescriptor* slot_desc = intermediate_tuple_desc_->slots()[j];
AggFnEvaluator* evaluator = aggregate_evaluators_[i];
@@ -1838,9 +1881,9 @@ Status PartitionedAggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen,
Value* agg_fn_ctx = builder.CreateLoad(agg_fn_ctx_ptr, "agg_fn_ctx");
// Call GetExprCtx() to get the expression context.
DCHECK(agg_expr_ctxs_[i] != NULL);
- Value* get_expr_ctx_args[] = { this_arg, codegen->GetIntConstant(TYPE_INT, i) };
- Value* agg_expr_ctx = builder.CreateCall(get_expr_ctx_fn, get_expr_ctx_args);
- Value* update_slot_args[] = { agg_fn_ctx, agg_expr_ctx, tuple_arg, row_arg };
+ Value* get_expr_ctxs_args[] = {this_arg, codegen->GetIntConstant(TYPE_INT, i)};
+ Value* agg_expr_ctxs = builder.CreateCall(get_expr_ctxs_fn, get_expr_ctxs_args);
+ Value* update_slot_args[] = {agg_fn_ctx, agg_expr_ctxs, tuple_arg, row_arg};
builder.CreateCall(update_slot_fn, update_slot_args);
}
}
@@ -1849,8 +1892,8 @@ Status PartitionedAggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen,
// CodegenProcessBatch() does the final optimizations.
*fn = codegen->FinalizeFunction(*fn);
if (*fn == NULL) {
- return Status("PartitionedAggregationNode::CodegeUpdateTuple(): codegen'd "
- "UpdateTuple() function failed verification, see log");
+ return Status("PartitionedAggregationNode::CodegenUpdateTuple(): codegen'd "
+ "UpdateTuple() function failed verification, see log");
}
return Status::OK();
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/partitioned-aggregation-node.h
----------------------------------------------------------------------
diff --git a/be/src/exec/partitioned-aggregation-node.h b/be/src/exec/partitioned-aggregation-node.h
index 9e14e66..4287cea 100644
--- a/be/src/exec/partitioned-aggregation-node.h
+++ b/be/src/exec/partitioned-aggregation-node.h
@@ -30,13 +30,17 @@
#include "runtime/string-value.h"
namespace llvm {
- class Function;
+class BasicBlock;
+class Function;
+class Value;
}
namespace impala {
class AggFnEvaluator;
+class CodegenAnyVal;
class LlvmCodeGen;
+class LlvmBuilder;
class RowBatch;
class RuntimeState;
struct StringValue;
@@ -203,7 +207,7 @@ class PartitionedAggregationNode : public ExecNode {
/// version of UpdateTuple() to avoid loading aggregate_evaluators_[i] at runtime.
/// An entry is NULL if the aggregate evaluator is not codegen'ed or there is no Expr
/// in the aggregate evaluator (e.g. count(*)).
- std::vector<ExprContext*> agg_expr_ctxs_;
+ std::vector<ExprContext* const*> agg_expr_ctxs_;
/// FunctionContext for each aggregate function and backing MemPool. String data
/// returned by the aggregate functions is allocated via these contexts.
@@ -520,12 +524,13 @@ class PartitionedAggregationNode : public ExecNode {
/// This function processes each individual row in ProcessBatch(). Must be inlined into
/// ProcessBatch for codegen to substitute function calls with codegen'd versions.
/// May spill partitions if not enough memory is available.
- template<bool AGGREGATED_ROWS>
+ template <bool AGGREGATED_ROWS>
Status IR_ALWAYS_INLINE ProcessRow(TupleRow* row, HashTableCtx* ht_ctx);
- /// Accessor for the expression context of an AggFnEvaluator. Used only in codegen'ed
+ /// Accessor for the expression contexts of an AggFnEvaluator. Returns an array of
+ /// pointers the the AggFnEvaluator's expression contexts. Used only in codegen'ed
/// version of UpdateTuple().
- ExprContext* IR_ALWAYS_INLINE GetAggExprContext(int i) const;
+ ExprContext* const* IR_ALWAYS_INLINE GetAggExprContexts(int i) const;
/// Create a new intermediate tuple in partition, initialized with row. ht_ctx is
/// the context for the partition's hash table and hash is the precomputed hash of
@@ -640,6 +645,16 @@ class PartitionedAggregationNode : public ExecNode {
Status CodegenUpdateSlot(LlvmCodeGen* codegen, AggFnEvaluator* evaluator,
SlotDescriptor* slot_desc, llvm::Function** fn);
+ /// Codegen a call to a function implementing the UDA interface with input values
+ /// from 'input_vals'. 'dst_val' should contain the previous value of the aggregate
+ /// function, and 'updated_dst_val' is set to the new value after the Update or Merge
+ /// operation is applied. The instruction sequence for the UDA call is inserted at
+ /// the insert position of 'builder'.
+ Status CodegenCallUda(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ AggFnEvaluator* evaluator, llvm::Value* agg_fn_ctx,
+ const std::vector<CodegenAnyVal>& input_vals, const CodegenAnyVal& dst_val,
+ CodegenAnyVal* updated_dst_val);
+
/// Codegen UpdateTuple(). Returns non-OK status if codegen is unsuccessful.
Status CodegenUpdateTuple(LlvmCodeGen* codegen, llvm::Function** fn);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/partitioned-hash-join-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/partitioned-hash-join-node.cc b/be/src/exec/partitioned-hash-join-node.cc
index 116ac02..c3211af 100644
--- a/be/src/exec/partitioned-hash-join-node.cc
+++ b/be/src/exec/partitioned-hash-join-node.cc
@@ -1144,7 +1144,7 @@ Status PartitionedHashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen,
prototype.AddArgument(LlvmCodeGen::NamedVariable("build_arg", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[4];
*fn = prototype.GeneratePrototype(&builder, args);
Value* out_row_arg = builder.CreateBitCast(args[1], tuple_row_working_type, "out");
@@ -1156,8 +1156,9 @@ Status PartitionedHashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen,
// Copy probe row
codegen->CodegenMemcpy(&builder, out_row_arg, probe_row_arg, probe_tuple_row_size_);
- Value* build_row_idx[] = { codegen->GetIntConstant(TYPE_INT, num_probe_tuples) };
- Value* build_row_dst = builder.CreateGEP(out_row_arg, build_row_idx, "build_dst_ptr");
+ Value* build_row_idx[] = {codegen->GetIntConstant(TYPE_INT, num_probe_tuples)};
+ Value* build_row_dst =
+ builder.CreateInBoundsGEP(out_row_arg, build_row_idx, "build_dst_ptr");
// Copy build row.
BasicBlock* build_not_null_block = BasicBlock::Create(context, "build_not_null", *fn);
@@ -1176,9 +1177,8 @@ Status PartitionedHashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen,
// to work.
builder.SetInsertPoint(build_null_block);
for (int i = 0; i < num_build_tuples; ++i) {
- Value* array_idx[] =
- { codegen->GetIntConstant(TYPE_INT, i + num_probe_tuples) };
- Value* dst = builder.CreateGEP(out_row_arg, array_idx, "dst_tuple_ptr");
+ Value* array_idx[] = {codegen->GetIntConstant(TYPE_INT, i + num_probe_tuples)};
+ Value* dst = builder.CreateInBoundsGEP(out_row_arg, array_idx, "dst_tuple_ptr");
builder.CreateStore(codegen->null_ptr_value(), dst);
}
builder.CreateRetVoid();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/text-converter.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/text-converter.cc b/be/src/exec/text-converter.cc
index d38d662..cb5d70c 100644
--- a/be/src/exec/text-converter.cc
+++ b/be/src/exec/text-converter.cc
@@ -128,19 +128,13 @@ Function* TextConverter::CodegenWriteSlot(LlvmCodeGen* codegen,
if (tuple_type == NULL) return NULL;
PointerType* tuple_ptr_type = tuple_type->getPointerTo();
- Function* set_null_fn = slot_desc->GetUpdateNullFn(codegen, true);
- if (set_null_fn == NULL) {
- LOG(ERROR) << "Could not codegen WriteSlot because slot update codegen failed.";
- return NULL;
- }
-
LlvmCodeGen::FnPrototype prototype(
codegen, "WriteSlot", codegen->GetType(TYPE_BOOLEAN));
prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple_arg", tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("data", codegen->ptr_type()));
prototype.AddArgument(LlvmCodeGen::NamedVariable("len", codegen->GetType(TYPE_INT)));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[3];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
@@ -267,13 +261,13 @@ Function* TextConverter::CodegenWriteSlot(LlvmCodeGen* codegen,
// Parse failed, set slot to null and return false
builder.SetInsertPoint(parse_failed_block);
- builder.CreateCall(set_null_fn, ArrayRef<Value*>({args[0]}));
+ slot_desc->CodegenSetNullIndicator(codegen, &builder, args[0], codegen->true_value());
builder.CreateRet(codegen->false_value());
}
// Case where data is \N or len == 0 and it is not a string col
builder.SetInsertPoint(set_null_block);
- builder.CreateCall(set_null_fn, ArrayRef<Value*>({args[0]}));
+ slot_desc->CodegenSetNullIndicator(codegen, &builder, args[0], codegen->true_value());
builder.CreateRet(codegen->true_value());
return codegen->FinalizeFunction(fn);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/aggregate-functions-ir.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/aggregate-functions-ir.cc b/be/src/exprs/aggregate-functions-ir.cc
index c07d1db..7ed6386 100644
--- a/be/src/exprs/aggregate-functions-ir.cc
+++ b/be/src/exprs/aggregate-functions-ir.cc
@@ -164,12 +164,10 @@ StringVal ToStringVal(FunctionContext* context, T val) {
stringstream ss;
ss << val;
const string &str = ss.str();
- return StringVal::CopyFrom(context, reinterpret_cast<const uint8_t*>(str.c_str()), str.size());
+ return StringVal::CopyFrom(
+ context, reinterpret_cast<const uint8_t*>(str.c_str()), str.size());
}
-// Delimiter to use if the separator is NULL.
-static const StringVal DEFAULT_STRING_CONCAT_DELIM((uint8_t*)", ", 2);
-
constexpr int AggregateFunctions::HLL_PRECISION;
constexpr int AggregateFunctions::HLL_LEN;
@@ -627,15 +625,21 @@ void AggregateFunctions::Max(FunctionContext*,
// StringConcatUpdate().
typedef int StringConcatHeader;
-void AggregateFunctions::StringConcatUpdate(FunctionContext* ctx,
- const StringVal& src, StringVal* result) {
- StringConcatUpdate(ctx, src, DEFAULT_STRING_CONCAT_DELIM, result);
+// Delimiter to use if the separator is not provided.
+static inline StringVal ALWAYS_INLINE DefaultStringConcatDelim() {
+ return StringVal(reinterpret_cast<uint8_t*>(const_cast<char*>(", ")), 2);
+}
+
+void AggregateFunctions::StringConcatUpdate(
+ FunctionContext* ctx, const StringVal& src, StringVal* result) {
+ StringConcatUpdate(ctx, src, DefaultStringConcatDelim(), result);
}
-void AggregateFunctions::StringConcatUpdate(FunctionContext* ctx,
- const StringVal& src, const StringVal& separator, StringVal* result) {
+void AggregateFunctions::StringConcatUpdate(FunctionContext* ctx, const StringVal& src,
+ const StringVal& separator, StringVal* result) {
if (src.is_null) return;
- const StringVal* sep = separator.is_null ? &DEFAULT_STRING_CONCAT_DELIM : &separator;
+ const StringVal default_delim = DefaultStringConcatDelim();
+ const StringVal* sep = separator.is_null ? &default_delim : &separator;
if (result->is_null) {
// Header of the intermediate state holds the length of the first separator.
const int header_len = sizeof(StringConcatHeader);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/case-expr.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/case-expr.cc b/be/src/exprs/case-expr.cc
index f139d64..3c0db79 100644
--- a/be/src/exprs/case-expr.cc
+++ b/be/src/exprs/case-expr.cc
@@ -196,7 +196,7 @@ Status CaseExpr::GetCodegendComputeFn(LlvmCodeGen* codegen, Function** fn) {
}
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[2];
Function* function = CreateIrFunctionPrototype(codegen, "CaseExpr", &args);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/compound-predicates.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/compound-predicates.cc b/be/src/exprs/compound-predicates.cc
index 531a70c..d367e5a 100644
--- a/be/src/exprs/compound-predicates.cc
+++ b/be/src/exprs/compound-predicates.cc
@@ -131,7 +131,7 @@ Status CompoundPredicate::CodegenComputeFn(
RETURN_IF_ERROR(children()[1]->GetCodegendComputeFn(codegen, &rhs_function));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[2];
Function* function = CreateIrFunctionPrototype(codegen, "CompoundPredicate", &args);
@@ -140,8 +140,7 @@ Status CompoundPredicate::CodegenComputeFn(
// Control blocks for aggregating results
BasicBlock* lhs_null_block = BasicBlock::Create(context, "lhs_null", function);
- BasicBlock* lhs_not_null_block =
- BasicBlock::Create(context, "lhs_not_null", function);
+ BasicBlock* lhs_not_null_block = BasicBlock::Create(context, "lhs_not_null", function);
BasicBlock* lhs_null_rhs_not_null_block =
BasicBlock::Create(context, "lhs_null_rhs_not_null", function);
BasicBlock* lhs_not_null_rhs_null_block =
@@ -232,7 +231,7 @@ Status CompoundPredicate::CodegenComputeFn(
CodegenAnyVal ret(codegen, &builder, TYPE_BOOLEAN, NULL, "ret");
ret.SetIsNull(is_null_phi);
ret.SetVal(val_phi);
- builder.CreateRet(ret.value());
+ builder.CreateRet(ret.GetLoweredValue());
*fn = codegen->FinalizeFunction(function);
DCHECK(*fn != NULL);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/expr-codegen-test.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr-codegen-test.cc b/be/src/exprs/expr-codegen-test.cc
index 800a440..6ccbbf4 100644
--- a/be/src/exprs/expr-codegen-test.cc
+++ b/be/src/exprs/expr-codegen-test.cc
@@ -252,7 +252,7 @@ TEST_F(ExprCodegenTest, TestInlineConstants) {
test_udf_file << getenv("IMPALA_HOME") << "/be/build/latest/exprs/expr-codegen-test.ll";
scoped_ptr<LlvmCodeGen> codegen;
ASSERT_OK(LlvmCodeGen::CreateFromFile(&pool, test_udf_file.str(), "test", &codegen));
- Function* fn = codegen->GetFunction(TEST_GET_CONSTANT_SYMBOL);
+ Function* fn = codegen->GetFunction(TEST_GET_CONSTANT_SYMBOL, false);
ASSERT_TRUE(fn != NULL);
// Function verification should fail because we haven't inlined GetConstant() calls
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/expr.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/expr.cc b/be/src/exprs/expr.cc
index 0141bae..045c030 100644
--- a/be/src/exprs/expr.cc
+++ b/be/src/exprs/expr.cc
@@ -684,10 +684,10 @@ Status Expr::GetCodegendComputeFnWrapper(LlvmCodeGen* codegen, Function** fn) {
ir_compute_fn_ = CreateIrFunctionPrototype(codegen, "CodegenComputeFnWrapper", &args);
BasicBlock* entry_block =
BasicBlock::Create(codegen->context(), "entry", ir_compute_fn_);
- LlvmCodeGen::LlvmBuilder builder(entry_block);
+ LlvmBuilder builder(entry_block);
Value* this_ptr =
codegen->CastPtrToLlvmPtr(codegen->GetPtrType(Expr::LLVM_CLASS_NAME), this);
- Value* compute_fn_args[] = { this_ptr, args[0], args[1] };
+ Value* compute_fn_args[] = {this_ptr, args[0], args[1]};
Value* ret = CodegenAnyVal::CreateCall(
codegen, &builder, static_getval_fn, compute_fn_args, "ret");
builder.CreateRet(ret);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/literal.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/literal.cc b/be/src/exprs/literal.cc
index 03bdd50..5b075f6 100644
--- a/be/src/exprs/literal.cc
+++ b/be/src/exprs/literal.cc
@@ -385,7 +385,7 @@ Status Literal::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
Value* args[2];
*fn = CreateIrFunctionPrototype(codegen, "Literal", &args);
BasicBlock* entry_block = BasicBlock::Create(codegen->context(), "entry", *fn);
- LlvmCodeGen::LlvmBuilder builder(entry_block);
+ LlvmBuilder builder(entry_block);
CodegenAnyVal v = CodegenAnyVal::GetNonNullVal(codegen, &builder, type_);
switch (type_.type) {
@@ -439,7 +439,7 @@ Status Literal::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
return Status(ss.str());
}
- builder.CreateRet(v.value());
+ builder.CreateRet(v.GetLoweredValue());
*fn = codegen->FinalizeFunction(*fn);
ir_compute_fn_ = *fn;
return Status::OK();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/null-literal.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/null-literal.cc b/be/src/exprs/null-literal.cc
index a8f4241..6985c5b 100644
--- a/be/src/exprs/null-literal.cc
+++ b/be/src/exprs/null-literal.cc
@@ -101,7 +101,7 @@ Status NullLiteral::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function**
Value* args[2];
*fn = CreateIrFunctionPrototype(codegen, "NullLiteral", &args);
BasicBlock* entry_block = BasicBlock::Create(codegen->context(), "entry", *fn);
- LlvmCodeGen::LlvmBuilder builder(entry_block);
+ LlvmBuilder builder(entry_block);
Value* v = CodegenAnyVal::GetNullVal(codegen, type());
builder.CreateRet(v);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/scalar-fn-call.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/scalar-fn-call.cc b/be/src/exprs/scalar-fn-call.cc
index 3a7ffb1..5457ced 100644
--- a/be/src/exprs/scalar-fn-call.cc
+++ b/be/src/exprs/scalar-fn-call.cc
@@ -319,7 +319,7 @@ Status ScalarFnCall::GetCodegendComputeFn(LlvmCodeGen* codegen, Function** fn) {
Value* expr_ctx = args[0];
Value* row = args[1];
BasicBlock* block = BasicBlock::Create(codegen->context(), "entry", *fn);
- LlvmCodeGen::LlvmBuilder builder(block);
+ LlvmBuilder builder(block);
// Populate UDF arguments
vector<Value*> udf_args;
@@ -482,7 +482,7 @@ Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, Function** udf) {
} else if (fn_.binary_type == TFunctionBinaryType::BUILTIN) {
// In this path, we're running a builtin with the UDF interface. The IR is
// in the llvm module.
- *udf = codegen->GetFunction(fn_.scalar_fn.symbol);
+ *udf = codegen->GetFunction(fn_.scalar_fn.symbol, false);
if (*udf == NULL) {
// Builtins symbols should exist unless there is a version mismatch.
stringstream ss;
@@ -502,11 +502,11 @@ Status ScalarFnCall::GetUdf(LlvmCodeGen* codegen, Function** udf) {
} else {
// We're running an IR UDF.
DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::IR);
- *udf = codegen->GetFunction(fn_.scalar_fn.symbol);
+ *udf = codegen->GetFunction(fn_.scalar_fn.symbol, false);
if (*udf == NULL) {
stringstream ss;
- ss << "Unable to locate function " << fn_.scalar_fn.symbol
- << " from LLVM module " << fn_.hdfs_location;
+ ss << "Unable to locate function " << fn_.scalar_fn.symbol << " from LLVM module "
+ << fn_.hdfs_location;
return Status(ss.str());
}
*udf = codegen->FinalizeFunction(*udf);
@@ -527,7 +527,7 @@ Status ScalarFnCall::GetFunction(RuntimeState* state, const string& symbol, void
DCHECK_EQ(fn_.binary_type, TFunctionBinaryType::IR);
LlvmCodeGen* codegen = state->codegen();
DCHECK(codegen != NULL);
- Function* ir_fn = codegen->GetFunction(symbol);
+ Function* ir_fn = codegen->GetFunction(symbol, false);
if (ir_fn == NULL) {
stringstream ss;
ss << "Unable to locate function " << symbol << " from LLVM module "
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exprs/slot-ref.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/slot-ref.cc b/be/src/exprs/slot-ref.cc
index eeba42f..3a70b6c 100644
--- a/be/src/exprs/slot-ref.cc
+++ b/be/src/exprs/slot-ref.cc
@@ -134,11 +134,11 @@ string SlotRef::DebugString() const {
// br label %check_slot_null
//
// check_slot_null: ; preds = %entry
-// %null_ptr = getelementptr i8* %tuple_ptr, i32 0
+// %null_byte_ptr = getelementptr i8* %tuple_ptr, i32 0
// %null_byte = load i8* %null_ptr
// %null_byte_set = and i8 %null_byte, 2
-// %slot_is_null = icmp ne i8 %null_byte_set, 0
-// br i1 %slot_is_null, label %ret, label %get_slot
+// %is_null = icmp ne i8 %null_byte_set, 0
+// br i1 %is_null, label %ret, label %get_slot
//
// get_slot: ; preds = %check_slot_null
// %slot_addr = getelementptr i8* %tuple_ptr, i32 8
@@ -189,28 +189,24 @@ Status SlotRef::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
Value* row_ptr = args[1];
Value* tuple_offset = ConstantInt::get(codegen->int_type(), tuple_idx_);
- Value* null_byte_offset =
- ConstantInt::get(codegen->int_type(), null_indicator_offset_.byte_offset);
Value* slot_offset = ConstantInt::get(codegen->int_type(), slot_offset_);
- Value* null_mask =
- ConstantInt::get(codegen->tinyint_type(), null_indicator_offset_.bit_mask);
Value* zero = ConstantInt::get(codegen->GetType(TYPE_TINYINT), 0);
Value* one = ConstantInt::get(codegen->GetType(TYPE_TINYINT), 1);
BasicBlock* entry_block = BasicBlock::Create(context, "entry", *fn);
+ bool slot_is_nullable = null_indicator_offset_.bit_mask != 0;
BasicBlock* check_slot_null_indicator_block = NULL;
- if (null_indicator_offset_.bit_mask != 0) {
- check_slot_null_indicator_block =
- BasicBlock::Create(context, "check_slot_null", *fn);
+ if (slot_is_nullable) {
+ check_slot_null_indicator_block = BasicBlock::Create(context, "check_slot_null", *fn);
}
BasicBlock* get_slot_block = BasicBlock::Create(context, "get_slot", *fn);
BasicBlock* ret_block = BasicBlock::Create(context, "ret", *fn);
- LlvmCodeGen::LlvmBuilder builder(entry_block);
+ LlvmBuilder builder(entry_block);
// Get the tuple offset addr from the row
Value* cast_row_ptr = builder.CreateBitCast(
row_ptr, PointerType::get(codegen->ptr_type(), 0), "cast_row_ptr");
- Value* tuple_addr = builder.CreateGEP(cast_row_ptr, tuple_offset, "tuple_addr");
+ Value* tuple_addr = builder.CreateInBoundsGEP(cast_row_ptr, tuple_offset, "tuple_addr");
// Load the tuple*
Value* tuple_ptr = builder.CreateLoad(tuple_addr, "tuple_ptr");
@@ -218,32 +214,30 @@ Status SlotRef::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
if (tuple_is_nullable_) {
Value* tuple_is_null = builder.CreateIsNull(tuple_ptr, "tuple_is_null");
// Check slot is null only if the null indicator bit is set
- if (null_indicator_offset_.bit_mask == 0) {
- builder.CreateCondBr(tuple_is_null, ret_block, get_slot_block);
- } else {
+ if (slot_is_nullable) {
builder.CreateCondBr(tuple_is_null, ret_block, check_slot_null_indicator_block);
+ } else {
+ builder.CreateCondBr(tuple_is_null, ret_block, get_slot_block);
}
} else {
- if (null_indicator_offset_.bit_mask == 0) {
- builder.CreateBr(get_slot_block);
- } else {
+ if (slot_is_nullable) {
builder.CreateBr(check_slot_null_indicator_block);
+ } else {
+ builder.CreateBr(get_slot_block);
}
}
// Branch for tuple* != NULL. Need to check if null-indicator is set
- if (check_slot_null_indicator_block != NULL) {
+ if (slot_is_nullable) {
builder.SetInsertPoint(check_slot_null_indicator_block);
- Value* null_addr = builder.CreateGEP(tuple_ptr, null_byte_offset, "null_ptr");
- Value* null_val = builder.CreateLoad(null_addr, "null_byte");
- Value* slot_null_mask = builder.CreateAnd(null_val, null_mask, "null_byte_set");
- Value* is_slot_null = builder.CreateICmpNE(slot_null_mask, zero, "slot_is_null");
+ Value* is_slot_null = SlotDescriptor::CodegenIsNull(
+ codegen, &builder, null_indicator_offset_, tuple_ptr);
builder.CreateCondBr(is_slot_null, ret_block, get_slot_block);
}
// Branch for slot != NULL
builder.SetInsertPoint(get_slot_block);
- Value* slot_ptr = builder.CreateGEP(tuple_ptr, slot_offset, "slot_addr");
+ Value* slot_ptr = builder.CreateInBoundsGEP(tuple_ptr, slot_offset, "slot_addr");
Value* val_ptr = builder.CreateBitCast(slot_ptr, codegen->GetPtrType(type_), "val_ptr");
// Depending on the type, load the values we need
Value* val = NULL;
@@ -313,7 +307,7 @@ Status SlotRef::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
result.SetIsNull(is_null_phi);
result.SetPtr(ptr_phi);
result.SetLen(len_phi);
- builder.CreateRet(result.value());
+ builder.CreateRet(result.GetLoweredValue());
} else if (type() == TYPE_TIMESTAMP) {
DCHECK(time_of_day != NULL);
DCHECK(date != NULL);
@@ -343,7 +337,7 @@ Status SlotRef::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
result.SetIsNull(is_null_phi);
result.SetTimeOfDay(time_of_day_phi);
result.SetDate(date_phi);
- builder.CreateRet(result.value());
+ builder.CreateRet(result.GetLoweredValue());
} else {
DCHECK(val != NULL);
PHINode* val_phi = builder.CreatePHI(val->getType(), 2, "val_phi");
@@ -360,7 +354,7 @@ Status SlotRef::GetCodegendComputeFn(LlvmCodeGen* codegen, llvm::Function** fn)
CodegenAnyVal::GetNonNullVal(codegen, &builder, type(), "result");
result.SetIsNull(is_null_phi);
result.SetVal(val_phi);
- builder.CreateRet(result.value());
+ builder.CreateRet(result.GetLoweredValue());
}
*fn = codegen->FinalizeFunction(*fn);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/runtime/descriptors.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/descriptors.cc b/be/src/runtime/descriptors.cc
index 41485f9..f8ec79c 100644
--- a/be/src/runtime/descriptors.cc
+++ b/be/src/runtime/descriptors.cc
@@ -77,9 +77,8 @@ ostream& operator<<(ostream& os, const NullIndicatorOffset& null_indicator) {
return os;
}
-SlotDescriptor::SlotDescriptor(
- const TSlotDescriptor& tdesc, const TupleDescriptor* parent,
- const TupleDescriptor* collection_item_descriptor)
+SlotDescriptor::SlotDescriptor(const TSlotDescriptor& tdesc,
+ const TupleDescriptor* parent, const TupleDescriptor* collection_item_descriptor)
: id_(tdesc.id),
type_(ColumnType::FromThrift(tdesc.slotType)),
parent_(parent),
@@ -89,9 +88,7 @@ SlotDescriptor::SlotDescriptor(
null_indicator_offset_(tdesc.nullIndicatorByte, tdesc.nullIndicatorBit),
slot_idx_(tdesc.slotIdx),
slot_size_(type_.GetSlotSize()),
- llvm_field_idx_(-1),
- set_not_null_fn_(NULL),
- set_null_fn_(NULL) {
+ llvm_field_idx_(-1) {
DCHECK_NE(type_.type, TYPE_STRUCT);
DCHECK(parent_ != NULL) << tdesc.parent;
if (type_.IsCollectionType()) {
@@ -569,60 +566,79 @@ void DescriptorTbl::GetTupleDescs(vector<TupleDescriptor*>* descs) const {
}
}
-// Generate function to set a slot to be null or not-null. The resulting IR
-// for SetNotNull looks like:
-// (in this case the tuple contains only a nullable double)
-// define void @SetNotNull({ i8, double }* %tuple) {
-// entry:
-// %null_byte_ptr = getelementptr inbounds { i8, double }* %tuple, i32 0, i32 0
-// %null_byte = load i8* %null_byte_ptr
-// %0 = and i8 %null_byte, -2
-// store i8 %0, i8* %null_byte_ptr
-// ret void
-// }
-Function* SlotDescriptor::GetUpdateNullFn(LlvmCodeGen* codegen, bool set_null) const {
- if (set_null && set_null_fn_ != NULL) return set_null_fn_;
- if (!set_null && set_not_null_fn_ != NULL) return set_not_null_fn_;
-
- StructType* tuple_type = parent()->GetLlvmStruct(codegen);
- PointerType* tuple_ptr_type = tuple_type->getPointerTo();
- LlvmCodeGen::FnPrototype prototype(codegen, (set_null) ? "SetNull" :"SetNotNull",
- codegen->void_type());
- prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple", tuple_ptr_type));
-
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
- Value* tuple_arg;
- Function* fn = prototype.GeneratePrototype(&builder, &tuple_arg);
-
- Value* tuple_int8_ptr =
- builder.CreateBitCast(tuple_arg, codegen->ptr_type(), "tuple_int8_ptr");
- Value* null_byte_offset =
- ConstantInt::get(codegen->int_type(), null_indicator_offset_.byte_offset);
- Value* null_byte_ptr =
- builder.CreateInBoundsGEP(tuple_int8_ptr, null_byte_offset, "null_byte_ptr");
- Value* null_byte = builder.CreateLoad(null_byte_ptr, "null_byte");
-
+Value* SlotDescriptor::CodegenIsNull(
+ LlvmCodeGen* codegen, LlvmBuilder* builder, Value* tuple) const {
+ return CodegenIsNull(codegen, builder, null_indicator_offset_, tuple);
+}
+
+// Example IR for getting the first null bit:
+// %0 = bitcast { i8, [7 x i8], %"class.impala::TimestampValue" }* %agg_tuple to i8*
+// %null_byte_ptr = getelementptr i8, i8* %0, i32 0
+// %null_byte = load i8, i8* %null_byte_ptr
+// %null_mask = and i8 %null_byte, 1
+// %is_null = icmp ne i8 %null_mask, 0
+Value* SlotDescriptor::CodegenIsNull(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const NullIndicatorOffset& null_indicator_offset, Value* tuple) {
+ Value* null_byte =
+ CodegenGetNullByte(codegen, builder, null_indicator_offset, tuple, NULL);
+ Constant* mask =
+ ConstantInt::get(codegen->tinyint_type(), null_indicator_offset.bit_mask);
+ Value* null_mask = builder->CreateAnd(null_byte, mask, "null_mask");
+ Constant* zero = ConstantInt::get(codegen->tinyint_type(), 0);
+ return builder->CreateICmpNE(null_mask, zero, "is_null");
+}
+
+// Example IR for setting the first null bit to a non-constant 'is_null' value:
+// %14 = bitcast { i8, [7 x i8], %"class.impala::TimestampValue" }* %agg_tuple to i8*
+// %null_byte_ptr3 = getelementptr i8, i8* %14, i32 0
+// %null_byte4 = load i8, i8* %null_byte_ptr3
+// %null_bit_cleared = and i8 %null_byte4, -2
+// %15 = sext i1 %result_is_null to i8
+// %null_bit = and i8 %15, 1
+// %null_bit_set = or i8 %null_bit_cleared, %null_bit
+// store i8 %null_bit_set, i8* %null_byte_ptr3
+void SlotDescriptor::CodegenSetNullIndicator(
+ LlvmCodeGen* codegen, LlvmBuilder* builder, Value* tuple, Value* is_null) const {
+ DCHECK_EQ(is_null->getType(), codegen->boolean_type());
+ Value* null_byte_ptr;
+ Value* null_byte =
+ CodegenGetNullByte(codegen, builder, null_indicator_offset_, tuple, &null_byte_ptr);
+ Constant* mask =
+ ConstantInt::get(codegen->tinyint_type(), null_indicator_offset_.bit_mask);
+ Constant* not_mask =
+ ConstantInt::get(codegen->tinyint_type(), ~null_indicator_offset_.bit_mask);
+
+ ConstantInt* constant_is_null = dyn_cast<ConstantInt>(is_null);
Value* result = NULL;
- if (set_null) {
- Value* null_set = codegen->GetIntConstant(
- TYPE_TINYINT, null_indicator_offset_.bit_mask);
- result = builder.CreateOr(null_byte, null_set);
- } else {
- Value* null_clear_val =
- codegen->GetIntConstant(TYPE_TINYINT, ~null_indicator_offset_.bit_mask);
- result = builder.CreateAnd(null_byte, null_clear_val);
- }
-
- builder.CreateStore(result, null_byte_ptr);
- builder.CreateRetVoid();
-
- fn = codegen->FinalizeFunction(fn);
- if (set_null) {
- set_null_fn_ = fn;
+ if (constant_is_null != NULL) {
+ if (constant_is_null->isOne()) {
+ result = builder->CreateOr(null_byte, mask, "null_bit_set");
+ } else {
+ DCHECK(constant_is_null->isZero());
+ result = builder->CreateAnd(null_byte, not_mask, "null_bit_cleared");
+ }
} else {
- set_not_null_fn_ = fn;
- }
- return fn;
+ // Avoid branching by computing the new byte as:
+ // (null_byte & ~mask) | (-null & mask);
+ Value* byte_with_cleared_bit =
+ builder->CreateAnd(null_byte, not_mask, "null_bit_cleared");
+ Value* sign_extended_null = builder->CreateSExt(is_null, codegen->tinyint_type());
+ Value* bit_only = builder->CreateAnd(sign_extended_null, mask, "null_bit");
+ result = builder->CreateOr(byte_with_cleared_bit, bit_only, "null_bit_set");
+ }
+
+ builder->CreateStore(result, null_byte_ptr);
+}
+
+Value* SlotDescriptor::CodegenGetNullByte(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const NullIndicatorOffset& null_indicator_offset, Value* tuple,
+ Value** null_byte_ptr) {
+ Constant* byte_offset =
+ ConstantInt::get(codegen->int_type(), null_indicator_offset.byte_offset);
+ Value* tuple_bytes = builder->CreateBitCast(tuple, codegen->ptr_type());
+ Value* byte_ptr = builder->CreateInBoundsGEP(tuple_bytes, byte_offset, "null_byte_ptr");
+ if (null_byte_ptr != NULL) *null_byte_ptr = byte_ptr;
+ return builder->CreateLoad(byte_ptr, "null_byte");
}
StructType* TupleDescriptor::GetLlvmStruct(LlvmCodeGen* codegen) const {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/runtime/descriptors.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/descriptors.h b/be/src/runtime/descriptors.h
index 8122653..4a50800 100644
--- a/be/src/runtime/descriptors.h
+++ b/be/src/runtime/descriptors.h
@@ -35,19 +35,21 @@ namespace llvm {
class Function;
class PointerType;
class StructType;
+ class Value;
};
namespace impala {
+class Expr;
+class ExprContext;
+class LlvmBuilder;
class LlvmCodeGen;
class ObjectPool;
+class RuntimeState;
class TDescriptorTable;
class TSlotDescriptor;
class TTable;
class TTupleDescriptor;
-class Expr;
-class ExprContext;
-class RuntimeState;
/// A path into a table schema (e.g. a vector of ColumnTypes) pointing to a particular
/// column/field. The i-th element of the path is the ordinal position of the column/field
@@ -133,9 +135,22 @@ class SlotDescriptor {
std::string DebugString() const;
- /// Codegen for: void SetNull(Tuple* tuple) / void SetNotNull(Tuple* tuple)
- /// The codegen'd IR function is cached.
- llvm::Function* GetUpdateNullFn(LlvmCodeGen*, bool set_null) const;
+ /// Generate LLVM code at the insert position of 'builder' that returns a boolean value
+ /// represented as a LLVM i1 indicating whether this slot is null in 'tuple'.
+ llvm::Value* CodegenIsNull(
+ LlvmCodeGen* codegen, LlvmBuilder* builder, llvm::Value* tuple) const;
+
+ /// Generate LLVM code at the insert position of 'builder' that returns a boolean value
+ /// represented as a LLVM i1 with value of the NULL bit at 'null_indicator_offset' in
+ /// 'tuple'.
+ static llvm::Value* CodegenIsNull(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const NullIndicatorOffset& null_indicator_offset, llvm::Value* tuple);
+
+ /// Generate LLVM code at the insert position of 'builder' to set this slot's
+ /// NULL bit in the given 'tuple' to the value 'is_null'. 'tuple' is a pointer
+ /// to the tuple, and 'is_null' is an boolean value represented as a LLVM i1.
+ void CodegenSetNullIndicator(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ llvm::Value* tuple, llvm::Value* is_null) const;
private:
friend class DescriptorTbl;
@@ -163,13 +178,16 @@ class SlotDescriptor {
/// any padding bytes.
int llvm_field_idx_;
- /// Cached codegen'd functions
- mutable llvm::Function* set_not_null_fn_;
- mutable llvm::Function* set_null_fn_;
-
/// collection_item_descriptor should be non-NULL iff this is a collection slot
SlotDescriptor(const TSlotDescriptor& tdesc, const TupleDescriptor* parent,
- const TupleDescriptor* collection_item_descriptor);
+ const TupleDescriptor* collection_item_descriptor);
+
+ /// Generate LLVM code at the insert position of 'builder' to get the i8 value of the
+ /// the byte containing 'null_indicator_offset' in 'tuple'. If 'null_byte_ptr' is
+ /// non-NULL, sets that to a pointer to the null byte.
+ static llvm::Value* CodegenGetNullByte(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const NullIndicatorOffset& null_indicator_offset, llvm::Value* tuple,
+ llvm::Value** null_byte_ptr);
};
class ColumnDescriptor {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/runtime/tuple.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/tuple.cc b/be/src/runtime/tuple.cc
index 7fa8b2b..dc83922 100644
--- a/be/src/runtime/tuple.cc
+++ b/be/src/runtime/tuple.cc
@@ -349,7 +349,7 @@ Status Tuple::CodegenMaterializeExprs(LlvmCodeGen* codegen, bool collect_string_
prototype.AddArgument("total_string_lengths", int_ptr_type);
prototype.AddArgument("num_non_null_string_values", int_ptr_type);
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[8];
*fn = prototype.GeneratePrototype(&builder, args);
Value* opaque_tuple_arg = args[0];
@@ -363,6 +363,9 @@ Status Tuple::CodegenMaterializeExprs(LlvmCodeGen* codegen, bool collect_string_
// Cast the opaque Tuple* argument to the generated struct type
Type* tuple_struct_type = desc.GetLlvmStruct(codegen);
+ if (tuple_struct_type == NULL) {
+ return Status("CodegenMaterializeExprs(): failed to generate tuple desc");
+ }
PointerType* tuple_type = codegen->GetPtrType(tuple_struct_type);
Value* tuple = builder.CreateBitCast(opaque_tuple_arg, tuple_type, "tuple");
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/runtime/types.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/types.h b/be/src/runtime/types.h
index 9558792..b0835bf 100644
--- a/be/src/runtime/types.h
+++ b/be/src/runtime/types.h
@@ -163,13 +163,28 @@ struct ColumnType {
return thrift_type;
}
+ inline bool IsBooleanType() const { return type == TYPE_BOOLEAN; }
+
+ inline bool IsIntegerType() const {
+ return type == TYPE_TINYINT || type == TYPE_SMALLINT || type == TYPE_INT
+ || type == TYPE_BIGINT;
+ }
+
+ inline bool IsFloatingPointType() const {
+ return type == TYPE_FLOAT || type == TYPE_DOUBLE;
+ }
+
+ inline bool IsDecimalType() const { return type == TYPE_DECIMAL; }
+
inline bool IsStringType() const {
return type == TYPE_STRING || type == TYPE_VARCHAR || type == TYPE_CHAR;
}
+ inline bool IsTimestampType() const { return type == TYPE_TIMESTAMP; }
+
inline bool IsVarLenStringType() const {
- return type == TYPE_STRING || type == TYPE_VARCHAR ||
- (type == TYPE_CHAR && len > MAX_CHAR_INLINE_LENGTH);
+ return type == TYPE_STRING || type == TYPE_VARCHAR
+ || (type == TYPE_CHAR && len > MAX_CHAR_INLINE_LENGTH);
}
inline bool IsComplexType() const {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/testutil/test-udas.cc
----------------------------------------------------------------------
diff --git a/be/src/testutil/test-udas.cc b/be/src/testutil/test-udas.cc
index 569853e..0097500 100644
--- a/be/src/testutil/test-udas.cc
+++ b/be/src/testutil/test-udas.cc
@@ -130,3 +130,39 @@ void ArgIsConstUpdate(FunctionContext* context, const IntVal& val,
void ArgIsConstMerge(FunctionContext* context, const BooleanVal& src, BooleanVal* dst) {
dst->val |= src.val;
}
+
+// Defines aggregate function for testing NULL handling. Returns NULL if an even number
+// of non-NULL inputs are consumed or 1 if an odd number of non-NULL inputs are consumed.
+void ToggleNullInit(FunctionContext* context, IntVal* total) {
+ *total = IntVal::null();
+}
+
+void ToggleNullUpdate(FunctionContext* context, const IntVal& val, IntVal* total) {
+ if (total->is_null) {
+ *total = IntVal(1);
+ } else {
+ *total = IntVal::null();
+ }
+}
+
+void ToggleNullMerge(FunctionContext* context, const IntVal& src, IntVal* dst) {
+ if (src.is_null != dst->is_null) {
+ *dst = IntVal(1);
+ } else {
+ *dst = IntVal::null();
+ }
+}
+
+// Defines aggregate function for testing input NULL handling. Returns the number of NULL
+// input values.
+void CountNullsInit(FunctionContext* context, BigIntVal* total) {
+ *total = BigIntVal(0);
+}
+
+void CountNullsUpdate(FunctionContext* context, const BigIntVal& val, BigIntVal* total) {
+ if (val.is_null) ++total->val;
+}
+
+void CountNullsMerge(FunctionContext* context, const BigIntVal& src, BigIntVal* dst) {
+ dst->val += src.val;
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/testutil/test-udfs.cc
----------------------------------------------------------------------
diff --git a/be/src/testutil/test-udfs.cc b/be/src/testutil/test-udfs.cc
index efdfa0a..56d4524 100644
--- a/be/src/testutil/test-udfs.cc
+++ b/be/src/testutil/test-udfs.cc
@@ -56,11 +56,7 @@ IntVal AllTypes(
StringVal NoArgs(FunctionContext* context) {
const char* result = "string";
StringVal ret(context, strlen(result));
- // TODO: llvm 3.3 seems to have a bug if we use memcpy here making
- // the IR udf crash. This is fixed in 3.3.1. Fix this when we upgrade.
- //memcpy(ret.ptr, result, strlen(result));
- // IMPALA-775
- for (int i = 0; i < strlen(result); ++i) ret.ptr[i] = result[i];
+ memcpy(ret.ptr, result, strlen(result));
return ret;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/util/tuple-row-compare.cc
----------------------------------------------------------------------
diff --git a/be/src/util/tuple-row-compare.cc b/be/src/util/tuple-row-compare.cc
index 69892ae..c159853 100644
--- a/be/src/util/tuple-row-compare.cc
+++ b/be/src/util/tuple-row-compare.cc
@@ -205,7 +205,7 @@ Status TupleRowComparator::CodegenCompare(LlvmCodeGen* codegen, Function** fn) {
prototype.AddArgument("lhs", tuple_row_type);
prototype.AddArgument("rhs", tuple_row_type);
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[4];
*fn = prototype.GeneratePrototype(&builder, args);
Value* lhs_ctxs_arg = args[0];
[32/50] [abbrv] incubator-impala git commit: IMPALA-4454:
test_kudu.TestShowCreateTable flaky
Posted by ta...@apache.org.
IMPALA-4454: test_kudu.TestShowCreateTable flaky
The cause of the flakiness is Kudu CREATE TABLE operations
that are sometimes taking a long time, leading to timeouts
in the hiveserver2 connection. This patch adds the ability
for tests using the 'conn' pytest fixture to specify a
timeout to connect(), and sets a timeout of 5 minutes for
this test.
Change-Id: I2727c27ff66140ac4043bcad332cd4e1d72b255f
Reviewed-on: http://gerrit.cloudera.org:8080/5040
Reviewed-by: Michael Brown <mi...@cloudera.com>
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/d15f86cb
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/d15f86cb
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/d15f86cb
Branch: refs/heads/hadoop-next
Commit: d15f86cb6fa5eb482b039f036dab3d979c7513c8
Parents: c68734a
Author: Thomas Tauber-Marshall <tm...@cloudera.com>
Authored: Thu Nov 10 15:13:56 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Fri Nov 11 20:04:01 2016 +0000
----------------------------------------------------------------------
tests/conftest.py | 14 +++++++++-----
tests/query_test/test_kudu.py | 5 +++++
2 files changed, 14 insertions(+), 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d15f86cb/tests/conftest.py
----------------------------------------------------------------------
diff --git a/tests/conftest.py b/tests/conftest.py
index c75f117..6bbbf78 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -36,6 +36,7 @@ from tests.util.filesystem_utils import FILESYSTEM, ISILON_WEBHDFS_PORT
logging.basicConfig(level=logging.INFO, format='%(threadName)s: %(message)s')
LOG = logging.getLogger('test_configuration')
+DEFAULT_CONN_TIMEOUT = 45
def _get_default_nn_http_addr():
"""Return the namenode ip and webhdfs port if the default shouldn't be used"""
@@ -320,6 +321,7 @@ def conn(request):
provided by get_db_name(), it must not exist. Classes that use both
auto_create_db() and get_db_name() should generate a random name in
get_db_name() and cache it.
+ - get_conn_timeout(): The timeout, in seconds, to use for this connection.
The returned connection will have a 'db_name' property.
See the 'unique_database' fixture above if you want to use Impala's custom python
@@ -327,8 +329,10 @@ def conn(request):
"""
db_name = __call_cls_method_if_exists(request.cls, "get_db_name")
use_unique_conn = __call_cls_method_if_exists(request.cls, "auto_create_db")
+ timeout = __call_cls_method_if_exists(request.cls, "get_conn_timeout") or \
+ DEFAULT_CONN_TIMEOUT
if use_unique_conn:
- with __unique_conn(db_name=db_name) as conn:
+ with __unique_conn(db_name=db_name, timeout=timeout) as conn:
yield conn
else:
with __auto_closed_conn(db_name=db_name) as conn:
@@ -345,7 +349,7 @@ def __call_cls_method_if_exists(cls, method_name):
@contextlib.contextmanager
-def __unique_conn(db_name=None):
+def __unique_conn(db_name=None, timeout=DEFAULT_CONN_TIMEOUT):
"""Connects to Impala and creates a new database, then returns a connection to it.
This is intended to be used in a "with" block. Upon exit, the database will be
dropped. A database name can be provided by 'db_name', a database by that name
@@ -362,7 +366,7 @@ def __unique_conn(db_name=None):
with __auto_closed_conn() as conn:
with __auto_closed_cursor(conn) as cur:
cur.execute("CREATE DATABASE %s" % db_name)
- with __auto_closed_conn(db_name=db_name) as conn:
+ with __auto_closed_conn(db_name=db_name, timeout=timeout) as conn:
try:
yield conn
finally:
@@ -378,13 +382,13 @@ def __unique_conn(db_name=None):
@contextlib.contextmanager
-def __auto_closed_conn(db_name=None):
+def __auto_closed_conn(db_name=None, timeout=DEFAULT_CONN_TIMEOUT):
"""Returns a connection to Impala. This is intended to be used in a "with" block. The
connection will be closed upon exiting the block.
The returned connection will have a 'db_name' property.
"""
- conn = impala_connect(database=db_name)
+ conn = impala_connect(database=db_name, timeout=timeout)
try:
conn.db_name = db_name
yield conn
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d15f86cb/tests/query_test/test_kudu.py
----------------------------------------------------------------------
diff --git a/tests/query_test/test_kudu.py b/tests/query_test/test_kudu.py
index 2a88137..f5579ed 100644
--- a/tests/query_test/test_kudu.py
+++ b/tests/query_test/test_kudu.py
@@ -200,6 +200,11 @@ class TestCreateExternalTable(KuduTestSuite):
class TestShowCreateTable(KuduTestSuite):
+ @classmethod
+ def get_conn_timeout(cls):
+ # For IMPALA-4454
+ return 60 * 5 # 5 minutes
+
def assert_show_create_equals(self, cursor, create_sql, show_create_sql):
"""Executes 'create_sql' to create a table, then runs "SHOW CREATE TABLE" and checks
that the output is the same as 'show_create_sql'. 'create_sql' and
[47/50] [abbrv] incubator-impala git commit: IMPALA-4444: Transfer
row group resources to row batch on scan failure
Posted by ta...@apache.org.
IMPALA-4444: Transfer row group resources to row batch on scan failure
Previously, if any column reader fails in HdfsParqetScanner::AssembleRows(),
the memory pools associated with the ScratchTupleBatch will be freed. This
is problematic as ScratchTupleBatch may contain memory pools which are still
referenced by row batches shipped upstream. This is possible because memory
pools used by parquet column readers (e.g. decompressor_pool_) won't be
transferred to a ScratchTupleBatch until the data page is exhausted. So,
the memory pools of the previous data page is always attached to the
ScratchTupleBatch of the current data page. On a scan failure, it's not
necessarily safe to free the memory pool attached to the current ScratchTupleBatch.
This patch fixes the problem above by transferring the memory pool and other
resources associated with a row group to the current row batch in the parquet
scanner on scan failure so it can eventually be freed by upstream operators as
the row batch is consumed.
Change-Id: Id70df470e98dd96284fd176bfbb946e9637ad126
Reviewed-on: http://gerrit.cloudera.org:8080/5052
Reviewed-by: Michael Ho <kw...@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/38ee3b69
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/38ee3b69
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/38ee3b69
Branch: refs/heads/hadoop-next
Commit: 38ee3b6942f3e044555ee399c51cba65f0b35267
Parents: 6937fa9
Author: Michael Ho <kw...@cloudera.com>
Authored: Thu Nov 10 13:33:46 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 23:02:50 2016 +0000
----------------------------------------------------------------------
be/src/exec/exec-node.cc | 2 +-
be/src/exec/hdfs-parquet-scanner.cc | 3 ++-
2 files changed, 3 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/38ee3b69/be/src/exec/exec-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/exec-node.cc b/be/src/exec/exec-node.cc
index 255217f..1d93626 100644
--- a/be/src/exec/exec-node.cc
+++ b/be/src/exec/exec-node.cc
@@ -429,7 +429,7 @@ Status ExecNode::ExecDebugAction(TExecNodePhase::type phase, RuntimeState* state
return Status::OK();
}
if (debug_action_ == TDebugAction::MEM_LIMIT_EXCEEDED) {
- mem_tracker()->MemLimitExceeded(state, "Debug Action: MEM_LIMIT_EXCEEDED");
+ return mem_tracker()->MemLimitExceeded(state, "Debug Action: MEM_LIMIT_EXCEEDED");
}
return Status::OK();
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/38ee3b69/be/src/exec/hdfs-parquet-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-parquet-scanner.cc b/be/src/exec/hdfs-parquet-scanner.cc
index bd5d65c..6b157aa 100644
--- a/be/src/exec/hdfs-parquet-scanner.cc
+++ b/be/src/exec/hdfs-parquet-scanner.cc
@@ -537,8 +537,9 @@ Status HdfsParquetScanner::AssembleRows(
bool num_tuples_mismatch = c != 0 && last_num_tuples != scratch_batch_->num_tuples;
if (UNLIKELY(!continue_execution || num_tuples_mismatch)) {
// Skipping this row group. Free up all the resources with this row group.
- scratch_batch_->mem_pool()->FreeAll();
+ FlushRowGroupResources(row_batch);
scratch_batch_->num_tuples = 0;
+ DCHECK(scratch_batch_->AtEnd());
*skip_row_group = true;
if (num_tuples_mismatch) {
parse_status_.MergeStatus(Substitute("Corrupt Parquet file '$0': column '$1' "
[19/50] [abbrv] incubator-impala git commit: IMPALA-3710: Kudu DML
should ignore conflicts by default
Posted by ta...@apache.org.
IMPALA-3710: Kudu DML should ignore conflicts by default
Removes the non-standard IGNORE syntax that was allowed for
DML into Kudu tables to indicate that certain errors should
be ignored, i.e. not fail the query and continue. However,
because there is no way to 'roll back' mutations that
occurred before an error occurs, tables are left in an
inconsistent state and it's difficult to know what rows were
successfully modified vs which rows were not. Instead, this
change makes it so that we always 'ignore' these conflicts,
i.e. a 'best effort'. In the future, when Kudu will provide
the mechanisms Impala needs to provide a notion of isolation
levels, then Impala will be able to provide options for more
traditional semantics.
After this change, the following errors are ignored:
* INSERT where the PK already exists
* UPDATE/DELETE where the PK doesn't exist
Another follow-up patch will change other violations to be
handled in this way as well, e.g. nulls inserted in
non-nullable cols.
Reporting:
The number of rows inserted is reported to the coordinator,
which makes the aggregate available to the shell and via the
profile.
TODO: Return rows modified for INSERT via HS2 (IMPALA-1789).
TODO: Return rows modified for other CRUD (beeswax+hs2) (IMPALA-3713).
TODO: Return error counts for specific warnings (IMPALA-4416).
Testing:
Updated tests. Ran all functional tests. More tests will be
needed when other conflicts are handled in the same way.
Change-Id: I83b5beaa982d006da4997a2af061ef7c22cad3f1
Reviewed-on: http://gerrit.cloudera.org:8080/4911
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/08d89a5c
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/08d89a5c
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/08d89a5c
Branch: refs/heads/hadoop-next
Commit: 08d89a5cc3d2135896a7d4518dac7d22e5e66ddf
Parents: ce4c5f6
Author: Matthew Jacobs <mj...@cloudera.com>
Authored: Tue Nov 1 17:52:21 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 20:34:00 2016 +0000
----------------------------------------------------------------------
be/src/exec/kudu-table-sink.cc | 11 ++---
be/src/exec/kudu-table-sink.h | 13 ++---
common/thrift/DataSinks.thrift | 3 --
fe/src/main/cup/sql-parser.cup | 51 ++++++++------------
.../analysis/CreateTableAsSelectStmt.java | 2 +-
.../org/apache/impala/analysis/DeleteStmt.java | 14 +++---
.../org/apache/impala/analysis/InsertStmt.java | 21 +++-----
.../org/apache/impala/analysis/ModifyStmt.java | 7 +--
.../org/apache/impala/analysis/UpdateStmt.java | 21 ++++----
.../apache/impala/planner/KuduTableSink.java | 19 ++------
.../org/apache/impala/planner/TableSink.java | 11 ++---
.../impala/analysis/AnalyzeModifyStmtsTest.java | 2 -
.../org/apache/impala/analysis/ParserTest.java | 6 ---
.../queries/PlannerTest/kudu-delete.test | 18 -------
.../queries/PlannerTest/kudu-update.test | 14 ------
.../queries/PlannerTest/kudu.test | 10 ----
.../queries/QueryTest/kudu_crud.test | 43 ++---------------
17 files changed, 66 insertions(+), 200 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/be/src/exec/kudu-table-sink.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.cc b/be/src/exec/kudu-table-sink.cc
index 14b1889..a58baab 100644
--- a/be/src/exec/kudu-table-sink.cc
+++ b/be/src/exec/kudu-table-sink.cc
@@ -292,13 +292,10 @@ Status KuduTableSink::CheckForErrors(RuntimeState* state) {
// them accordingly.
for (int i = 0; i < errors.size(); ++i) {
kudu::Status e = errors[i]->status();
- // If the sink has the option "ignore_not_found_or_duplicate" set, duplicate key or
- // key already present errors from Kudu in INSERT, UPDATE, or DELETE operations will
- // be ignored.
- if (!kudu_table_sink_.ignore_not_found_or_duplicate ||
- ((sink_action_ == TSinkAction::DELETE && !e.IsNotFound()) ||
- (sink_action_ == TSinkAction::UPDATE && !e.IsNotFound()) ||
- (sink_action_ == TSinkAction::INSERT && !e.IsAlreadyPresent()))) {
+ // 'Duplicate key' or 'key already present' errors from Kudu do not fail the query.
+ if ((sink_action_ == TSinkAction::DELETE && !e.IsNotFound()) ||
+ (sink_action_ == TSinkAction::UPDATE && !e.IsNotFound()) ||
+ (sink_action_ == TSinkAction::INSERT && !e.IsAlreadyPresent())) {
if (status.ok()) {
status = Status(strings::Substitute(
"Kudu error(s) reported, first error: $0", e.ToString()));
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/be/src/exec/kudu-table-sink.h
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.h b/be/src/exec/kudu-table-sink.h
index c37b15d..adf264e 100644
--- a/be/src/exec/kudu-table-sink.h
+++ b/be/src/exec/kudu-table-sink.h
@@ -45,12 +45,13 @@ namespace impala {
///
/// Kudu doesn't have transactions yet, so some rows may fail to write while others are
/// successful. The Kudu client reports errors, some of which may be considered to be
-/// expected: rows that fail to be written/updated/deleted due to a key conflict while
-/// the IGNORE option is specified, and these will not result in the sink returning an
-/// error. These errors when IGNORE is not specified, or any other kind of error
-/// reported by Kudu result in the sink returning an error status. The first non-ignored
-/// error is returned in the sink's Status. All reported errors (ignored or not) will be
-/// logged via the RuntimeState.
+/// expected: rows that fail to be written/updated/deleted due to a key conflict will not
+/// result in the sink returning an error. Any other kind of error reported by Kudu
+/// results in the sink returning an error status. The first non-ignored error is
+/// returned in the sink's Status. All reported errors (ignored or not) will be logged
+/// via the RuntimeState.
+/// TODO: Handle other data/constraint-violation errors as ignored, e.g. null in
+/// non-nullable col
class KuduTableSink : public DataSink {
public:
KuduTableSink(const RowDescriptor& row_desc,
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/common/thrift/DataSinks.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/DataSinks.thrift b/common/thrift/DataSinks.thrift
index 26f74cf..2a57304 100644
--- a/common/thrift/DataSinks.thrift
+++ b/common/thrift/DataSinks.thrift
@@ -74,9 +74,6 @@ struct TKuduTableSink {
// sink and holds the index of the corresponsding column in the Kudu schema,
// e.g. 'exprs[i]' references 'kudu_table.column(referenced_cols[i])'
1: optional list<i32> referenced_columns;
-
- // Defines if duplicate or not found keys should be ignored
- 2: optional bool ignore_not_found_or_duplicate;
}
// Sink to create the build side of a JoinNode.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/main/cup/sql-parser.cup
----------------------------------------------------------------------
diff --git a/fe/src/main/cup/sql-parser.cup b/fe/src/main/cup/sql-parser.cup
index c0865c4..57d5a24 100644
--- a/fe/src/main/cup/sql-parser.cup
+++ b/fe/src/main/cup/sql-parser.cup
@@ -479,7 +479,6 @@ nonterminal CreateUdaStmt create_uda_stmt;
nonterminal ShowFunctionsStmt show_functions_stmt;
nonterminal DropFunctionStmt drop_function_stmt;
nonterminal TFunctionCategory opt_function_category;
-nonterminal Boolean opt_ignore;
precedence left KW_OR;
precedence left KW_AND;
@@ -677,47 +676,44 @@ explain_stmt ::=
// tbl(col1,...) etc) and the PARTITION clause. If the column permutation is present, the
// query statement clause is optional as well.
insert_stmt ::=
- opt_with_clause:w KW_INSERT KW_OVERWRITE opt_ignore:ignore opt_kw_table table_name:table
+ opt_with_clause:w KW_INSERT KW_OVERWRITE opt_kw_table table_name:table
LPAREN opt_ident_list:col_perm RPAREN partition_clause:list opt_plan_hints:hints
opt_query_stmt:query
{:
- RESULT = InsertStmt.createInsert(w, table, true, list, hints, query, col_perm,
- ignore);
+ RESULT = InsertStmt.createInsert(w, table, true, list, hints, query, col_perm);
:}
| opt_with_clause:w KW_INSERT KW_OVERWRITE
- opt_ignore:ignore opt_kw_table table_name:table
+ opt_kw_table table_name:table
partition_clause:list opt_plan_hints:hints query_stmt:query
{:
- RESULT = InsertStmt.createInsert(w, table, true, list, hints, query, null, ignore);
+ RESULT = InsertStmt.createInsert(w, table, true, list, hints, query, null);
:}
- | opt_with_clause:w KW_INSERT opt_ignore:ignore KW_INTO
- opt_kw_table table_name:table LPAREN opt_ident_list:col_perm RPAREN
+ | opt_with_clause:w KW_INSERT KW_INTO opt_kw_table table_name:table
+ LPAREN opt_ident_list:col_perm RPAREN
partition_clause:list opt_plan_hints:hints opt_query_stmt:query
{:
- RESULT = InsertStmt.createInsert(w, table, false, list, hints, query, col_perm,
- ignore);
+ RESULT = InsertStmt.createInsert(w, table, false, list, hints, query, col_perm);
:}
- | opt_with_clause:w KW_INSERT
- opt_ignore:ignore KW_INTO opt_kw_table table_name:table partition_clause:list
- opt_plan_hints:hints query_stmt:query
+ | opt_with_clause:w KW_INSERT KW_INTO opt_kw_table table_name:table
+ partition_clause:list opt_plan_hints:hints query_stmt:query
{:
- RESULT = InsertStmt.createInsert(w, table, false, list, hints, query, null, ignore);
+ RESULT = InsertStmt.createInsert(w, table, false, list, hints, query, null);
:}
;
// Update statements have an optional WHERE and optional FROM clause.
update_stmt ::=
- KW_UPDATE opt_ignore:ignore dotted_path:target_table KW_SET update_set_expr_list:values
+ KW_UPDATE dotted_path:target_table KW_SET update_set_expr_list:values
where_clause:where_predicate
{:
FromClause from_clause = new FromClause(
Lists.newArrayList(new TableRef(target_table, null)));
- RESULT = new UpdateStmt(target_table, from_clause, values, where_predicate, ignore);
+ RESULT = new UpdateStmt(target_table, from_clause, values, where_predicate);
:}
- | KW_UPDATE opt_ignore:ignore dotted_path:target_table
+ | KW_UPDATE dotted_path:target_table
KW_SET update_set_expr_list:values
from_clause:tables where_clause:where_predicate
- {: RESULT = new UpdateStmt(target_table, tables, values, where_predicate, ignore); :}
+ {: RESULT = new UpdateStmt(target_table, tables, values, where_predicate); :}
;
update_set_expr_list ::=
@@ -750,21 +746,21 @@ upsert_stmt ::=
// keyword followed by a table alias or reference and a full FROM clause. In all cases
// a WHERE clause may be present.
delete_stmt ::=
- KW_DELETE opt_ignore:ignore dotted_path:target_table where_clause:where
+ KW_DELETE dotted_path:target_table where_clause:where
{:
FromClause from_clause = new FromClause(
Lists.newArrayList(new TableRef(target_table, null)));
- RESULT = new DeleteStmt(target_table, from_clause, where, ignore);
+ RESULT = new DeleteStmt(target_table, from_clause, where);
:}
- | KW_DELETE opt_ignore:ignore KW_FROM dotted_path:target_table where_clause:where
+ | KW_DELETE KW_FROM dotted_path:target_table where_clause:where
{:
FromClause from_clause = new FromClause(
Lists.newArrayList(new TableRef(target_table, null)));
- RESULT = new DeleteStmt(target_table, from_clause, where, ignore);
+ RESULT = new DeleteStmt(target_table, from_clause, where);
:}
- | KW_DELETE opt_ignore:ignore dotted_path:target_table from_clause:from
+ | KW_DELETE dotted_path:target_table from_clause:from
where_clause:where
- {: RESULT = new DeleteStmt(target_table, from, where, ignore); :}
+ {: RESULT = new DeleteStmt(target_table, from, where); :}
;
opt_query_stmt ::=
@@ -786,13 +782,6 @@ opt_kw_table ::=
| /* empty */
;
-opt_ignore ::=
- KW_IGNORE
- {: RESULT = true; :}
- | /* empty */
- {: RESULT = false; :}
- ;
-
show_roles_stmt ::=
KW_SHOW KW_ROLES
{: RESULT = new ShowRolesStmt(false, null); :}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/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 2eb399f..1e53d1e 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CreateTableAsSelectStmt.java
@@ -81,7 +81,7 @@ public class CreateTableAsSelectStmt extends StatementBase {
}
}
insertStmt_ = InsertStmt.createInsert(
- null, createStmt.getTblName(), false, pkvs, null, queryStmt, null, false);
+ null, createStmt.getTblName(), false, pkvs, null, queryStmt, null);
}
public QueryStmt getQueryStmt() { return insertStmt_.getQueryStmt(); }
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/main/java/org/apache/impala/analysis/DeleteStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/DeleteStmt.java b/fe/src/main/java/org/apache/impala/analysis/DeleteStmt.java
index 62606b8..9d84baa 100644
--- a/fe/src/main/java/org/apache/impala/analysis/DeleteStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/DeleteStmt.java
@@ -21,12 +21,11 @@ import java.util.List;
import org.apache.impala.common.Pair;
import org.apache.impala.planner.DataSink;
-import org.apache.impala.planner.KuduTableSink;
import org.apache.impala.planner.TableSink;
+
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
-import org.apache.hadoop.hbase.client.Delete;
/**
* Representation of a DELETE statement.
@@ -42,22 +41,22 @@ import org.apache.hadoop.hbase.client.Delete;
public class DeleteStmt extends ModifyStmt {
public DeleteStmt(List<String> targetTablePath, FromClause tableRefs,
- Expr wherePredicate, boolean ignoreNotFound) {
+ Expr wherePredicate) {
super(targetTablePath, tableRefs, Lists.<Pair<SlotRef, Expr>>newArrayList(),
- wherePredicate, ignoreNotFound);
+ wherePredicate);
}
public DeleteStmt(DeleteStmt other) {
super(other.targetTablePath_, other.fromClause_.clone(),
- Lists.<Pair<SlotRef, Expr>>newArrayList(), other.wherePredicate_.clone(),
- other.ignoreNotFound_);
+ Lists.<Pair<SlotRef, Expr>>newArrayList(), other.wherePredicate_.clone());
}
+ @Override
public DataSink createDataSink() {
// analyze() must have been called before.
Preconditions.checkState(table_ != null);
TableSink tableSink = TableSink.create(table_, TableSink.Op.DELETE,
- ImmutableList.<Expr>of(), referencedColumns_, false, ignoreNotFound_);
+ ImmutableList.<Expr>of(), referencedColumns_, false);
Preconditions.checkState(!referencedColumns_.isEmpty());
return tableSink;
}
@@ -71,7 +70,6 @@ public class DeleteStmt extends ModifyStmt {
public String toSql() {
StringBuilder b = new StringBuilder();
b.append("DELETE");
- if (ignoreNotFound_) b.append(" IGNORE");
if (fromClause_.size() > 1 || targetTableRef_.hasExplicitAlias()) {
b.append(" ");
if (targetTableRef_.hasExplicitAlias()) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/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 da360b1..55005f9 100644
--- a/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/InsertStmt.java
@@ -146,32 +146,26 @@ public class InsertStmt extends StatementBase {
// END: Members that need to be reset()
/////////////////////////////////////////
- // For tables with primary keys, indicates if duplicate key errors are ignored.
- private final boolean ignoreDuplicates_;
-
// True iff this is an UPSERT operation. Only supported for Kudu tables.
private final boolean isUpsert_;
public static InsertStmt createInsert(WithClause withClause, TableName targetTable,
boolean overwrite, List<PartitionKeyValue> partitionKeyValues,
- List<String> planHints, QueryStmt queryStmt, List<String> columnPermutation,
- boolean ignoreDuplicates) {
+ List<String> planHints, QueryStmt queryStmt, List<String> columnPermutation) {
return new InsertStmt(withClause, targetTable, overwrite, partitionKeyValues,
- planHints, queryStmt, columnPermutation, ignoreDuplicates, false);
+ planHints, queryStmt, columnPermutation, false);
}
public static InsertStmt createUpsert(WithClause withClause, TableName targetTable,
List<String> planHints, QueryStmt queryStmt, List<String> columnPermutation) {
return new InsertStmt(withClause, targetTable, false, null, planHints, queryStmt,
- columnPermutation, false, true);
+ columnPermutation, true);
}
protected InsertStmt(WithClause withClause, TableName targetTable, boolean overwrite,
List<PartitionKeyValue> partitionKeyValues, List<String> planHints,
- QueryStmt queryStmt, List<String> columnPermutation, boolean ignoreDuplicates,
- boolean isUpsert) {
- Preconditions.checkState(!isUpsert || (!overwrite && !ignoreDuplicates &&
- partitionKeyValues == null));
+ QueryStmt queryStmt, List<String> columnPermutation, boolean isUpsert) {
+ Preconditions.checkState(!isUpsert || (!overwrite && partitionKeyValues == null));
withClause_ = withClause;
targetTableName_ = targetTable;
originalTableName_ = targetTableName_;
@@ -182,7 +176,6 @@ public class InsertStmt extends StatementBase {
needsGeneratedQueryStatement_ = (queryStmt == null);
columnPermutation_ = columnPermutation;
table_ = null;
- ignoreDuplicates_ = ignoreDuplicates;
isUpsert_ = isUpsert;
}
@@ -201,7 +194,6 @@ public class InsertStmt extends StatementBase {
needsGeneratedQueryStatement_ = other.needsGeneratedQueryStatement_;
columnPermutation_ = other.columnPermutation_;
table_ = other.table_;
- ignoreDuplicates_ = other.ignoreDuplicates_;
isUpsert_ = other.isUpsert_;
}
@@ -789,7 +781,7 @@ public class InsertStmt extends StatementBase {
Preconditions.checkState(table_ != null);
Preconditions.checkState(isUpsert_ || mentionedUpsertColumns_.isEmpty());
return TableSink.create(table_, isUpsert_ ? TableSink.Op.UPSERT : TableSink.Op.INSERT,
- partitionKeyExprs_, mentionedUpsertColumns_, overwrite_, ignoreDuplicates_);
+ partitionKeyExprs_, mentionedUpsertColumns_, overwrite_);
}
/**
@@ -813,7 +805,6 @@ public class InsertStmt extends StatementBase {
if (overwrite_) {
strBuilder.append("OVERWRITE ");
} else {
- if (ignoreDuplicates_) strBuilder.append("IGNORE ");
strBuilder.append("INTO ");
}
strBuilder.append("TABLE " + originalTableName_);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/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 00f99a5..0107079 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ModifyStmt.java
@@ -92,17 +92,12 @@ public abstract class ModifyStmt extends StatementBase {
// position in the target table. Set in createSourceStmt() during analysis.
protected ArrayList<Integer> referencedColumns_;
- // On tables with a primary key, ignore key not found errors.
- protected final boolean ignoreNotFound_;
-
public ModifyStmt(List<String> targetTablePath, FromClause fromClause,
- List<Pair<SlotRef, Expr>> assignmentExprs,
- Expr wherePredicate, boolean ignoreNotFound) {
+ List<Pair<SlotRef, Expr>> assignmentExprs, Expr wherePredicate) {
targetTablePath_ = Preconditions.checkNotNull(targetTablePath);
fromClause_ = Preconditions.checkNotNull(fromClause);
assignments_ = Preconditions.checkNotNull(assignmentExprs);
wherePredicate_ = wherePredicate;
- ignoreNotFound_ = ignoreNotFound;
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/main/java/org/apache/impala/analysis/UpdateStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/UpdateStmt.java b/fe/src/main/java/org/apache/impala/analysis/UpdateStmt.java
index 8b0d96d..9a1bc9e 100644
--- a/fe/src/main/java/org/apache/impala/analysis/UpdateStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/UpdateStmt.java
@@ -17,18 +17,18 @@
package org.apache.impala.analysis;
+import static java.lang.String.format;
+
import java.util.List;
import org.apache.impala.common.Pair;
import org.apache.impala.planner.DataSink;
-import org.apache.impala.planner.KuduTableSink;
import org.apache.impala.planner.TableSink;
+
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
-import static java.lang.String.format;
-
/**
* Representation of an Update statement.
*
@@ -47,26 +47,25 @@ import static java.lang.String.format;
* Currently, only Kudu tables can be updated.
*/
public class UpdateStmt extends ModifyStmt {
- public UpdateStmt(List<String> targetTablePath, FromClause tableRefs,
- List<Pair<SlotRef, Expr>> assignmentExprs, Expr wherePredicate,
- boolean ignoreNotFound) {
- super(targetTablePath, tableRefs, assignmentExprs, wherePredicate, ignoreNotFound);
+ public UpdateStmt(List<String> targetTablePath, FromClause tableRefs,
+ List<Pair<SlotRef, Expr>> assignmentExprs, Expr wherePredicate) {
+ super(targetTablePath, tableRefs, assignmentExprs, wherePredicate);
}
public UpdateStmt(UpdateStmt other) {
super(other.targetTablePath_, other.fromClause_.clone(),
- Lists.<Pair<SlotRef, Expr>>newArrayList(), other.wherePredicate_,
- other.ignoreNotFound_);
+ Lists.<Pair<SlotRef, Expr>>newArrayList(), other.wherePredicate_);
}
/**
* Return an instance of a KuduTableSink specialized as an Update operation.
*/
+ @Override
public DataSink createDataSink() {
// analyze() must have been called before.
Preconditions.checkState(table_ != null);
DataSink dataSink = TableSink.create(table_, TableSink.Op.UPDATE,
- ImmutableList.<Expr>of(), referencedColumns_, false, ignoreNotFound_);
+ ImmutableList.<Expr>of(), referencedColumns_, false);
Preconditions.checkState(!referencedColumns_.isEmpty());
return dataSink;
}
@@ -81,8 +80,6 @@ public class UpdateStmt extends ModifyStmt {
StringBuilder b = new StringBuilder();
b.append("UPDATE ");
- if (ignoreNotFound_) b.append("IGNORE ");
-
if (fromClause_ == null) {
b.append(targetTableRef_.toSql());
} else {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/main/java/org/apache/impala/planner/KuduTableSink.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/KuduTableSink.java b/fe/src/main/java/org/apache/impala/planner/KuduTableSink.java
index 0a99af4..35b9022 100644
--- a/fe/src/main/java/org/apache/impala/planner/KuduTableSink.java
+++ b/fe/src/main/java/org/apache/impala/planner/KuduTableSink.java
@@ -30,6 +30,7 @@ import org.apache.impala.thrift.TExplainLevel;
import org.apache.impala.thrift.TKuduTableSink;
import org.apache.impala.thrift.TTableSink;
import org.apache.impala.thrift.TTableSinkType;
+
import com.google.common.collect.Lists;
/**
@@ -40,16 +41,13 @@ public class KuduTableSink extends TableSink {
// Optional list of referenced Kudu table column indices. The position of a result
// expression i matches a column index into the Kudu schema at targetColdIdxs[i].
- private ArrayList<Integer> targetColIdxs_;
-
- private final boolean ignoreNotFoundOrDuplicate_;
+ private final ArrayList<Integer> targetColIdxs_;
public KuduTableSink(Table targetTable, Op sinkOp,
- List<Integer> referencedColumns, boolean ignoreNotFoundOrDuplicate) {
+ List<Integer> referencedColumns) {
super(targetTable, sinkOp);
targetColIdxs_ = referencedColumns != null
? Lists.newArrayList(referencedColumns) : null;
- ignoreNotFoundOrDuplicate_ = ignoreNotFoundOrDuplicate;
}
@Override
@@ -58,16 +56,6 @@ public class KuduTableSink extends TableSink {
StringBuilder output = new StringBuilder();
output.append(prefix + sinkOp_.toExplainString());
output.append(" KUDU [" + targetTable_.getFullName() + "]\n");
- if (sinkOp_ != Op.UPSERT) {
- output.append(detailPrefix);
- if (sinkOp_ == Op.INSERT) {
- output.append("check unique keys: ");
- } else {
- output.append("check keys exist: ");
- }
- output.append(ignoreNotFoundOrDuplicate_);
- output.append("\n");
- }
if (explainLevel.ordinal() >= TExplainLevel.EXTENDED.ordinal()) {
output.append(PrintUtils.printHosts(detailPrefix, fragment_.getNumNodes()));
output.append(PrintUtils.printMemCost(" ", perHostMemCost_));
@@ -83,7 +71,6 @@ public class KuduTableSink extends TableSink {
TTableSinkType.KUDU, sinkOp_.toThrift());
TKuduTableSink tKuduSink = new TKuduTableSink();
tKuduSink.setReferenced_columns(targetColIdxs_);
- tKuduSink.setIgnore_not_found_or_duplicate(ignoreNotFoundOrDuplicate_);
tTableSink.setKudu_table_sink(tKuduSink);
result.table_sink = tTableSink;
return result;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/main/java/org/apache/impala/planner/TableSink.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/TableSink.java b/fe/src/main/java/org/apache/impala/planner/TableSink.java
index 102b280..742e6c9 100644
--- a/fe/src/main/java/org/apache/impala/planner/TableSink.java
+++ b/fe/src/main/java/org/apache/impala/planner/TableSink.java
@@ -17,15 +17,16 @@
package org.apache.impala.planner;
+import java.util.List;
+
import org.apache.impala.analysis.Expr;
import org.apache.impala.catalog.HBaseTable;
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.catalog.KuduTable;
import org.apache.impala.catalog.Table;
import org.apache.impala.thrift.TSinkAction;
-import com.google.common.base.Preconditions;
-import java.util.List;
+import com.google.common.base.Preconditions;
/**
* A DataSink that writes into a table.
@@ -89,7 +90,7 @@ public abstract class TableSink extends DataSink {
*/
public static TableSink create(Table table, Op sinkAction,
List<Expr> partitionKeyExprs, List<Integer> referencedColumns,
- boolean overwrite, boolean ignoreDuplicates) {
+ boolean overwrite) {
if (table instanceof HdfsTable) {
// Hdfs only supports inserts.
Preconditions.checkState(sinkAction == Op.INSERT);
@@ -112,9 +113,7 @@ public abstract class TableSink extends DataSink {
Preconditions.checkState(overwrite == false);
// Partition clauses don't make sense for Kudu inserts.
Preconditions.checkState(partitionKeyExprs.isEmpty());
- // UPSERT is incompatible with ignoreDuplicates.
- Preconditions.checkState(sinkAction != Op.UPSERT || !ignoreDuplicates);
- return new KuduTableSink(table, sinkAction, referencedColumns, ignoreDuplicates);
+ return new KuduTableSink(table, sinkAction, referencedColumns);
} else {
throw new UnsupportedOperationException(
"Cannot create data sink into table of type: " + table.getClass().getName());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/test/java/org/apache/impala/analysis/AnalyzeModifyStmtsTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/AnalyzeModifyStmtsTest.java b/fe/src/test/java/org/apache/impala/analysis/AnalyzeModifyStmtsTest.java
index 939d499..152add6 100644
--- a/fe/src/test/java/org/apache/impala/analysis/AnalyzeModifyStmtsTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/AnalyzeModifyStmtsTest.java
@@ -76,7 +76,6 @@ public class AnalyzeModifyStmtsTest extends AnalyzerTest {
".testtbl a on a.id = b.id where a.id = 10");
AnalyzesOk("delete from functional_kudu.testtbl");
- AnalyzesOk("delete ignore from functional_kudu.testtbl");
AnalyzesOk("delete functional_kudu.testtbl from functional_kudu.testtbl");
AnalyzesOk("delete a from functional_kudu.testtbl a");
AnalyzesOk("delete a from functional_kudu.testtbl a join functional.testtbl b " +
@@ -87,7 +86,6 @@ public class AnalyzeModifyStmtsTest extends AnalyzerTest {
public void TestUpdate() {
TestUtils.assumeKuduIsSupported();
AnalyzesOk("update functional_kudu.dimtbl set name = 'Oskar'");
- AnalyzesOk("update ignore functional_kudu.dimtbl set name = 'Oskar'");
// Correct default database resolution
AnalyzesOk("update dimtbl set name = 'Oskar'", createAnalyzer("functional_kudu"));
// Correct table alias resolution
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
index 98863ce..0affd4e 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
@@ -1615,8 +1615,6 @@ public class ParserTest extends FrontendTestBase {
"select a from src where b > 5");
ParserError("insert into table t partition [shuffle] (pk1=10 pk2=20) " +
"select a from src where b > 5");
-
- ParsesOk("insert ignore into table t values (1,2,3)");
}
@Test
@@ -1666,8 +1664,6 @@ public class ParserTest extends FrontendTestBase {
ParsesOk("update t set x = (3 + length(\"hallo\")) where a < 'adasas'");
ParsesOk("update t set x = 3");
ParsesOk("update t set x=3, x=4 from a.b t where b = 10");
- ParsesOk("update ignore t set x = 3");
- ParsesOk("update ignore t set x=3, x=4 from a.b t where b = 10");
ParserError("update t");
ParserError("update t set x < 3");
ParserError("update t set x");
@@ -1687,11 +1683,9 @@ public class ParserTest extends FrontendTestBase {
@Test
public void TestDelete() {
ParsesOk("delete from t");
- ParsesOk("delete ignore from t");
ParsesOk("delete a from t a");
ParsesOk("delete a from t a join b on a.id = b.id where true");
ParsesOk("delete a from t a join b where true");
- ParsesOk("delete ignore a from t a join b where true");
ParsesOk("delete t from t");
ParsesOk("delete t from t where a < b");
ParsesOk("delete a from t a where a < b");
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/testdata/workloads/functional-planner/queries/PlannerTest/kudu-delete.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/kudu-delete.test b/testdata/workloads/functional-planner/queries/PlannerTest/kudu-delete.test
index 50c5b12..3a4b97a 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/kudu-delete.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/kudu-delete.test
@@ -1,37 +1,21 @@
delete from functional_kudu.testtbl
---- PLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
---- DISTRIBUTEDPLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
-|
-00:SCAN KUDU [functional_kudu.testtbl]
-====
-delete ignore from functional_kudu.testtbl
----- PLAN
-DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: true
-|
-00:SCAN KUDU [functional_kudu.testtbl]
----- DISTRIBUTEDPLAN
-DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: true
|
00:SCAN KUDU [functional_kudu.testtbl]
====
delete from functional_kudu.testtbl where name = 'hallo'
---- PLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: name = 'hallo'
---- DISTRIBUTEDPLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: name = 'hallo'
@@ -40,7 +24,6 @@ delete a from functional_kudu.testtbl a, functional.alltypes b
where a.id = b.id and a.id in (select id from functional.alltypes)
---- PLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
04:HASH JOIN [RIGHT SEMI JOIN]
| hash predicates: id = a.id
@@ -61,7 +44,6 @@ DELETE FROM KUDU [functional_kudu.testtbl]
runtime filters: RF000 -> id
---- DISTRIBUTEDPLAN
DELETE FROM KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
04:HASH JOIN [RIGHT SEMI JOIN, PARTITIONED]
| hash predicates: id = a.id
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/testdata/workloads/functional-planner/queries/PlannerTest/kudu-update.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/kudu-update.test b/testdata/workloads/functional-planner/queries/PlannerTest/kudu-update.test
index a26ec40..4681b91 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/kudu-update.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/kudu-update.test
@@ -1,13 +1,11 @@
update functional_kudu.testtbl set name = 'peter' where zip > 94549
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: zip > 94549
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: zip > 94549
@@ -16,13 +14,11 @@ UPDATE KUDU [functional_kudu.testtbl]
update functional_kudu.testtbl set name = 'peter' where zip > 94549 and id = 5
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: id = 5, zip > 94549
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: id = 5, zip > 94549
@@ -31,13 +27,11 @@ UPDATE KUDU [functional_kudu.testtbl]
update functional_kudu.testtbl set zip = 94546 where zip > 94549
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: zip > 94549
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:SCAN KUDU [functional_kudu.testtbl]
kudu predicates: zip > 94549
@@ -48,7 +42,6 @@ from functional_kudu.testtbl a join functional.testtbl b on a.id = b.id
where a.id = 10
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [INNER JOIN]
| hash predicates: a.id = b.id
@@ -61,7 +54,6 @@ UPDATE KUDU [functional_kudu.testtbl]
kudu predicates: a.id = 10
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [INNER JOIN, BROADCAST]
| hash predicates: a.id = b.id
@@ -80,7 +72,6 @@ set a.name = 'values'
from functional_kudu.testtbl a join (values(1 as ids, 2, 3) ) b on a.id = b.ids
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [INNER JOIN]
| hash predicates: ids = a.id
@@ -91,7 +82,6 @@ UPDATE KUDU [functional_kudu.testtbl]
constant-operands=1
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [INNER JOIN, BROADCAST]
| hash predicates: ids = a.id
@@ -109,7 +99,6 @@ from functional_kudu.testtbl a
where a.zip in (select zip from functional.testtbl limit 10)
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [LEFT SEMI JOIN]
| hash predicates: a.zip = zip
@@ -121,7 +110,6 @@ UPDATE KUDU [functional_kudu.testtbl]
00:SCAN KUDU [functional_kudu.testtbl a]
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
02:HASH JOIN [LEFT SEMI JOIN, BROADCAST]
| hash predicates: a.zip = zip
@@ -140,12 +128,10 @@ UPDATE KUDU [functional_kudu.testtbl]
update functional_kudu.testtbl set zip = 94546 where false
---- PLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:EMPTYSET
---- DISTRIBUTEDPLAN
UPDATE KUDU [functional_kudu.testtbl]
-| check keys exist: false
|
00:EMPTYSET
====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test b/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
index a656341..fbb7f7f 100644
--- a/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
+++ b/testdata/workloads/functional-planner/queries/PlannerTest/kudu.test
@@ -44,13 +44,11 @@ PLAN-ROOT SINK
insert into functional_kudu.testtbl(id) values (10)
---- PLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
00:UNION
constant-operands=1
---- DISTRIBUTEDPLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
00:UNION
constant-operands=1
@@ -58,12 +56,10 @@ INSERT INTO KUDU [functional_kudu.testtbl]
insert into functional_kudu.testtbl(id) select int_col from functional_kudu.tinyinttable
---- PLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
00:SCAN KUDU [functional_kudu.tinyinttable]
---- DISTRIBUTEDPLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
00:SCAN KUDU [functional_kudu.tinyinttable]
====
@@ -72,7 +68,6 @@ select count(distinct id), name from functional_kudu.dimtbl
group by name
---- PLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
02:AGGREGATE [FINALIZE]
| output: count(id)
@@ -84,7 +79,6 @@ INSERT INTO KUDU [functional_kudu.testtbl]
00:SCAN KUDU [functional_kudu.dimtbl]
---- DISTRIBUTEDPLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
02:AGGREGATE [FINALIZE]
| output: count(id)
@@ -229,7 +223,6 @@ insert into table functional_kudu.alltypes /*+ clustered */
select * from functional_kudu.alltypes
---- PLAN
INSERT INTO KUDU [functional_kudu.alltypes]
-| check unique keys: false
|
01:SORT
| order by: id DESC NULLS LAST
@@ -237,7 +230,6 @@ INSERT INTO KUDU [functional_kudu.alltypes]
00:SCAN KUDU [functional_kudu.alltypes]
---- DISTRIBUTEDPLAN
INSERT INTO KUDU [functional_kudu.alltypes]
-| check unique keys: false
|
01:SORT
| order by: id DESC NULLS LAST
@@ -253,7 +245,6 @@ from functional_kudu.testtbl group by id, name
) as sub;
---- PLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
02:SORT
| order by: id DESC NULLS LAST
@@ -265,7 +256,6 @@ INSERT INTO KUDU [functional_kudu.testtbl]
00:SCAN KUDU [functional_kudu.testtbl]
---- DISTRIBUTEDPLAN
INSERT INTO KUDU [functional_kudu.testtbl]
-| check unique keys: false
|
04:SORT
| order by: id DESC NULLS LAST
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/08d89a5c/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test b/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
index 949a25c..761db13 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
@@ -213,13 +213,7 @@ row_regex: .*NumModifiedRows: 1.*
====
---- QUERY
insert into tdata values
-(666, "The Devil", cast(1.2 as float), 43, cast('z' as string), true)
----- CATCH
-Kudu error(s) reported, first error: Already present
-====
----- QUERY
-insert ignore into tdata values
-(666, "The Devil", cast(1.2 as float), 43, cast('z' as string), true)
+(666, "The Devil", cast(1.2 as float), 43, cast('z' as VARCHAR(20)), true)
---- RESULTS
: 0
---- RUNTIME_PROFILE
@@ -234,28 +228,14 @@ row_regex: .*NumModifiedRows: 7.*
====
---- QUERY
-- Does not exercise any error path in the sink because updating the same record multiple
--- times is valid. Makes sure IGNORE works.
-update ignore a set a.name='Satan' from tdata a, tdata b where a.id = 666
+-- times is valid.
+update a set a.name='Satan' from tdata a, tdata b where a.id = 666
---- RESULTS
---- RUNTIME_PROFILE
row_regex: .*NumModifiedRows: 7.*
====
---- QUERY
--- Using a cross join to generate the same delete twice. After the first delete succeeded,
--- trying to execute the second delete will fail because the record does not exist.
delete a from tdata a, tdata b where a.id = 666
----- CATCH
-Kudu error(s) reported, first error: Not found: key not found
-====
----- QUERY
--- Re-insert the data
-insert into tdata values
-(666, "The Devil", cast(1.2 as float), 43, cast('z' as string), true)
----- RESULTS
-: 1
-====
----- QUERY
-delete ignore a from tdata a, tdata b where a.id = 666
---- RESULTS
---- RUNTIME_PROFILE
row_regex: .*NumModifiedRows: 1.*
@@ -368,7 +348,7 @@ SELECT * FROM functional_kudu.alltypes WHERE id < 100;
row_regex: .*NumModifiedRows: 100.*
====
---- QUERY
-INSERT IGNORE INTO kudu_test_tbl
+INSERT INTO kudu_test_tbl
SELECT * FROM functional_kudu.alltypes WHERE id < 100;
---- RESULTS
: 0
@@ -377,12 +357,6 @@ row_regex: .*NumModifiedRows: 0.*
====
---- QUERY
INSERT INTO kudu_test_tbl
-SELECT * FROM functional_kudu.alltypes WHERE id < 100;
----- CATCH
-Kudu error(s) reported, first error: Already present: key already present
-====
----- QUERY
-INSERT IGNORE INTO kudu_test_tbl
SELECT * FROM functional_kudu.alltypes;
---- RESULTS
: 7200
@@ -413,15 +387,6 @@ FROM functional_kudu.alltypes
Kudu error(s) reported, first error: Not found: No tablet covering the requested range partition: NonCoveredRange { lower_bound: (int32 id=10001), upper_bound: (<end>)
====
---- QUERY
-# Insert rows that are not covered by any of the existing range partitions
-INSERT IGNORE INTO kudu_test_tbl SELECT cast(id + 10000 as int), bool_col, tinyint_col,
- smallint_col, int_col, bigint_col, float_col, double_col, date_string_col, string_col,
- timestamp_col,year, month
-FROM functional_kudu.alltypes
----- CATCH
-Kudu error(s) reported, first error: Not found: No tablet covering the requested range partition: NonCoveredRange { lower_bound: (int32 id=10001), upper_bound: (<end>)
-====
----- QUERY
# Try to delete a row with a primary key value that is not covered by the existing range
# partitions
DELETE FROM kudu_test_tbl WHERE id = 10001
[38/50] [abbrv] incubator-impala git commit: IMPALA-1654: General
partition exprs in DDL operations.
Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java b/fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java
index 8dab33a..077c4cb 100644
--- a/fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java
+++ b/fe/src/main/java/org/apache/impala/analysis/TupleDescriptor.java
@@ -345,4 +345,18 @@ public class TupleDescriptor {
}
return true;
}
+
+ /**
+ * Returns a list of slot ids that correspond to partition columns.
+ */
+ public List<SlotId> getPartitionSlots() {
+ List<SlotId> partitionSlots = Lists.newArrayList();
+ for (SlotDescriptor slotDesc: getSlots()) {
+ if (slotDesc.getColumn() == null) continue;
+ if (slotDesc.getColumn().getPosition() < getTable().getNumClusteringCols()) {
+ partitionSlots.add(slotDesc.getId());
+ }
+ }
+ return partitionSlots;
+ }
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/catalog/CatalogServiceCatalog.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/CatalogServiceCatalog.java b/fe/src/main/java/org/apache/impala/catalog/CatalogServiceCatalog.java
index f56f502..203ef6d 100644
--- a/fe/src/main/java/org/apache/impala/catalog/CatalogServiceCatalog.java
+++ b/fe/src/main/java/org/apache/impala/catalog/CatalogServiceCatalog.java
@@ -932,6 +932,25 @@ public class CatalogServiceCatalog extends Catalog {
}
/**
+ * Drops the partitions specified in 'partitionSet' from 'tbl'. Throws a
+ * CatalogException if 'tbl' is not an HdfsTable. Returns the target table.
+ */
+ public Table dropPartitions(Table tbl, List<List<TPartitionKeyValue>> partitionSet)
+ throws CatalogException {
+ Preconditions.checkNotNull(tbl);
+ Preconditions.checkNotNull(partitionSet);
+ Preconditions.checkState(Thread.holdsLock(tbl));
+ if (!(tbl instanceof HdfsTable)) {
+ throw new CatalogException("Table " + tbl.getFullName() + " is not an Hdfs table");
+ }
+ HdfsTable hdfsTable = (HdfsTable) tbl;
+ List<HdfsPartition> partitions =
+ hdfsTable.getPartitionsFromPartitionSet(partitionSet);
+ hdfsTable.dropPartitions(partitions);
+ return hdfsTable;
+ }
+
+ /**
* Drops the partition specified in 'partitionSpec' from 'tbl'. Throws a
* CatalogException if 'tbl' is not an HdfsTable. If the partition having the given
* partition spec does not exist, null is returned. Otherwise, the modified table is
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
index 69b4b4e..21b5359 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
@@ -90,12 +90,42 @@ import org.apache.impala.util.MetaStoreUtil;
import org.apache.impala.util.TAccessLevelUtil;
import org.apache.impala.util.TResultRowBuilder;
import com.google.common.base.Preconditions;
-import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
-import com.google.common.collect.ImmutableSet;
-import com.google.common.collect.ImmutableMap;
+
+import org.apache.avro.Schema;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.BlockLocation;
+import org.apache.hadoop.fs.BlockStorageLocation;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.fs.VolumeId;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.DistributedFileSystem;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
+import org.apache.hadoop.hive.serde.serdeConstants;
+import org.apache.hadoop.util.StringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import java.io.IOException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
/**
* Internal representation of table-related metadata of a file-resident table on a
@@ -621,6 +651,20 @@ public class HdfsTable extends Table {
}
/**
+ * Gets hdfs partitions by the given partition set.
+ */
+ public List<HdfsPartition> getPartitionsFromPartitionSet(
+ List<List<TPartitionKeyValue>> partitionSet) {
+ List<HdfsPartition> partitions = Lists.newArrayList();
+ for (List<TPartitionKeyValue> kv : partitionSet) {
+ HdfsPartition partition =
+ getPartitionFromThriftPartitionSpec(kv);
+ if (partition != null) partitions.add(partition);
+ }
+ return partitions;
+ }
+
+ /**
* Create columns corresponding to fieldSchemas. Throws a TableLoadingException if the
* metadata is incompatible with what we support.
*/
@@ -961,6 +1005,20 @@ public class HdfsTable extends Table {
}
/**
+ * Drops the given partitions from this table. Cleans up its metadata from all the
+ * mappings used to speed up partition pruning/lookup. Also updates partitions column
+ * statistics. Returns the list of partitions that were dropped.
+ */
+ public List<HdfsPartition> dropPartitions(List<HdfsPartition> partitions) {
+ ArrayList<HdfsPartition> droppedPartitions = Lists.newArrayList();
+ for (HdfsPartition partition: partitions) {
+ HdfsPartition hdfsPartition = dropPartition(partition);
+ if (hdfsPartition != null) droppedPartitions.add(hdfsPartition);
+ }
+ return droppedPartitions;
+ }
+
+ /**
* Adds or replaces the default partition.
*/
public void addDefaultPartition(StorageDescriptor storageDescriptor)
@@ -1143,7 +1201,7 @@ public class HdfsTable extends Table {
partitionNames.add(partition.getPartitionName());
}
partitionsToRemove.addAll(dirtyPartitions);
- for (HdfsPartition partition: partitionsToRemove) dropPartition(partition);
+ dropPartitions(partitionsToRemove);
// Load dirty partitions from Hive Metastore
loadPartitionsFromMetastore(dirtyPartitions, client);
@@ -1889,7 +1947,7 @@ public class HdfsTable extends Table {
* Returns files info for all partitions, if partition spec is null, ordered
* by partition.
*/
- public TResultSet getFiles(List<TPartitionKeyValue> partitionSpec)
+ public TResultSet getFiles(List<List<TPartitionKeyValue>> partitionSet)
throws CatalogException {
TResultSet result = new TResultSet();
TResultSetMetadata resultSchema = new TResultSetMetadata();
@@ -1899,16 +1957,14 @@ public class HdfsTable extends Table {
resultSchema.addToColumns(new TColumn("Partition", Type.STRING.toThrift()));
result.setRows(Lists.<TResultRow>newArrayList());
- List<HdfsPartition> orderedPartitions = null;
- if (partitionSpec == null) {
+ List<HdfsPartition> orderedPartitions;
+ if (partitionSet == null) {
orderedPartitions = Lists.newArrayList(partitionMap_.values());
- Collections.sort(orderedPartitions);
} else {
- // Get the HdfsPartition object for the given partition spec.
- HdfsPartition partition = getPartitionFromThriftPartitionSpec(partitionSpec);
- Preconditions.checkState(partition != null);
- orderedPartitions = Lists.newArrayList(partition);
+ // Get a list of HdfsPartition objects for the given partition set.
+ orderedPartitions = getPartitionsFromPartitionSet(partitionSet);
}
+ Collections.sort(orderedPartitions);
for (HdfsPartition p: orderedPartitions) {
List<FileDescriptor> orderedFds = Lists.newArrayList(p.getFileDescriptors());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/catalog/Table.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/Table.java b/fe/src/main/java/org/apache/impala/catalog/Table.java
index bef381a..be9dc7b 100644
--- a/fe/src/main/java/org/apache/impala/catalog/Table.java
+++ b/fe/src/main/java/org/apache/impala/catalog/Table.java
@@ -245,6 +245,10 @@ public abstract class Table implements CatalogObject {
return newTable;
}
+ public boolean isClusteringColumn(Column c) {
+ return c.getPosition() < numClusteringCols_;
+ }
+
protected void loadFromThrift(TTable thriftTable) throws TableLoadingException {
List<TColumn> columns = new ArrayList<TColumn>();
columns.addAll(thriftTable.getClustering_columns());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 10b6539..f719d0c 100644
--- a/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
+++ b/fe/src/main/java/org/apache/impala/planner/HdfsPartitionPruner.java
@@ -74,8 +74,7 @@ public class HdfsPartitionPruner {
private final static int PARTITION_PRUNING_BATCH_SIZE = 1024;
private final HdfsTable tbl_;
-
- private final List<SlotId> partitionSlots_ = Lists.newArrayList();
+ private final List<SlotId> partitionSlots_;
// For converting BetweenPredicates to CompoundPredicates so they can be
// executed in the BE.
@@ -85,21 +84,17 @@ public class HdfsPartitionPruner {
public HdfsPartitionPruner(TupleDescriptor tupleDesc) {
Preconditions.checkState(tupleDesc.getTable() instanceof HdfsTable);
tbl_ = (HdfsTable)tupleDesc.getTable();
+ partitionSlots_ = tupleDesc.getPartitionSlots();
- // Collect all the partitioning columns from TupleDescriptor.
- for (SlotDescriptor slotDesc: tupleDesc.getSlots()) {
- if (slotDesc.getColumn() == null) continue;
- if (slotDesc.getColumn().getPosition() < tbl_.getNumClusteringCols()) {
- partitionSlots_.add(slotDesc.getId());
- }
- }
}
/**
* Return a list of partitions left after applying the conjuncts. Please note
- * that conjuncts used for filtering will be removed from the list 'conjuncts'.
+ * that conjunts used for filtering will be removed from the list 'conjuncts'.
+ * If 'allowEmpty' is False, empty partitions are not returned.
*/
- public List<HdfsPartition> prunePartitions(Analyzer analyzer, List<Expr> conjuncts)
+ public List<HdfsPartition> prunePartitions(
+ Analyzer analyzer, List<Expr> conjuncts, boolean allowEmpty)
throws InternalException, AnalysisException {
// Start with creating a collection of partition filters for the applicable conjuncts.
List<HdfsPartitionFilter> partitionFilters = Lists.newArrayList();
@@ -159,7 +154,7 @@ public class HdfsPartitionPruner {
for (Long id: matchingPartitionIds) {
HdfsPartition partition = partitionMap.get(id);
Preconditions.checkNotNull(partition);
- if (partition.hasFileDescriptors()) {
+ if (partition.hasFileDescriptors() || allowEmpty) {
results.add(partition);
analyzer.getDescTbl().addReferencedPartition(tbl_, partition.getId());
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 9b0e376..6219127 100644
--- a/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
+++ b/fe/src/main/java/org/apache/impala/planner/SingleNodePlanner.java
@@ -1196,7 +1196,7 @@ public class SingleNodePlanner {
// Do partition pruning before deciding which slots to materialize,
// We might end up removing some predicates.
HdfsPartitionPruner pruner = new HdfsPartitionPruner(tupleDesc);
- List<HdfsPartition> partitions = pruner.prunePartitions(analyzer, conjuncts);
+ List<HdfsPartition> partitions = pruner.prunePartitions(analyzer, conjuncts, false);
// Mark all slots referenced by the remaining conjuncts as materialized.
analyzer.materializeSlots(conjuncts);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
index 884c43a..1755934 100644
--- a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
+++ b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
@@ -49,6 +49,15 @@ import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.metastore.api.SerDeInfo;
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.metastore.api.StringColumnStatsData;
+import org.apache.impala.common.Reference;
+import org.apache.log4j.Logger;
+import org.apache.thrift.TException;
+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.apache.impala.analysis.FunctionName;
import org.apache.impala.analysis.TableName;
import org.apache.impala.authorization.User;
@@ -332,6 +341,11 @@ public class CatalogOpExecutor {
// When true, loads the table schema and the column stats from the Hive Metastore.
boolean reloadTableSchema = false;
+ // When true, sets the result to be reported to the client.
+ boolean setResultSet = false;
+ TColumnValue resultColVal = new TColumnValue();
+ Reference<Long> numUpdatedPartitions = new Reference<>(0L);
+
TableName tableName = TableName.fromThrift(params.getTable_name());
Table tbl = getExistingTable(tableName.getDb(), tableName.getTbl());
catalog_.getLock().writeLock().lock();
@@ -351,6 +365,7 @@ public class CatalogOpExecutor {
}
// Get a new catalog version to assign to the table being altered.
long newCatalogVersion = catalog_.incrementAndGetCatalogVersion();
+ boolean reloadMetadata = true;
catalog_.getLock().writeLock().unlock();
switch (params.getAlter_type()) {
case ADD_REPLACE_COLUMNS:
@@ -373,7 +388,8 @@ public class CatalogOpExecutor {
refreshedTable.setCatalogVersion(newCatalogVersion);
addTableToCatalogUpdate(refreshedTable, response.result);
}
- return;
+ reloadMetadata = false;
+ break;
case DROP_COLUMN:
TAlterTableDropColParams dropColParams = params.getDrop_col_params();
alterTableDropCol(tbl, dropColParams.getCol_name());
@@ -390,57 +406,82 @@ public class CatalogOpExecutor {
params.getDrop_partition_params();
// Drop the partition from the corresponding table. Get the table object
// with an updated catalog version. If the partition does not exist and
- // "IfExists" is true, then return without populating the response object.
- // If "purge" option is specified partition data is purged by skipping
- // Trash, if configured.
- refreshedTable = alterTableDropPartition(tbl,
- dropPartParams.getPartition_spec(),
- dropPartParams.isIf_exists(), dropPartParams.isPurge());
+ // "IfExists" is true, null is returned. If "purge" option is specified
+ // partition data is purged by skipping Trash, if configured.
+ refreshedTable = alterTableDropPartition(
+ tbl, dropPartParams.getPartition_set(),
+ dropPartParams.isIf_exists(),
+ dropPartParams.isPurge(), numUpdatedPartitions);
if (refreshedTable != null) {
refreshedTable.setCatalogVersion(newCatalogVersion);
addTableToCatalogUpdate(refreshedTable, response.result);
}
- return;
+ resultColVal.setString_val(
+ "Dropped " + numUpdatedPartitions.getRef() + " partition(s).");
+ setResultSet = true;
+ reloadMetadata = false;
+ break;
case RENAME_TABLE:
case RENAME_VIEW:
Preconditions.checkState(false,
"RENAME TABLE/VIEW operation has been processed");
- return;
+ break;
case SET_FILE_FORMAT:
TAlterTableSetFileFormatParams fileFormatParams =
params.getSet_file_format_params();
- List<TPartitionKeyValue> fileFormatPartitionSpec = null;
- if (fileFormatParams.isSetPartition_spec()) {
- fileFormatPartitionSpec = fileFormatParams.getPartition_spec();
+ reloadFileMetadata = alterTableSetFileFormat(
+ tbl, fileFormatParams.getPartition_set(), fileFormatParams.getFile_format(),
+ numUpdatedPartitions);
+
+ if (fileFormatParams.isSetPartition_set()) {
+ resultColVal.setString_val(
+ "Updated " + numUpdatedPartitions.getRef() + " partition(s).");
+ } else {
+ resultColVal.setString_val("Updated table.");
}
- reloadFileMetadata = alterTableSetFileFormat(tbl, fileFormatPartitionSpec,
- fileFormatParams.getFile_format());
+ setResultSet = true;
break;
case SET_LOCATION:
TAlterTableSetLocationParams setLocationParams =
params.getSet_location_params();
- List<TPartitionKeyValue> partitionSpec = null;
- if (setLocationParams.isSetPartition_spec()) {
- partitionSpec = setLocationParams.getPartition_spec();
- }
- reloadFileMetadata = alterTableSetLocation(tbl, partitionSpec,
- setLocationParams.getLocation());
+ reloadFileMetadata = alterTableSetLocation(tbl,
+ setLocationParams.getPartition_spec(), setLocationParams.getLocation());
break;
case SET_TBL_PROPERTIES:
- alterTableSetTblProperties(tbl, params.getSet_tbl_properties_params());
+ alterTableSetTblProperties(tbl, params.getSet_tbl_properties_params(),
+ numUpdatedPartitions);
+ if (params.getSet_tbl_properties_params().isSetPartition_set()) {
+ resultColVal.setString_val(
+ "Updated " + numUpdatedPartitions.getRef() + " partition(s).");
+ } else {
+ resultColVal.setString_val("Updated table.");
+ }
+ setResultSet = true;
break;
case UPDATE_STATS:
Preconditions.checkState(params.isSetUpdate_stats_params());
- alterTableUpdateStats(tbl, params.getUpdate_stats_params(), response);
+ Reference<Long> numUpdatedColumns = new Reference<>(0L);
+ alterTableUpdateStats(tbl, params.getUpdate_stats_params(), response,
+ numUpdatedPartitions, numUpdatedColumns);
reloadTableSchema = true;
+ resultColVal.setString_val("Updated " + numUpdatedPartitions.getRef() +
+ " partition(s) and " + numUpdatedColumns.getRef() + " column(s).");
+ setResultSet = true;
break;
case SET_CACHED:
Preconditions.checkState(params.isSetSet_cached_params());
- if (params.getSet_cached_params().getPartition_spec() == null) {
+ String op = params.getSet_cached_params().getCache_op().isSet_cached() ?
+ "Cached " : "Uncached ";
+ if (params.getSet_cached_params().getPartition_set() == null) {
reloadFileMetadata = alterTableSetCached(tbl, params.getSet_cached_params());
+ resultColVal.setString_val(op + "table.");
} else {
- alterPartitionSetCached(tbl, params.getSet_cached_params());
+ alterPartitionSetCached(tbl, params.getSet_cached_params(),
+ numUpdatedPartitions);
+ resultColVal.setString_val(
+ op + numUpdatedPartitions.getRef() + " partition(s).");
}
+ setResultSet = true;
break;
case RECOVER_PARTITIONS:
alterTableRecoverPartitions(tbl);
@@ -450,9 +491,21 @@ public class CatalogOpExecutor {
"Unknown ALTER TABLE operation type: " + params.getAlter_type());
}
- loadTableMetadata(tbl, newCatalogVersion, reloadFileMetadata, reloadTableSchema,
- null);
- addTableToCatalogUpdate(tbl, response.result);
+ if (reloadMetadata) {
+ loadTableMetadata(tbl, newCatalogVersion, reloadFileMetadata, reloadTableSchema,
+ null);
+ addTableToCatalogUpdate(tbl, response.result);
+ }
+
+ if (setResultSet) {
+ TResultSet resultSet = new TResultSet();
+ resultSet.setSchema(new TResultSetMetadata(Lists.newArrayList(
+ new TColumn("summary", Type.STRING.toThrift()))));
+ TResultRow resultRow = new TResultRow();
+ resultRow.setColVals(Lists.newArrayList(resultColVal));
+ resultSet.setRows(Lists.newArrayList(resultRow));
+ response.setResult_set(resultSet);
+ }
} // end of synchronized block
}
@@ -550,7 +603,8 @@ public class CatalogOpExecutor {
* in batches of size 'MAX_PARTITION_UPDATES_PER_RPC'.
*/
private void alterTableUpdateStats(Table table, TAlterTableUpdateStatsParams params,
- TDdlExecResponse resp) throws ImpalaException {
+ TDdlExecResponse resp, Reference<Long> numUpdatedPartitions,
+ Reference<Long> numUpdatedColumns) throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(table));
if (params.isSetTable_stats()) {
// Updating table and column stats via COMPUTE STATS.
@@ -578,9 +632,9 @@ public class CatalogOpExecutor {
}
}
- int numTargetedPartitions = 0;
- int numUpdatedColumns = 0;
- try (MetaStoreClient msClient = catalog_.getMetaStoreClient()) {
+ long numTargetedPartitions = 0L;
+ long numTargetedColumns = 0L;
+ try(MetaStoreClient msClient = catalog_.getMetaStoreClient()) {
// Update the table and partition row counts based on the query results.
List<HdfsPartition> modifiedParts = Lists.newArrayList();
if (params.isSetTable_stats()) {
@@ -592,12 +646,12 @@ public class CatalogOpExecutor {
if (params.isSetColumn_stats()) {
// Create Hive column stats from the query results.
colStats = createHiveColStats(params.getColumn_stats(), table);
- numUpdatedColumns = colStats.getStatsObjSize();
+ numTargetedColumns = colStats.getStatsObjSize();
}
// Update all partitions.
bulkAlterPartitions(table.getDb().getName(), table.getName(), modifiedParts);
- if (numUpdatedColumns > 0) {
+ if (numTargetedColumns > 0) {
Preconditions.checkNotNull(colStats);
// Update column stats.
try {
@@ -611,18 +665,8 @@ public class CatalogOpExecutor {
// lastDdlTime is as accurate as possible.
applyAlterTable(msTbl);
}
-
- // Set the results to be reported to the client.
- TResultSet resultSet = new TResultSet();
- resultSet.setSchema(new TResultSetMetadata(Lists.newArrayList(
- new TColumn("summary", Type.STRING.toThrift()))));
- TColumnValue resultColVal = new TColumnValue();
- resultColVal.setString_val("Updated " + numTargetedPartitions + " partition(s) and " +
- numUpdatedColumns + " column(s).");
- TResultRow resultRow = new TResultRow();
- resultRow.setColVals(Lists.newArrayList(resultColVal));
- resultSet.setRows(Lists.newArrayList(resultRow));
- resp.setResult_set(resultSet);
+ numUpdatedPartitions.setRef(numTargetedPartitions);
+ numUpdatedColumns.setRef(numTargetedColumns);
}
/**
@@ -983,33 +1027,27 @@ public class CatalogOpExecutor {
synchronized(table) {
long newCatalogVersion = catalog_.incrementAndGetCatalogVersion();
catalog_.getLock().writeLock().unlock();
- if (params.getPartition_spec() == null) {
+ if (params.getPartition_set() == null) {
// TODO: Report the number of updated partitions/columns to the user?
+ // TODO: bulk alter the partitions.
dropColumnStats(table);
dropTableStats(table);
} else {
- HdfsPartition partition =
- ((HdfsTable)table).getPartitionFromThriftPartitionSpec(
- params.getPartition_spec());
- if (partition == null) {
- List<String> partitionDescription = Lists.newArrayList();
- for (TPartitionKeyValue v: params.getPartition_spec()) {
- partitionDescription.add(v.name + " = " + v.value);
- }
- throw new ImpalaRuntimeException("Could not find partition: " +
- Joiner.on("/").join(partitionDescription));
- }
+ List<HdfsPartition> partitions =
+ ((HdfsTable)table).getPartitionsFromPartitionSet(params.getPartition_set());
+ if (partitions.isEmpty()) return;
- if (partition.getPartitionStats() != null) {
- PartitionStatsUtil.deletePartStats(partition);
- try {
- applyAlterPartition(table, partition);
- } finally {
- partition.markDirty();
+ for(HdfsPartition partition : partitions) {
+ if (partition.getPartitionStats() != null) {
+ PartitionStatsUtil.deletePartStats(partition);
+ try {
+ applyAlterPartition(table, partition);
+ } finally {
+ partition.markDirty();
+ }
}
}
}
-
loadTableMetadata(table, newCatalogVersion, false, true, null);
addTableToCatalogUpdate(table, resp.result);
} // end of synchronization
@@ -1825,59 +1863,73 @@ public class CatalogOpExecutor {
}
/**
- * Drops an existing partition from the given table in Hive. If the partition is cached,
+ * Drops existing partitions from the given table in Hive. If a partition is cached,
* the associated cache directive will also be removed.
- * Also drops the partition from its Hdfs table.
- * Returns the table object with an updated catalog version. If the partition does not
- * exist and "IfExists" is true, null is returned. If purge is true, partition data is
- * permanently deleted.
+ * Also drops the corresponding partitions from its Hdfs table.
+ * Returns the table object with an updated catalog version. If none of the partitions
+ * exists and "IfExists" is true, null is returned. If purge is true, partition data is
+ * permanently deleted. numUpdatedPartitions is used to inform the client how many
+ * partitions being dropped in this operation.
*/
private Table alterTableDropPartition(Table tbl,
- List<TPartitionKeyValue> partitionSpec, boolean ifExists, boolean purge)
+ List<List<TPartitionKeyValue>> partitionSet,
+ boolean ifExists, boolean purge, Reference<Long> numUpdatedPartitions)
throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(tbl));
+ Preconditions.checkNotNull(partitionSet);
+
TableName tableName = tbl.getTableName();
- if (ifExists && !catalog_.containsHdfsPartition(tableName.getDb(), tableName.getTbl(),
- partitionSpec)) {
- LOG.debug(String.format("Skipping partition drop because (%s) does not exist " +
- "and ifExists is true.", Joiner.on(", ").join(partitionSpec)));
- return null;
+ if (!ifExists) {
+ Preconditions.checkState(!partitionSet.isEmpty());
+ } else {
+ if (partitionSet.isEmpty()) {
+ LOG.debug(String.format("Ignoring empty partition list when dropping " +
+ "partitions from %s because ifExists is true.", tableName));
+ return tbl;
+ }
+ }
+
+ Preconditions.checkArgument(tbl instanceof HdfsTable);
+ List<HdfsPartition> parts =
+ ((HdfsTable) tbl).getPartitionsFromPartitionSet(partitionSet);
+
+ if (!ifExists && parts.isEmpty()) {
+ throw new PartitionNotFoundException(
+ "The partitions being dropped don't exist any more");
}
- HdfsPartition part = catalog_.getHdfsPartition(tableName.getDb(),
- tableName.getTbl(), partitionSpec);
org.apache.hadoop.hive.metastore.api.Table msTbl =
tbl.getMetaStoreTable().deepCopy();
- List<String> values = Lists.newArrayList();
- // Need to add in the values in the same order they are defined in the table.
- for (FieldSchema fs: msTbl.getPartitionKeys()) {
- for (TPartitionKeyValue kv: partitionSpec) {
- if (fs.getName().toLowerCase().equals(kv.getName().toLowerCase())) {
- values.add(kv.getValue());
- }
- }
- }
+
PartitionDropOptions dropOptions = PartitionDropOptions.instance();
dropOptions.purgeData(purge);
+ long numTargetedPartitions = 0L;
try (MetaStoreClient msClient = catalog_.getMetaStoreClient()) {
- msClient.getHiveClient().dropPartition(tableName.getDb(),
- tableName.getTbl(), values, dropOptions);
- updateLastDdlTime(msTbl, msClient);
- if (part.isMarkedCached()) {
- HdfsCachingUtil.uncachePartition(part);
- }
- } catch (NoSuchObjectException e) {
- if (!ifExists) {
- throw new ImpalaRuntimeException(
- String.format(HMS_RPC_ERROR_FORMAT_STR, "dropPartition"), e);
+ for (HdfsPartition part : parts) {
+ try {
+ msClient.getHiveClient().dropPartition(tableName.getDb(), tableName.getTbl(),
+ part.getPartitionValuesAsStrings(true), dropOptions);
+ ++numTargetedPartitions;
+ if (part.isMarkedCached()) {
+ HdfsCachingUtil.uncachePartition(part);
+ }
+ } catch (NoSuchObjectException e) {
+ if (!ifExists) {
+ throw new ImpalaRuntimeException(
+ String.format(HMS_RPC_ERROR_FORMAT_STR, "dropPartition"), e);
+ }
+ LOG.debug(
+ String.format("Ignoring '%s' when dropping partitions from %s because" +
+ " ifExists is true.", e, tableName));
+ }
}
- LOG.debug(String.format("Ignoring '%s' when dropping partition from %s because" +
- " ifExists is true.", e, tableName));
+ updateLastDdlTime(msTbl, msClient);
} catch (TException e) {
throw new ImpalaRuntimeException(
String.format(HMS_RPC_ERROR_FORMAT_STR, "dropPartition"), e);
}
- return catalog_.dropPartition(tbl, partitionSpec);
+ numUpdatedPartitions.setRef(numTargetedPartitions);
+ return catalog_.dropPartitions(tbl, partitionSet);
}
/**
@@ -1970,18 +2022,19 @@ public class CatalogOpExecutor {
}
/**
- * Changes the file format for the given table or partition. This is a metadata only
+ * Changes the file format for the given table or partitions. This is a metadata only
* operation, existing table data will not be converted to the new format. After
* changing the file format the table metadata is marked as invalid and will be
* reloaded on the next access.
*/
private boolean alterTableSetFileFormat(Table tbl,
- List<TPartitionKeyValue> partitionSpec, THdfsFileFormat fileFormat)
+ List<List<TPartitionKeyValue>> partitionSet, THdfsFileFormat fileFormat,
+ Reference<Long> numUpdatedPartitions)
throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(tbl));
- Preconditions.checkState(partitionSpec == null || !partitionSpec.isEmpty());
+ Preconditions.checkState(partitionSet == null || !partitionSet.isEmpty());
boolean reloadFileMetadata = false;
- if (partitionSpec == null) {
+ if (partitionSet == null) {
org.apache.hadoop.hive.metastore.api.Table msTbl =
tbl.getMetaStoreTable().deepCopy();
setStorageDescriptorFileFormat(msTbl.getSd(), fileFormat);
@@ -1991,16 +2044,17 @@ public class CatalogOpExecutor {
applyAlterTable(msTbl);
reloadFileMetadata = true;
} else {
- TableName tableName = tbl.getTableName();
- HdfsPartition partition = catalog_.getHdfsPartition(
- tableName.getDb(), tableName.getTbl(), partitionSpec);
- Preconditions.checkNotNull(partition);
- partition.setFileFormat(HdfsFileFormat.fromThrift(fileFormat));
- try {
- applyAlterPartition(tbl, partition);
- } finally {
- partition.markDirty();
+ Preconditions.checkArgument(tbl instanceof HdfsTable);
+ List<HdfsPartition> partitions =
+ ((HdfsTable) tbl).getPartitionsFromPartitionSet(partitionSet);
+ List<HdfsPartition> modifiedParts = Lists.newArrayList();
+ for(HdfsPartition partition: partitions) {
+ partition.setFileFormat(HdfsFileFormat.fromThrift(fileFormat));
+ modifiedParts.add(partition);
}
+ TableName tableName = tbl.getTableName();
+ bulkAlterPartitions(tableName.getDb(), tableName.getTbl(), modifiedParts);
+ numUpdatedPartitions.setRef((long) modifiedParts.size());
}
return reloadFileMetadata;
}
@@ -2024,7 +2078,6 @@ public class CatalogOpExecutor {
private boolean alterTableSetLocation(Table tbl,
List<TPartitionKeyValue> partitionSpec, String location) throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(tbl));
- Preconditions.checkState(partitionSpec == null || !partitionSpec.isEmpty());
boolean reloadFileMetadata = false;
if (partitionSpec == null) {
org.apache.hadoop.hive.metastore.api.Table msTbl =
@@ -2047,35 +2100,44 @@ public class CatalogOpExecutor {
}
/**
- * Appends to the table or partition property metadata for the given table, replacing
+ * Appends to the table or partitions property metadata for the given table, replacing
* the values of any keys that already exist.
*/
private void alterTableSetTblProperties(Table tbl,
- TAlterTableSetTblPropertiesParams params) throws ImpalaException {
+ TAlterTableSetTblPropertiesParams params, Reference<Long> numUpdatedPartitions)
+ throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(tbl));
Map<String, String> properties = params.getProperties();
Preconditions.checkNotNull(properties);
- if (params.isSetPartition_spec()) {
- TableName tableName = tbl.getTableName();
- // Alter partition params.
- HdfsPartition partition = catalog_.getHdfsPartition(
- tableName.getDb(), tableName.getTbl(), params.getPartition_spec());
- switch (params.getTarget()) {
- case TBL_PROPERTY:
- partition.getParameters().putAll(properties);
- break;
- case SERDE_PROPERTY:
- partition.getSerdeInfo().getParameters().putAll(properties);
- break;
- default:
- throw new UnsupportedOperationException(
- "Unknown target TTablePropertyType: " + params.getTarget());
+ if (params.isSetPartition_set()) {
+ Preconditions.checkArgument(tbl instanceof HdfsTable);
+ List<HdfsPartition> partitions =
+ ((HdfsTable) tbl).getPartitionsFromPartitionSet(params.getPartition_set());
+
+ List<HdfsPartition> modifiedParts = Lists.newArrayList();
+ for(HdfsPartition partition: partitions) {
+ switch (params.getTarget()) {
+ case TBL_PROPERTY:
+ partition.getParameters().putAll(properties);
+ break;
+ case SERDE_PROPERTY:
+ partition.getSerdeInfo().getParameters().putAll(properties);
+ break;
+ default:
+ throw new UnsupportedOperationException(
+ "Unknown target TTablePropertyType: " + params.getTarget());
+ }
+ modifiedParts.add(partition);
}
+ TableName tableName = tbl.getTableName();
try {
- applyAlterPartition(tbl, partition);
+ bulkAlterPartitions(tableName.getDb(), tableName.getTbl(), modifiedParts);
} finally {
- partition.markDirty();
+ for (HdfsPartition modifiedPart : modifiedParts) {
+ modifiedPart.markDirty();
+ }
}
+ numUpdatedPartitions.setRef((long) modifiedParts.size());
} else {
// Alter table params.
org.apache.hadoop.hive.metastore.api.Table msTbl =
@@ -2226,56 +2288,68 @@ public class CatalogOpExecutor {
}
/**
- * Caches or uncaches the HDFS location of the target partition and updates the
- * partition's metadata in Hive Metastore Store. If a partition is being cached, the
+ * Caches or uncaches the HDFS location of the target partitions and updates the
+ * partitions' metadata in Hive Metastore Store. If a partition is being cached, the
* partition properties will have the ID of the cache directive added. If the partition
* is being uncached, any outstanding cache directive will be dropped and the cache
* directive ID property key will be cleared.
*/
- private void alterPartitionSetCached(Table tbl, TAlterTableSetCachedParams params)
+ private void alterPartitionSetCached(Table tbl,
+ TAlterTableSetCachedParams params, Reference<Long> numUpdatedPartitions)
throws ImpalaException {
Preconditions.checkState(Thread.holdsLock(tbl));
THdfsCachingOp cacheOp = params.getCache_op();
Preconditions.checkNotNull(cacheOp);
- Preconditions.checkNotNull(params.getPartition_spec());
- // Alter partition params.
+ Preconditions.checkNotNull(params.getPartition_set());
TableName tableName = tbl.getTableName();
- HdfsPartition partition = catalog_.getHdfsPartition(
- tableName.getDb(), tableName.getTbl(), params.getPartition_spec());
+ Preconditions.checkArgument(tbl instanceof HdfsTable);
+ List<HdfsPartition> partitions =
+ ((HdfsTable) tbl).getPartitionsFromPartitionSet(params.getPartition_set());
+ List<HdfsPartition> modifiedParts = Lists.newArrayList();
if (cacheOp.isSet_cached()) {
- // The directive is null if the partition is not cached
- Long directiveId = HdfsCachingUtil.getCacheDirectiveId(
- partition.getParameters());
- short replication = HdfsCachingUtil.getReplicationOrDefault(cacheOp);
- List<Long> cacheDirs = Lists.newArrayList();
-
- if (directiveId == null) {
- cacheDirs.add(HdfsCachingUtil.submitCachePartitionDirective(partition,
- cacheOp.getCache_pool_name(), replication));
- } else {
- if (HdfsCachingUtil.isUpdateOp(cacheOp, partition.getParameters())) {
- HdfsCachingUtil.validateCachePool(cacheOp, directiveId, tableName, partition);
- cacheDirs.add(HdfsCachingUtil.modifyCacheDirective(directiveId, partition,
- cacheOp.getCache_pool_name(), replication));
+ for (HdfsPartition partition : partitions) {
+ // The directive is null if the partition is not cached
+ Long directiveId =
+ HdfsCachingUtil.getCacheDirectiveId(partition.getParameters());
+ short replication = HdfsCachingUtil.getReplicationOrDefault(cacheOp);
+ List<Long> cacheDirs = Lists.newArrayList();
+ if (directiveId == null) {
+ cacheDirs.add(HdfsCachingUtil.submitCachePartitionDirective(
+ partition, cacheOp.getCache_pool_name(), replication));
+ } else {
+ if (HdfsCachingUtil.isUpdateOp(cacheOp, partition.getParameters())) {
+ HdfsCachingUtil.validateCachePool(cacheOp, directiveId, tableName, partition);
+ cacheDirs.add(HdfsCachingUtil.modifyCacheDirective(
+ directiveId, partition, cacheOp.getCache_pool_name(),
+ replication));
+ }
}
- }
- // Once the cache directives are submitted, observe the status of the caching
- // until no more progress is made -- either fully cached or out of cache memory
- if (!cacheDirs.isEmpty()) {
- catalog_.watchCacheDirs(cacheDirs, tableName.toThrift());
+ // Once the cache directives are submitted, observe the status of the caching
+ // until no more progress is made -- either fully cached or out of cache memory
+ if (!cacheDirs.isEmpty()) {
+ catalog_.watchCacheDirs(cacheDirs, tableName.toThrift());
+ }
+ if (!partition.isMarkedCached()) {
+ modifiedParts.add(partition);
+ }
}
-
} else {
- // Partition is not cached, just return.
- if (!partition.isMarkedCached()) return;
- HdfsCachingUtil.uncachePartition(partition);
+ for (HdfsPartition partition : partitions) {
+ if (partition.isMarkedCached()) {
+ HdfsCachingUtil.uncachePartition(partition);
+ modifiedParts.add(partition);
+ }
+ }
}
try {
- applyAlterPartition(tbl, partition);
+ bulkAlterPartitions(tableName.getDb(), tableName.getTbl(), modifiedParts);
} finally {
- partition.markDirty();
+ for (HdfsPartition modifiedPart : modifiedParts) {
+ modifiedPart.markDirty();
+ }
}
+ numUpdatedPartitions.setRef((long) modifiedParts.size());
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/service/Frontend.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/Frontend.java b/fe/src/main/java/org/apache/impala/service/Frontend.java
index a974278..8657182 100644
--- a/fe/src/main/java/org/apache/impala/service/Frontend.java
+++ b/fe/src/main/java/org/apache/impala/service/Frontend.java
@@ -1203,7 +1203,7 @@ public class Frontend {
Table table = impaladCatalog_.getTable(request.getTable_name().getDb_name(),
request.getTable_name().getTable_name());
if (table instanceof HdfsTable) {
- return ((HdfsTable) table).getFiles(request.getPartition_spec());
+ return ((HdfsTable) table).getFiles(request.getPartition_set());
} else {
throw new InternalException("SHOW FILES only supports Hdfs table. " +
"Unsupported table class: " + table.getClass());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/test/java/org/apache/impala/analysis/AnalyzeDDLTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/AnalyzeDDLTest.java b/fe/src/test/java/org/apache/impala/analysis/AnalyzeDDLTest.java
index b005924..0a78dd5 100644
--- a/fe/src/test/java/org/apache/impala/analysis/AnalyzeDDLTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/AnalyzeDDLTest.java
@@ -77,21 +77,6 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalysisError("alter table functional_hbase.alltypesagg " + kw +
" partition (i=1)", "Table is not partitioned: functional_hbase.alltypesagg");
- // Duplicate partition key name
- AnalysisError("alter table functional.alltypes " + kw +
- " partition(year=2050, year=2051)", "Duplicate partition key name: year");
- // Not a partition column
- AnalysisError("alter table functional.alltypes " + kw +
- " partition(year=2050, int_col=1)",
- "Column 'int_col' is not a partition column in table: functional.alltypes");
-
- // NULL partition keys
- AnalyzesOk("alter table functional.alltypes " + kw +
- " partition(year=NULL, month=1)");
- AnalyzesOk("alter table functional.alltypes " + kw +
- " partition(year=NULL, month=NULL)");
- AnalyzesOk("alter table functional.alltypes " + kw +
- " partition(year=ascii(null), month=ascii(NULL))");
// Empty string partition keys
AnalyzesOk("alter table functional.insert_string_partitioned " + kw +
" partition(s2='')");
@@ -99,41 +84,13 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalyzesOk("alter table functional.alltypes " + kw +
" partition(year=-1, month=cast((10+5*4) as INT))");
- // Arbitrary exprs as partition key values. Non-constant exprs should fail.
- AnalysisError("alter table functional.alltypes " + kw +
- " partition(year=2050, month=int_col)",
- "Non-constant expressions are not supported as static partition-key values " +
- "in 'month=int_col'.");
- AnalysisError("alter table functional.alltypes " + kw +
- " partition(year=cast(int_col as int), month=12)",
- "Non-constant expressions are not supported as static partition-key values " +
- "in 'year=CAST(int_col AS INT)'.");
-
- // Not a valid column
- AnalysisError("alter table functional.alltypes " + kw +
- " partition(year=2050, blah=1)",
- "Partition column 'blah' not found in table: functional.alltypes");
-
- // Data types don't match
- AnalysisError(
- "alter table functional.insert_string_partitioned " + kw +
- " partition(s2=1234)",
- "Value of partition spec (column=s2) has incompatible type: 'SMALLINT'. " +
- "Expected type: 'STRING'.");
-
- // Loss of precision
- AnalysisError(
- "alter table functional.alltypes " + kw +
- " partition(year=100000000000, month=10)",
- "Partition key value may result in loss of precision.\nWould need to cast" +
- " '100000000000' to 'INT' for partition column: year");
-
-
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes " + kw +
- " partition (i=1)", "Database does not exist: db_does_not_exist");
+ " partition (i=1)", "Could not resolve table reference: " +
+ "'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist " + kw +
- " partition (i=1)", "Table does not exist: functional.table_does_not_exist");
+ " partition (i=1)", "Could not resolve table reference: " +
+ "'functional.table_does_not_exist'");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " + kw +
@@ -143,8 +100,60 @@ public class AnalyzeDDLTest extends FrontendTestBase {
" partition(year=2050, month=10)",
"ALTER TABLE not allowed on a table produced by a data source: " +
"functional.alltypes_datasource");
+
+ // NULL partition keys
+ AnalyzesOk("alter table functional.alltypes " + kw +
+ " partition(year=NULL, month=1)");
+ AnalyzesOk("alter table functional.alltypes " + kw +
+ " partition(year=NULL, month=NULL)");
+ AnalyzesOk("alter table functional.alltypes " + kw +
+ " partition(year=ascii(null), month=ascii(NULL))");
}
+ // Data types don't match
+ AnalysisError("alter table functional.insert_string_partitioned add" +
+ " partition(s2=1234)",
+ "Value of partition spec (column=s2) has incompatible type: " +
+ "'SMALLINT'. Expected type: 'STRING'.");
+ AnalysisError("alter table functional.insert_string_partitioned drop" +
+ " partition(s2=1234)",
+ "operands of type STRING and SMALLINT are not comparable: s2 = 1234");
+
+ // Loss of precision
+ AnalysisError(
+ "alter table functional.alltypes add " +
+ "partition(year=100000000000, month=10) ",
+ "Partition key value may result in loss of precision.\nWould need to cast " +
+ "'100000000000' to 'INT' for partition column: year");
+
+ // Duplicate partition key name
+ AnalysisError("alter table functional.alltypes add " +
+ "partition(year=2050, year=2051)", "Duplicate partition key name: year");
+
+ // Arbitrary exprs as partition key values. Non-constant exprs should fail.
+ AnalysisError("alter table functional.alltypes add " +
+ "partition(year=2050, month=int_col) ",
+ "Non-constant expressions are not supported as static partition-key " +
+ "values in 'month=int_col'.");
+ AnalysisError("alter table functional.alltypes add " +
+ "partition(year=cast(int_col as int), month=12) ",
+ "Non-constant expressions are not supported as static partition-key " +
+ "values in 'year=CAST(int_col AS INT)'.");
+
+ // Not a partition column
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=2050, int_col=1)",
+ "Partition exprs cannot contain non-partition column(s): int_col = 1.");
+
+ // Arbitrary exprs as partition key values. Non-partition columns should fail.
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=2050, month=int_col) ",
+ "Partition exprs cannot contain non-partition column(s): month = int_col.");
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=cast(int_col as int), month=12) ",
+ "Partition exprs cannot contain non-partition column(s): " +
+ "year = CAST(int_col AS INT).");
+
// IF NOT EXISTS properly checks for partition existence
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10)");
@@ -152,20 +161,63 @@ public class AnalyzeDDLTest extends FrontendTestBase {
"partition(year=2010, month=10)",
"Partition spec already exists: (year=2010, month=10).");
AnalyzesOk("alter table functional.alltypes add if not exists " +
- " partition(year=2010, month=10)");
+ "partition(year=2010, month=10)");
AnalyzesOk("alter table functional.alltypes add if not exists " +
- " partition(year=2010, month=10) location " +
+ "partition(year=2010, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
// IF EXISTS properly checks for partition existence
+ // with a fully specified partition.
AnalyzesOk("alter table functional.alltypes drop " +
"partition(year=2010, month=10)");
AnalysisError("alter table functional.alltypes drop " +
"partition(year=2050, month=10)",
- "Partition spec does not exist: (year=2050, month=10).");
+ "No matching partition(s) found.");
AnalyzesOk("alter table functional.alltypes drop if exists " +
"partition(year=2050, month=10)");
+ // NULL partition keys
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=NULL, month=1)",
+ "No matching partition(s) found.");
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=NULL, month is NULL)",
+ "No matching partition(s) found.");
+
+ // Drop partition using predicates
+ // IF EXISTS is added here
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(year<2011, month!=10)");
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(1=1, month=10)",
+ "Invalid partition expr 1 = 1. " +
+ "A partition spec may not contain constant predicates.");
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(year>1050, month=10)");
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(year>1050 and month=10)");
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(month=10)");
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(month+2000=year)");
+ AnalyzesOk("alter table functional.alltypes drop " +
+ "partition(year>9050, month=10)");
+ AnalyzesOk("alter table functional.alltypes drop if exists " +
+ "partition(year>9050, month=10)");
+
+ // Not a valid column
+ AnalysisError("alter table functional.alltypes add " +
+ "partition(year=2050, blah=1)",
+ "Partition column 'blah' not found in table: functional.alltypes");
+ AnalysisError("alter table functional.alltypes drop " +
+ "partition(year=2050, blah=1)",
+ "Could not resolve column/field reference: 'blah'");
+
+ // Not a partition column
+ AnalysisError("alter table functional.alltypes add " +
+ "partition(year=2050, int_col=1) ",
+ "Column 'int_col' is not a partition column in table: functional.alltypes");
+
// Caching ops
AnalyzesOk("alter table functional.alltypes add " +
"partition(year=2050, month=10) cached in 'testPool'");
@@ -185,25 +237,25 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Valid URIs.
AnalyzesOk("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location " +
+ "partition(year=2050, month=10) location " +
"'/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location " +
+ "partition(year=2050, month=10) location " +
"'hdfs://localhost:20500/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location " +
+ "partition(year=2050, month=10) location " +
"'s3n://bucket/test-warehouse/alltypes/year=2010/month=10'");
AnalyzesOk("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location " +
+ "partition(year=2050, month=10) location " +
"'file:///test-warehouse/alltypes/year=2010/month=10'");
// Invalid URIs.
AnalysisError("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location " +
+ "partition(year=2050, month=10) location " +
"'foofs://bar/test-warehouse/alltypes/year=2010/month=10'",
"No FileSystem for scheme: foofs");
AnalysisError("alter table functional.alltypes add " +
- " partition(year=2050, month=10) location ' '",
+ "partition(year=2050, month=10) location ' '",
"URI path cannot be empty.");
}
@@ -242,14 +294,19 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes add columns (i int)",
- "Database does not exist: db_does_not_exist");
+ "Could not resolve table reference: 'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist add columns (i int)",
- "Table does not exist: functional.table_does_not_exist");
+ "Could not resolve table reference: 'functional.table_does_not_exist'");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"add columns (c1 string comment 'hi')",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot ALTER TABLE a nested collection.
+ AnalysisError("alter table allcomplextypes.int_array_col " +
+ "add columns (c1 string comment 'hi')",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"add columns (c1 string comment 'hi')",
@@ -278,13 +335,17 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes drop column col1",
- "Database does not exist: db_does_not_exist");
+ "Could not resolve table reference: 'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist drop column col1",
- "Table does not exist: functional.table_does_not_exist");
+ "Could not resolve table reference: 'functional.table_does_not_exist'");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view drop column int_col",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot ALTER TABLE a nested collection.
+ AnalysisError("alter table allcomplextypes.int_array_col drop column int_col",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource drop column int_col",
"ALTER TABLE not allowed on a table produced by a data source: " +
@@ -324,14 +385,19 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes change c1 c2 int",
- "Database does not exist: db_does_not_exist");
+ "Could not resolve table reference: 'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist change c1 c2 double",
- "Table does not exist: functional.table_does_not_exist");
+ "Could not resolve table reference: 'functional.table_does_not_exist'");
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view " +
"change column int_col int_col2 int",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot ALTER TABLE a nested collection.
+ AnalysisError("alter table allcomplextypes.int_array_col " +
+ "change column int_col int_col2 int",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource " +
"change column int_col int_col2 int",
@@ -353,14 +419,20 @@ public class AnalyzeDDLTest extends FrontendTestBase {
"set location '/a/b'");
AnalyzesOk("alter table functional.alltypes PARTITION (month=11, year=2010) " +
"set fileformat parquetfile");
+ AnalyzesOk("alter table functional.alltypes PARTITION (month<=11, year=2010) " +
+ "set fileformat parquetfile");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition1') set fileformat parquet");
AnalyzesOk("alter table functional.stringpartitionkey PARTITION " +
"(string_col='PaRtiTion1') set location '/a/b/c'");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set tblproperties('a'='1')");
+ AnalyzesOk("alter table functional.alltypes PARTITION (year<=2010, month=11) " +
+ "set tblproperties('a'='1')");
AnalyzesOk("alter table functional.alltypes PARTITION (year=2010, month=11) " +
"set serdeproperties ('a'='2')");
+ AnalyzesOk("alter table functional.alltypes PARTITION (year<=2010, month=11) " +
+ "set serdeproperties ('a'='2')");
{
// Check that long_properties fail at the analysis layer
@@ -422,33 +494,33 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalyzesOk("alter table functional.alltypes PARTITION " +
"(year=cast(100*20+10 as INT), month=cast(2+9 as INT)) " +
"set location '/a/b'");
- // Arbitrary exprs as partition key values. Non-constant exprs should fail.
- AnalysisError("alter table functional.alltypes PARTITION " +
- "(Year=2050, month=int_col) set fileformat sequencefile",
- "Non-constant expressions are not supported as static partition-key " +
- "values in 'month=int_col'.");
+
+ // Arbitrary exprs as partition key values. One-partition-column-bound exprs are ok.
+ AnalyzesOk("alter table functional.alltypes PARTITION " +
+ "(Year*2=Year+2010, month=11) set fileformat sequencefile");
+
+ // Arbitrary exprs as partition key values. Non-partition-column exprs.
AnalysisError("alter table functional.alltypes PARTITION " +
- "(Year=2050, month=int_col) set location '/a/b'",
- "Non-constant expressions are not supported as static partition-key " +
- "values in 'month=int_col'.");
+ "(int_col=3) set fileformat sequencefile",
+ "Partition exprs cannot contain non-partition column(s): int_col = 3.");
+
+ // Partition expr matches more than one partition in set location statement.
+ AnalysisError("alter table functional.alltypes PARTITION (year!=20) " +
+ "set location '/a/b'",
+ "Partition expr in set location statements can only match " +
+ "one partition. Too many matched partitions year=2009/month=1," +
+ "year=2009/month=2,year=2009/month=3");
// Partition spec does not exist
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set location '/a/b'",
- "Partition spec does not exist: (year=2014, month=11)");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.alltypes PARTITION (year=2014, month=11) " +
"set tblproperties('a'='1')",
- "Partition spec does not exist: (year=2014, month=11)");
- AnalysisError("alter table functional.alltypes PARTITION (year=2010) " +
- "set tblproperties('a'='1')",
- "Items in partition spec must exactly match the partition columns " +
- "in the table definition: functional.alltypes (1 vs 2)");
- AnalysisError("alter table functional.alltypes PARTITION (year=2010, year=2010) " +
- "set location '/a/b'",
- "Duplicate partition key name: year");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.alltypes PARTITION (month=11, year=2014) " +
"set fileformat sequencefile",
- "Partition spec does not exist: (month=11, year=2014)");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.alltypesnopart PARTITION (month=1) " +
"set fileformat sequencefile",
"Table is not partitioned: functional.alltypesnopart");
@@ -457,34 +529,32 @@ public class AnalyzeDDLTest extends FrontendTestBase {
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set location '/a/b'",
- "Partition spec does not exist: (string_col='partition2')");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.stringpartitionkey PARTITION " +
"(string_col='partition2') set fileformat sequencefile",
- "Partition spec does not exist: (string_col='partition2')");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set location '/a/b'",
- "Partition spec does not exist: " +
- "(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
+ "No matching partition(s) found.");
AnalysisError("alter table functional.alltypes PARTITION " +
"(year=cast(10*20+10 as INT), month=cast(5*3 as INT)) " +
"set fileformat sequencefile",
- "Partition spec does not exist: " +
- "(year=CAST(10 * 20 + 10 AS INT), month=CAST(5 * 3 AS INT))");
+ "No matching partition(s) found.");
// Table/Db does not exist
AnalysisError("alter table db_does_not_exist.alltypes set fileformat sequencefile",
- "Database does not exist: db_does_not_exist");
+ "Could not resolve table reference: 'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist set fileformat rcfile",
- "Table does not exist: functional.table_does_not_exist");
+ "Could not resolve table reference: 'functional.table_does_not_exist'");
AnalysisError("alter table db_does_not_exist.alltypes set location '/a/b'",
- "Database does not exist: db_does_not_exist");
+ "Could not resolve table reference: 'db_does_not_exist.alltypes'");
AnalysisError("alter table functional.table_does_not_exist set location '/a/b'",
- "Table does not exist: functional.table_does_not_exist");
+ "Could not resolve table reference: 'functional.table_does_not_exist'");
AnalysisError("alter table functional.no_tbl partition(i=1) set location '/a/b'",
- "Table does not exist: functional.no_tbl");
+ "Could not resolve table reference: 'functional.no_tbl'");
AnalysisError("alter table no_db.alltypes partition(i=1) set fileformat textfile",
- "Database does not exist: no_db");
+ "Could not resolve table reference: 'no_db.alltypes'");
// Valid location
AnalyzesOk("alter table functional.alltypes set location " +
@@ -507,6 +577,10 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view set fileformat sequencefile",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot ALTER TABLE a nested collection.
+ AnalysisError("alter table allcomplextypes.int_array_col set fileformat sequencefile",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
// Cannot ALTER TABLE produced by a data source.
AnalysisError("alter table functional.alltypes_datasource set fileformat parquet",
"ALTER TABLE not allowed on a table produced by a data source: " +
@@ -524,6 +598,8 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalyzesOk("alter table functional.alltypes set cached in 'testPool'");
AnalyzesOk("alter table functional.alltypes partition(year=2010, month=12) " +
"set cached in 'testPool'");
+ AnalyzesOk("alter table functional.alltypes partition(year<=2010, month<=12) " +
+ "set cached in 'testPool'");
// Replication factor
AnalyzesOk("alter table functional.alltypes set cached in 'testPool' " +
@@ -542,6 +618,9 @@ public class AnalyzeDDLTest extends FrontendTestBase {
"ALTER TABLE SET not currently supported on HBase tables.");
AnalysisError("alter table functional.view_view set cached in 'testPool'",
"ALTER TABLE not allowed on a view: functional.view_view");
+ AnalysisError("alter table allcomplextypes.int_array_col set cached in 'testPool'",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
AnalysisError("alter table functional.alltypes set cached in 'badPool'",
"The specified cache pool does not exist: badPool");
@@ -565,17 +644,17 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalysisError("alter table functional.alltypestiny partition (year=2009,month=1) " +
"set location '/test-warehouse/new_location'",
"Target partition is cached, please uncache before changing the location " +
- "using: ALTER TABLE functional.alltypestiny PARTITION (year=2009, month=1) " +
+ "using: ALTER TABLE functional.alltypestiny PARTITION (year = 2009, month = 1) " +
"SET UNCACHED");
// Table/db/partition do not exist
AnalysisError("alter table baddb.alltypestiny set cached in 'testPool'",
- "Database does not exist: baddb");
+ "Could not resolve table reference: 'baddb.alltypestiny'");
AnalysisError("alter table functional.badtbl set cached in 'testPool'",
- "Table does not exist: functional.badtbl");
+ "Could not resolve table reference: 'functional.badtbl'");
AnalysisError("alter table functional.alltypestiny partition(year=9999, month=1) " +
"set cached in 'testPool'",
- "Partition spec does not exist: (year=9999, month=1).");
+ "No matching partition(s) found.");
}
@Test
@@ -646,7 +725,7 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Table does not exist.
AnalysisError("alter table bad_tbl set column stats int_col ('numNulls'='2')",
- "Table does not exist: default.bad_tbl");
+ "Could not resolve table reference: 'bad_tbl'");
// Column does not exist.
AnalysisError(
"alter table functional.alltypes set column stats bad_col ('numNulls'='2')",
@@ -656,6 +735,12 @@ public class AnalyzeDDLTest extends FrontendTestBase {
AnalysisError(
"alter table functional.alltypes_view set column stats int_col ('numNulls'='2')",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot set column stats of a nested collection.
+ AnalysisError(
+ "alter table allcomplextypes.int_array_col " +
+ "set column stats int_col ('numNulls'='2')",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
// Cannot set column stats of partition columns.
AnalysisError(
"alter table functional.alltypes set column stats month ('numDVs'='10')",
@@ -835,6 +920,10 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Cannot ALTER TABLE a view.
AnalysisError("alter table functional.alltypes_view rename to new_alltypes",
"ALTER TABLE not allowed on a view: functional.alltypes_view");
+ // Cannot ALTER TABLE a nested collection.
+ AnalysisError("alter table allcomplextypes.int_array_col rename to new_alltypes",
+ createAnalyzer("functional"),
+ "Database does not exist: allcomplextypes");
// It should be okay to rename an HBase table.
AnalyzesOk("alter table functional_hbase.alltypes rename to new_alltypes");
@@ -847,13 +936,16 @@ public class AnalyzeDDLTest extends FrontendTestBase {
public void TestAlterTableRecoverPartitions() throws CatalogException {
AnalyzesOk("alter table functional.alltypes recover partitions");
AnalysisError("alter table baddb.alltypes recover partitions",
- "Database does not exist: baddb");
+ "Could not resolve table reference: 'baddb.alltypes'");
AnalysisError("alter table functional.badtbl recover partitions",
- "Table does not exist: functional.badtbl");
+ "Could not resolve table reference: 'functional.badtbl'");
AnalysisError("alter table functional.alltypesnopart recover partitions",
"Table is not partitioned: functional.alltypesnopart");
AnalysisError("alter table functional.view_view recover partitions",
"ALTER TABLE not allowed on a view: functional.view_view");
+ AnalysisError("alter table allcomplextypes.int_array_col recover partitions",
+ createAnalyzer("functional"),
+ "ALTER TABLE not allowed on a nested collection: allcomplextypes.int_array_col");
AnalysisError("alter table functional_hbase.alltypes recover partitions",
"ALTER TABLE RECOVER PARTITIONS must target an HDFS table: " +
"functional_hbase.alltypes");
@@ -958,10 +1050,10 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Cannot compute stats on a database.
AnalysisError("compute stats tbl_does_not_exist",
- "Table does not exist: default.tbl_does_not_exist");
+ "Could not resolve table reference: 'tbl_does_not_exist'");
// Cannot compute stats on a view.
AnalysisError("compute stats functional.alltypes_view",
- "COMPUTE STATS not supported for view functional.alltypes_view");
+ "COMPUTE STATS not supported for view: functional.alltypes_view");
AnalyzesOk("compute stats functional_avro_snap.alltypes");
// Test mismatched column definitions and Avro schema (HIVE-6308, IMPALA-867).
@@ -991,28 +1083,26 @@ public class AnalyzeDDLTest extends FrontendTestBase {
checkComputeStatsStmt("compute incremental stats functional.alltypes");
checkComputeStatsStmt(
"compute incremental stats functional.alltypes partition(year=2010, month=10)");
+ checkComputeStatsStmt(
+ "compute incremental stats functional.alltypes partition(year<=2010)");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=9999, month=10)",
- "Partition spec does not exist: (year=9999, month=10)");
- AnalysisError(
- "compute incremental stats functional.alltypes partition(year=2010)",
- "Items in partition spec must exactly match the partition columns in the table " +
- "definition: functional.alltypes (1 vs 2)");
+ "No matching partition(s) found.");
AnalysisError(
"compute incremental stats functional.alltypes partition(year=2010, month)",
- "Syntax error");
+ "Partition expr requires return type 'BOOLEAN'. Actual type is 'INT'.");
// Test that NULL partitions generates a valid query
checkComputeStatsStmt("compute incremental stats functional.alltypesagg " +
- "partition(year=2010, month=1, day=NULL)");
+ "partition(year=2010, month=1, day is NULL)");
AnalysisError("compute incremental stats functional_hbase.alltypes " +
"partition(year=2010, month=1)", "COMPUTE INCREMENTAL ... PARTITION not " +
"supported for non-HDFS table functional_hbase.alltypes");
AnalysisError("compute incremental stats functional.view_view",
- "COMPUTE STATS not supported for view functional.view_view");
+ "COMPUTE STATS not supported for view: functional.view_view");
}
@@ -1020,9 +1110,11 @@ public class AnalyzeDDLTest extends FrontendTestBase {
public void TestDropIncrementalStats() throws AnalysisException {
AnalyzesOk(
"drop incremental stats functional.alltypes partition(year=2010, month=10)");
+ AnalyzesOk(
+ "drop incremental stats functional.alltypes partition(year<=2010, month=10)");
AnalysisError(
"drop incremental stats functional.alltypes partition(year=9999, month=10)",
- "Partition spec does not exist: (year=9999, month=10)");
+ "No matching partition(s) found.");
}
@@ -1032,10 +1124,10 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Table does not exist
AnalysisError("drop stats tbl_does_not_exist",
- "Table does not exist: default.tbl_does_not_exist");
+ "Could not resolve table reference: 'tbl_does_not_exist'");
// Database does not exist
AnalysisError("drop stats no_db.no_tbl",
- "Database does not exist: no_db");
+ "Could not resolve table reference: 'no_db.no_tbl'");
AnalysisError("drop stats functional.alltypes partition(year=2010, month=10)",
"Syntax error");
@@ -2959,32 +3051,38 @@ public class AnalyzeDDLTest extends FrontendTestBase {
// Test empty table
AnalyzesOk(String.format("show files in functional.emptytable"));
- String[] partitions = new String[] { "", "partition(month=10, year=2010)" };
+ String[] partitions = new String[] {
+ "",
+ "partition(month=10, year=2010)",
+ "partition(month>10, year<2011, year>2008)"};
for (String partition: partitions) {
AnalyzesOk(String.format("show files in functional.alltypes %s", partition));
// Database/table doesn't exist.
AnalysisError(String.format("show files in baddb.alltypes %s", partition),
- "Database does not exist: baddb");
+ "Could not resolve table reference: 'baddb.alltypes'");
AnalysisError(String.format("show files in functional.badtbl %s", partition),
- "Table does not exist: functional.badtbl");
+ "Could not resolve table reference: 'functional.badtbl'");
// Cannot show files on a non hdfs table.
AnalysisError(String.format("show files in functional.alltypes_view %s",
partition),
"SHOW FILES not applicable to a non hdfs table: functional.alltypes_view");
+ AnalysisError(String.format("show files in allcomplextypes.int_array_col %s",
+ partition), createAnalyzer("functional"),
+ "SHOW FILES not applicable to a non hdfs table: allcomplextypes.int_array_col");
}
// Not a partition column.
AnalysisError("show files in functional.alltypes partition(year=2010,int_col=1)",
- "Column 'int_col' is not a partition column in table: functional.alltypes");
+ "Partition exprs cannot contain non-partition column(s): int_col = 1.");
// Not a valid column.
AnalysisError("show files in functional.alltypes partition(year=2010,day=1)",
- "Partition column 'day' not found in table: functional.alltypes");
+ "Could not resolve column/field reference: 'day'");
// Table is not partitioned.
AnalysisError("show files in functional.tinyinttable partition(int_col=1)",
"Table is not partitioned: functional.tinyinttable");
// Partition spec does not exist
AnalysisError("show files in functional.alltypes partition(year=2010,month=NULL)",
- "Partition spec does not exist: (year=2010, month=NULL)");
+ "No matching partition(s) found.");
}
@Test
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 a6760de..cacdd83 100644
--- a/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/AnalyzeStmtsTest.java
@@ -3466,7 +3466,7 @@ public class AnalyzeStmtsTest extends AnalyzerTest {
testNumberOfMembers(ValuesStmt.class, 0);
// Also check TableRefs.
- testNumberOfMembers(TableRef.class, 18);
+ testNumberOfMembers(TableRef.class, 19);
testNumberOfMembers(BaseTableRef.class, 0);
testNumberOfMembers(InlineViewRef.class, 8);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
----------------------------------------------------------------------
diff --git a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
index 0affd4e..69c90da 100644
--- a/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
+++ b/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
@@ -1768,8 +1768,8 @@ public class ParserTest extends FrontendTestBase {
ParserError("SHOW TABLE STATS 'strlit'");
// Missing table.
ParserError("SHOW FILES IN");
- // Invalid partition.
- ParserError("SHOW FILES IN db.tbl PARTITION(p)");
+
+ ParsesOk("SHOW FILES IN db.tbl PARTITION(p)");
}
@Test
@@ -2002,9 +2002,6 @@ public class ParserTest extends FrontendTestBase {
ParsesOk("ALTER TABLE Foo ADD PARTITION (i=NULL, j=2, k=NULL)");
ParsesOk("ALTER TABLE Foo ADD PARTITION (i=abc, j=(5*8+10), k=!true and false)");
- // Cannot use dynamic partition syntax
- ParserError("ALTER TABLE TestDb.Foo ADD PARTITION (partcol)");
- ParserError("ALTER TABLE TestDb.Foo ADD PARTITION (i=1, partcol)");
// Location needs to be a string literal
ParserError("ALTER TABLE TestDb.Foo ADD PARTITION (i=1, s='Hello') LOCATION a/b");
@@ -2070,10 +2067,6 @@ public class ParserTest extends FrontendTestBase {
ParsesOk(String.format("ALTER TABLE Foo DROP PARTITION (i=abc, "
+ "j=(5*8+10), k=!true and false) %s", kw));
- // Cannot use dynamic partition syntax
- ParserError(String.format("ALTER TABLE Foo DROP PARTITION (partcol) %s", kw));
- ParserError(String.format("ALTER TABLE Foo DROP PARTITION (i=1, j) %s", kw));
-
ParserError(String.format("ALTER TABLE Foo DROP IF NOT EXISTS "
+ "PARTITION (i=1, s='Hello') %s", kw));
ParserError(String.format("ALTER TABLE TestDb.Foo DROP (i=1, s='Hello') %s", kw));
@@ -2126,10 +2119,7 @@ public class ParserTest extends FrontendTestBase {
ParsesOk("ALTER TABLE Foo PARTITION (i=1,s='str') SET LOCATION '/a/i=1/s=str'");
ParsesOk("ALTER TABLE Foo PARTITION (s='str') SET LOCATION '/a/i=1/s=str'");
- ParserError("ALTER TABLE Foo PARTITION (s) SET LOCATION '/a'");
ParserError("ALTER TABLE Foo PARTITION () SET LOCATION '/a'");
- ParserError("ALTER TABLE Foo PARTITION ('str') SET FILEFORMAT TEXTFILE");
- ParserError("ALTER TABLE Foo PARTITION (a=1, 5) SET FILEFORMAT TEXTFILE");
ParserError("ALTER TABLE Foo PARTITION () SET FILEFORMAT PARQUETFILE");
ParserError("ALTER TABLE Foo PARTITION (,) SET FILEFORMAT PARQUET");
ParserError("ALTER TABLE Foo PARTITION (a=1) SET FILEFORMAT");
@@ -3331,13 +3321,10 @@ public class ParserTest extends FrontendTestBase {
ParsesOk(
"COMPUTE INCREMENTAL STATS functional.alltypes PARTITION(month=10, year=2010)");
- // No dynamic partition specs
- ParserError("COMPUTE INCREMENTAL STATS functional.alltypes PARTITION(month, year)");
ParserError("COMPUTE INCREMENTAL STATS");
ParsesOk("DROP INCREMENTAL STATS functional.alltypes PARTITION(month=10, year=2010)");
- ParserError("DROP INCREMENTAL STATS functional.alltypes PARTITION(month, year)");
ParserError("DROP INCREMENTAL STATS functional.alltypes");
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/shell/impala_client.py
----------------------------------------------------------------------
diff --git a/shell/impala_client.py b/shell/impala_client.py
index f57a015..f84c14e 100755
--- a/shell/impala_client.py
+++ b/shell/impala_client.py
@@ -450,7 +450,7 @@ class ImpalaClient(object):
def expect_result_metadata(self, query_str):
""" Given a query string, return True if impalad expects result metadata"""
- excluded_query_types = ['use', 'alter', 'drop']
+ excluded_query_types = ['use', 'drop']
if True in set(map(query_str.startswith, excluded_query_types)):
return False
return True
[28/50] [abbrv] incubator-impala git commit: IMPALA-3710: Kudu DML
should ignore conflicts, pt2
Posted by ta...@apache.org.
IMPALA-3710: Kudu DML should ignore conflicts, pt2
Second part of IMPALA-3710, which removed the IGNORE DML
option and changed the following errors on Kudu DML
operations to be ignored:
1) INSERT where the PK already exists
2) UPDATE/DELETE where the PK doesn't exist
This changes other data-related errors to be ignored as
well:
3) NULLs in non-nullable columns, i.e. null constraint
violoations.
4) Rows with PKs that are in an 'uncovered range'.
It became clear that we can't differentiate between (3) and
(4) because both return a Kudu 'NotFound' error code. The
Impala error codes have been simplified as well: we just
report a generic KUDU_NOT_FOUND error in these cases.
This also adds some metadata to the thrift report sent to
the coordinator from sinks so the total number of rows with
errors can be added to the profile. Note that this does not
include a breakdown of error counts by type/code because we
cannot differentiate between all of these cases yet.
An upcoming change will add this new info to the beeswax
interface and show it in the shell output (IMPALA-3713).
Testing: Updated kudu_crud tests to check the number of rows
with errors.
Change-Id: I4eb1ad91dc355ea51de261c3a14df0f9d28c879c
Reviewed-on: http://gerrit.cloudera.org:8080/4985
Reviewed-by: Alex Behm <al...@cloudera.com>
Reviewed-by: Dan Hecht <dh...@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/cfac09de
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/cfac09de
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/cfac09de
Branch: refs/heads/hadoop-next
Commit: cfac09de10c996a48852b9a9d50c70cf24cf5f5f
Parents: d7246d6
Author: Matthew Jacobs <mj...@cloudera.com>
Authored: Mon Nov 7 15:55:42 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 06:43:41 2016 +0000
----------------------------------------------------------------------
be/src/exec/data-sink.cc | 17 ++-
be/src/exec/data-sink.h | 9 +-
be/src/exec/hdfs-table-sink.cc | 2 +-
be/src/exec/kudu-table-sink.cc | 89 +++++++++-------
be/src/exec/kudu-table-sink.h | 31 +++---
be/src/runtime/coordinator.cc | 4 +-
common/thrift/ImpalaInternalService.thrift | 21 +++-
common/thrift/generate_error_codes.py | 5 +-
.../queries/QueryTest/kudu_crud.test | 103 ++++++++++++-------
9 files changed, 180 insertions(+), 101 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/exec/data-sink.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/data-sink.cc b/be/src/exec/data-sink.cc
index 6a34543..17f1f8c 100644
--- a/be/src/exec/data-sink.cc
+++ b/be/src/exec/data-sink.cc
@@ -112,9 +112,18 @@ Status DataSink::CreateDataSink(ObjectPool* pool,
return Status::OK();
}
-void DataSink::MergeInsertStats(const TInsertStats& src_stats,
+void DataSink::MergeDmlStats(const TInsertStats& src_stats,
TInsertStats* dst_stats) {
dst_stats->bytes_written += src_stats.bytes_written;
+ if (src_stats.__isset.kudu_stats) {
+ if (!dst_stats->__isset.kudu_stats) dst_stats->__set_kudu_stats(TKuduDmlStats());
+ if (!dst_stats->kudu_stats.__isset.num_row_errors) {
+ dst_stats->kudu_stats.__set_num_row_errors(0);
+ }
+
+ dst_stats->kudu_stats.__set_num_row_errors(
+ dst_stats->kudu_stats.num_row_errors + src_stats.kudu_stats.num_row_errors);
+ }
if (src_stats.__isset.parquet_stats) {
if (dst_stats->__isset.parquet_stats) {
MergeMapValues<string, int64_t>(src_stats.parquet_stats.per_column_size,
@@ -125,7 +134,7 @@ void DataSink::MergeInsertStats(const TInsertStats& src_stats,
}
}
-string DataSink::OutputInsertStats(const PartitionStatusMap& stats,
+string DataSink::OutputDmlStats(const PartitionStatusMap& stats,
const string& prefix) {
const char* indent = " ";
stringstream ss;
@@ -148,6 +157,10 @@ string DataSink::OutputInsertStats(const PartitionStatusMap& stats,
if (!val.second.__isset.stats) continue;
const TInsertStats& stats = val.second.stats;
+ if (stats.__isset.kudu_stats) {
+ ss << "NumRowErrors: " << stats.kudu_stats.num_row_errors << endl;
+ }
+
ss << indent << "BytesWritten: "
<< PrettyPrinter::Print(stats.bytes_written, TUnit::BYTES);
if (stats.__isset.parquet_stats) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/exec/data-sink.h
----------------------------------------------------------------------
diff --git a/be/src/exec/data-sink.h b/be/src/exec/data-sink.h
index 95acf16..1970cf2 100644
--- a/be/src/exec/data-sink.h
+++ b/be/src/exec/data-sink.h
@@ -85,14 +85,13 @@ class DataSink {
const TPlanFragmentInstanceCtx& fragment_instance_ctx,
const RowDescriptor& row_desc, boost::scoped_ptr<DataSink>* sink);
- /// Merges one update to the insert stats for a partition. dst_stats will have the
+ /// Merges one update to the DML stats for a partition. dst_stats will have the
/// combined stats of src_stats and dst_stats after this method returns.
- static void MergeInsertStats(const TInsertStats& src_stats,
+ static void MergeDmlStats(const TInsertStats& src_stats,
TInsertStats* dst_stats);
- /// Outputs the insert stats contained in the map of insert partition updates to a
- /// string
- static std::string OutputInsertStats(const PartitionStatusMap& stats,
+ /// Outputs the DML stats contained in the map of partition updates to a string
+ static std::string OutputDmlStats(const PartitionStatusMap& stats,
const std::string& prefix = "");
MemTracker* mem_tracker() const { return mem_tracker_; }
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/exec/hdfs-table-sink.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-table-sink.cc b/be/src/exec/hdfs-table-sink.cc
index 63bd648..07c1167 100644
--- a/be/src/exec/hdfs-table-sink.cc
+++ b/be/src/exec/hdfs-table-sink.cc
@@ -595,7 +595,7 @@ Status HdfsTableSink::FinalizePartitionFile(RuntimeState* state,
// initialised.
DCHECK(it != state->per_partition_status()->end());
it->second.num_modified_rows += partition->num_rows;
- DataSink::MergeInsertStats(partition->writer->stats(), &it->second.stats);
+ DataSink::MergeDmlStats(partition->writer->stats(), &it->second.stats);
}
RETURN_IF_ERROR(ClosePartitionFile(state, partition));
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/exec/kudu-table-sink.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.cc b/be/src/exec/kudu-table-sink.cc
index a58baab..11613aa 100644
--- a/be/src/exec/kudu-table-sink.cc
+++ b/be/src/exec/kudu-table-sink.cc
@@ -61,9 +61,9 @@ KuduTableSink::KuduTableSink(const RowDescriptor& row_desc,
select_list_texprs_(select_list_texprs),
sink_action_(tsink.table_sink.action),
kudu_table_sink_(tsink.table_sink.kudu_table_sink),
- kudu_error_counter_(NULL),
- rows_written_(NULL),
- rows_written_rate_(NULL) {
+ total_rows_(NULL),
+ num_row_errors_(NULL),
+ rows_processed_rate_(NULL) {
DCHECK(KuduIsAvailable());
}
@@ -96,15 +96,19 @@ Status KuduTableSink::Prepare(RuntimeState* state, MemTracker* mem_tracker) {
TInsertPartitionStatus root_status;
root_status.__set_num_modified_rows(0L);
root_status.__set_id(-1L);
+ TKuduDmlStats kudu_dml_stats;
+ kudu_dml_stats.__set_num_row_errors(0L);
+ root_status.__set_stats(TInsertStats());
+ root_status.stats.__set_kudu_stats(kudu_dml_stats);
state->per_partition_status()->insert(make_pair(ROOT_PARTITION_KEY, root_status));
// Add counters
- kudu_error_counter_ = ADD_COUNTER(profile(), "TotalKuduFlushErrors", TUnit::UNIT);
- rows_written_ = ADD_COUNTER(profile(), "RowsWritten", TUnit::UNIT);
+ total_rows_ = ADD_COUNTER(profile(), "TotalNumRows", TUnit::UNIT);
+ num_row_errors_ = ADD_COUNTER(profile(), "NumRowErrors", TUnit::UNIT);
kudu_apply_timer_ = ADD_TIMER(profile(), "KuduApplyTimer");
- rows_written_rate_ = profile()->AddDerivedCounter(
- "RowsWrittenRate", TUnit::UNIT_PER_SECOND,
- bind<int64_t>(&RuntimeProfile::UnitsPerSecond, rows_written_,
+ rows_processed_rate_ = profile()->AddDerivedCounter(
+ "RowsProcessedRate", TUnit::UNIT_PER_SECOND,
+ bind<int64_t>(&RuntimeProfile::UnitsPerSecond, total_rows_,
profile()->total_time_counter()));
return Status::OK();
@@ -174,16 +178,21 @@ Status KuduTableSink::Send(RuntimeState* state, RowBatch* batch) {
SCOPED_TIMER(profile()->total_time_counter());
ExprContext::FreeLocalAllocations(output_expr_ctxs_);
RETURN_IF_ERROR(state->CheckQueryState());
+ const KuduSchema& table_schema = table_->schema();
// Collect all write operations and apply them together so the time in Apply() can be
// easily timed.
vector<unique_ptr<kudu::client::KuduWriteOperation>> write_ops;
- int rows_added = 0;
+ // Count the number of rows with nulls in non-nullable columns, i.e. null constraint
+ // violations.
+ int num_null_violations = 0;
+
// Since everything is set up just forward everything to the writer.
for (int i = 0; i < batch->num_rows(); ++i) {
TupleRow* current_row = batch->GetRow(i);
unique_ptr<kudu::client::KuduWriteOperation> write(NewWriteOp());
+ bool add_row = true;
for (int j = 0; j < output_expr_ctxs_.size(); ++j) {
// For INSERT, output_expr_ctxs_ will contain all columns of the table in order.
@@ -198,14 +207,20 @@ Status KuduTableSink::Send(RuntimeState* state, RowBatch* batch) {
// If the value is NULL, we only need to explicitly set it for UPDATE and UPSERT.
// For INSERT, it can be ignored as unspecified cols will be implicitly set to NULL.
if (value == NULL) {
- if (sink_action_ == TSinkAction::UPDATE || sink_action_ == TSinkAction::UPSERT) {
- DCHECK(!kudu_table_sink_.referenced_columns.empty());
+ if (table_schema.Column(j).is_nullable()) {
KUDU_RETURN_IF_ERROR(write->mutable_row()->SetNull(col),
"Could not add Kudu WriteOp.");
+ continue;
} else {
- DCHECK(kudu_table_sink_.referenced_columns.empty());
+ // This row violates the nullability constraints of the column, do not attempt
+ // to write this row because it is already known to be an error and the Kudu
+ // error will be difficult to interpret later (error code isn't specific).
+ ++num_null_violations;
+ state->LogError(ErrorMsg::Init(TErrorCode::KUDU_NULL_CONSTRAINT_VIOLATION,
+ table_desc_->table_name()));
+ add_row = false;
+ break; // skip remaining columns for this row
}
- continue;
}
PrimitiveType type = output_expr_ctxs_[j]->root()->type().type;
@@ -257,18 +272,22 @@ Status KuduTableSink::Send(RuntimeState* state, RowBatch* batch) {
return Status(TErrorCode::IMPALA_KUDU_TYPE_MISSING, TypeToString(type));
}
}
- write_ops.push_back(move(write));
+ if (add_row) write_ops.push_back(move(write));
}
{
SCOPED_TIMER(kudu_apply_timer_);
for (auto&& write: write_ops) {
KUDU_RETURN_IF_ERROR(session_->Apply(write.release()), "Error applying Kudu Op.");
- ++rows_added;
}
}
- COUNTER_ADD(rows_written_, rows_added);
+ // Increment for all rows received by the sink, including errors.
+ COUNTER_ADD(total_rows_, batch->num_rows());
+ // Add the number of null constraint violations to the number of row errors, which
+ // isn't reported by Kudu in CheckForErrors() because those rows were never
+ // successfully added to the KuduSession.
+ COUNTER_ADD(num_row_errors_, num_null_violations);
RETURN_IF_ERROR(CheckForErrors(state));
return Status::OK();
}
@@ -281,7 +300,6 @@ Status KuduTableSink::CheckForErrors(RuntimeState* state) {
// Get the pending errors from the Kudu session. If errors overflowed the error buffer
// we can't be sure all errors can be ignored, so an error status will be reported.
- // TODO: Make sure Kudu handles conflict errors properly if IGNORE is set (KUDU-1563).
bool error_overflow = false;
session_->GetPendingErrors(&errors, &error_overflow);
if (UNLIKELY(error_overflow)) {
@@ -292,28 +310,27 @@ Status KuduTableSink::CheckForErrors(RuntimeState* state) {
// them accordingly.
for (int i = 0; i < errors.size(); ++i) {
kudu::Status e = errors[i]->status();
- // 'Duplicate key' or 'key already present' errors from Kudu do not fail the query.
- if ((sink_action_ == TSinkAction::DELETE && !e.IsNotFound()) ||
- (sink_action_ == TSinkAction::UPDATE && !e.IsNotFound()) ||
- (sink_action_ == TSinkAction::INSERT && !e.IsAlreadyPresent())) {
- if (status.ok()) {
- status = Status(strings::Substitute(
- "Kudu error(s) reported, first error: $0", e.ToString()));
- }
- }
if (e.IsNotFound()) {
- state->LogError(ErrorMsg::Init(TErrorCode::KUDU_KEY_NOT_FOUND,
- table_desc_->table_name()));
+ // Kudu does not yet have a way to programmatically differentiate between 'row not
+ // found' and 'tablet not found' (e.g. PK in a non-covered range) and both have the
+ // IsNotFound error code.
+ state->LogError(ErrorMsg::Init(TErrorCode::KUDU_NOT_FOUND,
+ table_desc_->table_name(), e.ToString()), 2);
} else if (e.IsAlreadyPresent()) {
state->LogError(ErrorMsg::Init(TErrorCode::KUDU_KEY_ALREADY_PRESENT,
- table_desc_->table_name()));
+ table_desc_->table_name()), 2);
} else {
+ if (status.ok()) {
+ status = Status(strings::Substitute(
+ "Kudu error(s) reported, first error: $0", e.ToString()));
+ }
state->LogError(ErrorMsg::Init(TErrorCode::KUDU_SESSION_ERROR,
- table_desc_->table_name(), e.ToString()));
+ table_desc_->table_name(), e.ToString()), 2);
}
delete errors[i];
}
- COUNTER_ADD(kudu_error_counter_, errors.size());
+
+ COUNTER_ADD(num_row_errors_, errors.size());
return status;
}
@@ -326,10 +343,12 @@ Status KuduTableSink::FlushFinal(RuntimeState* state) {
VLOG_RPC << "Ignoring Flush() error status: " << flush_status.ToString();
}
Status status = CheckForErrors(state);
- (*state->per_partition_status())[ROOT_PARTITION_KEY].__set_num_modified_rows(
- rows_written_->value() - kudu_error_counter_->value());
- (*state->per_partition_status())[ROOT_PARTITION_KEY].__set_kudu_latest_observed_ts(
- client_->GetLatestObservedTimestamp());
+ TInsertPartitionStatus& insert_status =
+ (*state->per_partition_status())[ROOT_PARTITION_KEY];
+ insert_status.__set_num_modified_rows(
+ total_rows_->value() - num_row_errors_->value());
+ insert_status.stats.kudu_stats.__set_num_row_errors(num_row_errors_->value());
+ insert_status.__set_kudu_latest_observed_ts(client_->GetLatestObservedTimestamp());
return status;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/exec/kudu-table-sink.h
----------------------------------------------------------------------
diff --git a/be/src/exec/kudu-table-sink.h b/be/src/exec/kudu-table-sink.h
index adf264e..3ff667c 100644
--- a/be/src/exec/kudu-table-sink.h
+++ b/be/src/exec/kudu-table-sink.h
@@ -44,14 +44,13 @@ namespace impala {
/// because Kudu currently has some 8MB buffer limits.
///
/// Kudu doesn't have transactions yet, so some rows may fail to write while others are
-/// successful. The Kudu client reports errors, some of which may be considered to be
-/// expected: rows that fail to be written/updated/deleted due to a key conflict will not
-/// result in the sink returning an error. Any other kind of error reported by Kudu
-/// results in the sink returning an error status. The first non-ignored error is
-/// returned in the sink's Status. All reported errors (ignored or not) will be logged
-/// via the RuntimeState.
-/// TODO: Handle other data/constraint-violation errors as ignored, e.g. null in
-/// non-nullable col
+/// successful. The Kudu client reports errors, some of which are treated as warnings and
+/// will not fail the query: PK already exists on INSERT, key not found on UPDATE/DELETE,
+/// NULL in a non-nullable column, and PK specifying rows in an uncovered range.
+/// The number of rows that cannot be modified due to these errors is reported in the
+/// TInsertPartitionStatus report sent by the DataSink to the coordinator.
+/// Any other kind of error reported by Kudu results in the sink returning an error
+/// status. All reported errors (ignored or not) will be logged via the RuntimeState.
class KuduTableSink : public DataSink {
public:
KuduTableSink(const RowDescriptor& row_desc,
@@ -101,7 +100,6 @@ class KuduTableSink : public DataSink {
std::vector<ExprContext*> output_expr_ctxs_;
/// The Kudu client, table and session.
- /// This uses 'kudu::client::sp::shared_ptr' as that is the type expected by Kudu.
kudu::client::sp::shared_ptr<kudu::client::KuduClient> client_;
kudu::client::sp::shared_ptr<kudu::client::KuduTable> table_;
kudu::client::sp::shared_ptr<kudu::client::KuduSession> session_;
@@ -112,19 +110,22 @@ class KuduTableSink : public DataSink {
/// Captures parameters passed down from the frontend
TKuduTableSink kudu_table_sink_;
- /// Total number of errors returned from Kudu.
- RuntimeProfile::Counter* kudu_error_counter_;
-
/// Time spent applying Kudu operations. In normal circumstances, Apply() should be
/// negligible because it is asynchronous with AUTO_FLUSH_BACKGROUND enabled.
/// Significant time spent in Apply() may indicate that Kudu cannot buffer and send
/// rows as fast as the sink can write them.
RuntimeProfile::Counter* kudu_apply_timer_;
- /// Total number of rows written including errors.
- RuntimeProfile::Counter* rows_written_;
- RuntimeProfile::Counter* rows_written_rate_;
+ /// Total number of rows processed, i.e. rows written to Kudu and also rows with
+ /// errors.
+ RuntimeProfile::Counter* total_rows_;
+
+ /// The number of rows with errors.
+ RuntimeProfile::Counter* num_row_errors_;
+ /// Rate at which the sink consumes and processes rows, i.e. writing rows to Kudu or
+ /// skipping rows that are known to violate nullability constraints.
+ RuntimeProfile::Counter* rows_processed_rate_;
};
} // namespace impala
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/be/src/runtime/coordinator.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/coordinator.cc b/be/src/runtime/coordinator.cc
index c9a166d..0a278ae 100644
--- a/be/src/runtime/coordinator.cc
+++ b/be/src/runtime/coordinator.cc
@@ -1090,7 +1090,7 @@ Status Coordinator::Wait() {
if (needs_finalization_) RETURN_IF_ERROR(FinalizeQuery());
query_profile_->AddInfoString(
- "Insert Stats", DataSink::OutputInsertStats(per_partition_status_, "\n"));
+ "DML Stats", DataSink::OutputDmlStats(per_partition_status_, "\n"));
// For DML queries, when Wait is done, the query is complete. Report aggregate
// query profiles at this point.
// TODO: make sure ReportQuerySummary gets called on error
@@ -1489,7 +1489,7 @@ Status Coordinator::UpdateFragmentExecStatus(const TReportExecStatusParams& para
if (partition.second.__isset.stats) {
if (!status->__isset.stats) status->__set_stats(TInsertStats());
- DataSink::MergeInsertStats(partition.second.stats, &status->stats);
+ DataSink::MergeDmlStats(partition.second.stats, &status->stats);
}
}
files_to_move_.insert(
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/common/thrift/ImpalaInternalService.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/ImpalaInternalService.thrift b/common/thrift/ImpalaInternalService.thrift
index 15c0020..d5a92ca 100644
--- a/common/thrift/ImpalaInternalService.thrift
+++ b/common/thrift/ImpalaInternalService.thrift
@@ -410,16 +410,28 @@ struct TParquetInsertStats {
1: required map<string, i64> per_column_size
}
-// Per partition insert stats
+struct TKuduDmlStats {
+ // The number of reported per-row errors, i.e. this many rows were not modified.
+ // Note that this aggregate is less useful than a breakdown of the number of errors by
+ // error type, e.g. number of rows with duplicate key conflicts, number of rows
+ // violating nullability constraints, etc., but it isn't possible yet to differentiate
+ // all error types in the KuduTableSink yet.
+ 1: optional i64 num_row_errors
+}
+
+// Per partition DML stats
// TODO: this should include the table stats that we update the metastore with.
+// TODO: Refactor to reflect usage by other DML statements.
struct TInsertStats {
1: required i64 bytes_written
2: optional TParquetInsertStats parquet_stats
+ 3: optional TKuduDmlStats kudu_stats
}
const string ROOT_PARTITION_KEY = ''
-// Per-partition statistics and metadata resulting from INSERT queries.
+// Per-partition statistics and metadata resulting from DML statements.
+// TODO: Refactor to reflect usage by other DML statements.
struct TInsertPartitionStatus {
// The id of the partition written to (may be -1 if the partition is created by this
// query). See THdfsTable.partitions.
@@ -434,13 +446,14 @@ struct TInsertPartitionStatus {
// Fully qualified URI to the base directory for this partition.
4: required string partition_base_dir
- // The latest observed Kudu timestamp reported by the KuduSession at this partition.
+ // The latest observed Kudu timestamp reported by the local KuduSession.
// This value is an unsigned int64.
5: optional i64 kudu_latest_observed_ts
}
-// The results of an INSERT query, sent to the coordinator as part of
+// The results of a DML statement, sent to the coordinator as part of
// TReportExecStatusParams
+// TODO: Refactor to reflect usage by other DML statements.
struct TInsertExecStatus {
// A map from temporary absolute file path to final absolute destination. The
// coordinator performs these updates after the query completes.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/common/thrift/generate_error_codes.py
----------------------------------------------------------------------
diff --git a/common/thrift/generate_error_codes.py b/common/thrift/generate_error_codes.py
index e9df146..c96cfc8 100755
--- a/common/thrift/generate_error_codes.py
+++ b/common/thrift/generate_error_codes.py
@@ -295,7 +295,7 @@ error_codes = (
("KUDU_KEY_ALREADY_PRESENT", 95, "Key already present in Kudu table '$0'."),
- ("KUDU_KEY_NOT_FOUND", 96, "Key not found in Kudu table '$0'."),
+ ("KUDU_NOT_FOUND", 96, "Not found in Kudu table '$0': $1"),
("KUDU_SESSION_ERROR", 97, "Error in Kudu table '$0': $1"),
@@ -303,6 +303,9 @@ error_codes = (
("AVRO_INVALID_DECIMAL", 99,
"Column '$0': invalid Avro decimal type with precision = '$1' scale = '$2'"),
+
+ ("KUDU_NULL_CONSTRAINT_VIOLATION", 100,
+ "Row with null value violates nullability constraint on table '$0'."),
)
import sys
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/cfac09de/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test b/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
index 761db13..1ecfdf5 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/kudu_crud.test
@@ -31,14 +31,16 @@ insert into tdata values
---- RESULTS
: 3
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 3.*
+NumModifiedRows: 3
+NumRowErrors: 0
====
---- QUERY
update tdata set vali=43 where id = 1
---- RESULTS
# TODO: Verify row count after fixing IMPALA-3713 (Here and UPDATE/DELETE below)
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -56,7 +58,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
update tdata set valv=cast('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' as varchar(20)) where id = 1
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -71,7 +74,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
update tdata set valb=false where id = 1
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -86,7 +90,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
update tdata set vali=43 where id > 1
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 2.*
+NumModifiedRows: 2
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -101,7 +106,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
update tdata set name='unknown' where name = 'martin'
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -119,7 +125,8 @@ insert into tdata values
---- RESULTS
: 2
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 2.*
+NumModifiedRows: 2
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -136,7 +143,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
update tdata set name=null where id = 40
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -152,7 +160,8 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
---- QUERY
update tdata set name='he' where id = 40
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
---- RESULTS
====
---- QUERY
@@ -173,7 +182,8 @@ insert into tdata values (320, '', 2.0, 932, cast('' as string), false)
---- RESULTS
: 1
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select id, name, valv, valb from tdata where id = 320;
@@ -194,7 +204,8 @@ insert into ignore_column_case values (1, 'Martin', 1.0, 10);
---- RESULTS
: 1
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
select ID, nAmE, VALF, VALI from ignore_column_case where NaMe = 'Martin';
@@ -209,7 +220,8 @@ insert into tdata values
---- RESULTS
: 1
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 0
====
---- QUERY
insert into tdata values
@@ -217,28 +229,23 @@ insert into tdata values
---- RESULTS
: 0
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 0.*
+NumModifiedRows: 0
+NumRowErrors: 1
====
---- QUERY
-- Updating the same record many times: cross join produces 7 identical updates
update a set a.name='Satan' from tdata a, tdata b where a.id = 666
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 7.*
-====
----- QUERY
--- Does not exercise any error path in the sink because updating the same record multiple
--- times is valid.
-update a set a.name='Satan' from tdata a, tdata b where a.id = 666
----- RESULTS
----- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 7.*
+NumModifiedRows: 7
+NumRowErrors: 0
====
---- QUERY
delete a from tdata a, tdata b where a.id = 666
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 1.*
+NumModifiedRows: 1
+NumRowErrors: 6
====
---- QUERY
select * from tdata
@@ -256,6 +263,9 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
upsert into table tdata values (40, 'they', 1, 43, cast('e' as VARCHAR(20)), false),
(1, NULL, 1, 0, cast('a' as VARCHAR(20)), true)
---- RESULTS
+---- RUNTIME_PROFILE
+NumModifiedRows: 2
+NumRowErrors: 0
====
---- QUERY
select * from tdata
@@ -306,8 +316,9 @@ INT,STRING,FLOAT,BIGINT,STRING,BOOLEAN
====
---- QUERY
upsert into table tdata (id, name) values (null, '')
----- CATCH
-Could not add Kudu WriteOp.: Invalid argument: column not nullable: id[int32 NOT NULL]
+---- RUNTIME_PROFILE
+NumModifiedRows: 0
+NumRowErrors: 1
====
---- QUERY
# IMPALA-3454: A delete that requires a rewrite may not get the Kudu column order correct
@@ -328,7 +339,8 @@ insert into impala_3454 values
delete from impala_3454 where key_1 < (select max(key_2) from impala_3454)
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 2.*
+NumModifiedRows: 2
+NumRowErrors: 0
====
---- QUERY
select * from impala_3454
@@ -345,7 +357,8 @@ SELECT * FROM functional_kudu.alltypes WHERE id < 100;
---- RESULTS
'Inserted 100 row(s)'
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 100.*
+NumModifiedRows: 100
+NumRowErrors: 0
====
---- QUERY
INSERT INTO kudu_test_tbl
@@ -353,7 +366,8 @@ SELECT * FROM functional_kudu.alltypes WHERE id < 100;
---- RESULTS
: 0
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 0.*
+NumModifiedRows: 0
+NumRowErrors: 100
====
---- QUERY
INSERT INTO kudu_test_tbl
@@ -361,42 +375,53 @@ SELECT * FROM functional_kudu.alltypes;
---- RESULTS
: 7200
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 7200.*
+NumModifiedRows: 7200
+NumRowErrors: 100
====
---- QUERY
# Test a larger UPDATE
UPDATE kudu_test_tbl SET int_col = -1;
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 7300.*
+NumModifiedRows: 7300
+NumRowErrors: 0
====
---- QUERY
# Test a larger DELETE
DELETE FROM kudu_test_tbl WHERE id > -1;
---- RESULTS
---- RUNTIME_PROFILE
-row_regex: .*NumModifiedRows: 7300.*
+NumModifiedRows: 7300
+NumRowErrors: 0
====
---- QUERY
# Insert rows that are not covered by any of the existing range partitions
+# Only the row at 10000 is inserted.
INSERT INTO kudu_test_tbl SELECT cast(id + 10000 as int), bool_col, tinyint_col,
smallint_col, int_col, bigint_col, float_col, double_col, date_string_col, string_col,
timestamp_col, year, month
FROM functional_kudu.alltypes
----- CATCH
-Kudu error(s) reported, first error: Not found: No tablet covering the requested range partition: NonCoveredRange { lower_bound: (int32 id=10001), upper_bound: (<end>)
+---- RUNTIME_PROFILE
+NumModifiedRows: 1
+NumRowErrors: 7299
====
---- QUERY
# Try to delete a row with a primary key value that is not covered by the existing range
-# partitions
+# partitions. This doesn't actually end up selecting any rows to modify.
DELETE FROM kudu_test_tbl WHERE id = 10001
---- RESULTS
+---- RUNTIME_PROFILE
+NumModifiedRows: 0
+NumRowErrors: 0
====
---- QUERY
# Try to update a row with a primary key value that is not covered by the existing range
-# partitions
+# partitions. This doesn't actually end up selecting any rows to modify.
UPDATE kudu_test_tbl SET int_col = 10 WHERE id = 10001
---- RESULTS
+---- RUNTIME_PROFILE
+NumModifiedRows: 0
+NumRowErrors: 0
====
---- QUERY
# IMPALA-2521: clustered insert into table.
@@ -414,6 +439,9 @@ from functional_kudu.alltypessmall group by id, name
) as sub;
---- RESULTS
: 10
+---- RUNTIME_PROFILE
+NumModifiedRows: 10
+NumRowErrors: 0
====
---- QUERY
select * from impala_2521
@@ -442,7 +470,10 @@ create table allkeytypes (i1 tinyint, i2 smallint, i3 int, i4 bigint, name strin
---- QUERY
insert into allkeytypes select cast(id as tinyint), smallint_col, int_col,
cast (bigint_col/10 as bigint), string_col, float_col, double_col
- from functional.alltypes where id > 0 and id < 4
+ from functional.alltypes where id > 0 and id < 10
---- RESULTS
: 3
+---- RUNTIME_PROFILE
+NumModifiedRows: 3
+NumRowErrors: 6
====
[24/50] [abbrv] incubator-impala git commit: IMPALA-4447: Rein in
overly broad sed that dirties the tree
Posted by ta...@apache.org.
IMPALA-4447: Rein in overly broad sed that dirties the tree
This patch fixes a sed expression to make sure it only laters the code
it is meant to alter, not the comment describing the code.
Tested with tests/run-tests.py query_test/test_udfs.py
Change-Id: I51a0498d24b7fccc05b6183123501766cb36f85e
Reviewed-on: http://gerrit.cloudera.org:8080/5008
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/67758938
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/67758938
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/67758938
Branch: refs/heads/hadoop-next
Commit: 67758938949496060c3cc7c7fb987e0b7c2c613f
Parents: 27e9f0a
Author: Jim Apple <jb...@cloudera.com>
Authored: Tue Nov 8 13:02:51 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 02:44:36 2016 +0000
----------------------------------------------------------------------
testdata/bin/copy-udfs-udas.sh | 8 ++++----
1 file changed, 4 insertions(+), 4 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/67758938/testdata/bin/copy-udfs-udas.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/copy-udfs-udas.sh b/testdata/bin/copy-udfs-udas.sh
index 57c0bc7..5e5b804 100755
--- a/testdata/bin/copy-udfs-udas.sh
+++ b/testdata/bin/copy-udfs-udas.sh
@@ -53,13 +53,13 @@ then
cd "${IMPALA_HOME}/tests/test-hive-udfs"
"${IMPALA_HOME}/bin/mvn-quiet.sh" package
cp target/test-hive-udfs-1.0.jar "${IMPALA_HOME}/testdata/udfs/impala-hive-udfs.jar"
- # Change one of the Java files to make a new jar for testing
- # purposes, then change it back
+ # Change one of the Java files to make a new jar for testing purposes, then change it
+ # back
find . -type f -name 'TestUpdateUdf.java' -execdir \
- bash -c "sed -i s/'Old UDF'/'New UDF'/g '{}'" \;
+ bash -c "sed -i s/'Text(\"Old UDF\")'/'Text(\"New UDF\")'/g '{}'" \;
"${IMPALA_HOME}/bin/mvn-quiet.sh" package
find . -type f -name 'TestUpdateUdf.java' -execdir \
- bash -c "sed -i s/'New UDF'/'Old UDF'/g '{}'" \;
+ bash -c "sed -i s/'Text(\"New UDF\")'/'Text(\"Old UDF\")'/g '{}'" \;
popd
fi
[15/50] [abbrv] incubator-impala git commit: IMPALA-4266: Java udf
returning string can give incorrect results
Posted by ta...@apache.org.
IMPALA-4266: Java udf returning string can give incorrect results
The memory management of string results was wrong: strings returned from
Exprs must live until the next time FreeLocalAllocations() is called.
Otherwise the buffer holding the string is freed or reused by the next
UDF call. The fix is to copy string values into a buffer with the
right lifetime.
Testing:
Added a regression test based on Bharath's example that reproduced the
bug reliably.
Change-Id: I705d271814cb1143f67d8a12f4fd87bab7a8e161
Reviewed-on: http://gerrit.cloudera.org:8080/4941
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/381e7190
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/381e7190
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/381e7190
Branch: refs/heads/hadoop-next
Commit: 381e719065e9699fc2757295241594d548db6e1d
Parents: 10fa472
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Thu Nov 3 17:36:42 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 02:47:11 2016 +0000
----------------------------------------------------------------------
be/src/exprs/hive-udf-call.cc | 11 ++++++-
.../queries/QueryTest/java-udf.test | 23 +++++++++++++++
.../queries/QueryTest/load-java-udfs.test | 6 ++++
.../org/apache/impala/ReplaceStringUdf.java | 31 ++++++++++++++++++++
4 files changed, 70 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/381e7190/be/src/exprs/hive-udf-call.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/hive-udf-call.cc b/be/src/exprs/hive-udf-call.cc
index 7d82431..cd27dab 100644
--- a/be/src/exprs/hive-udf-call.cc
+++ b/be/src/exprs/hive-udf-call.cc
@@ -322,7 +322,16 @@ DoubleVal HiveUdfCall::GetDoubleVal(ExprContext* ctx, const TupleRow* row) {
StringVal HiveUdfCall::GetStringVal(ExprContext* ctx, const TupleRow* row) {
DCHECK_EQ(type_.type, TYPE_STRING);
- return *reinterpret_cast<StringVal*>(Evaluate(ctx, row));
+ StringVal result = *reinterpret_cast<StringVal*>(Evaluate(ctx, row));
+
+ // Copy the string into a local allocation with the usual lifetime for expr results.
+ // Needed because the UDF output buffer is owned by the Java UDF executor and may be
+ // freed or reused by the next call into the Java UDF executor.
+ FunctionContext* fn_ctx = ctx->fn_context(fn_context_index_);
+ uint8_t* local_alloc = fn_ctx->impl()->AllocateLocal(result.len);
+ memcpy(local_alloc, result.ptr, result.len);
+ result.ptr = local_alloc;
+ return result;
}
TimestampVal HiveUdfCall::GetTimestampVal(ExprContext* ctx, const TupleRow* row) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/381e7190/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/java-udf.test b/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
index 1002e29..c473fdf 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/java-udf.test
@@ -290,3 +290,26 @@ INT
999
999
====
+---- QUERY
+drop table if exists replace_string_input
+====
+---- QUERY
+create table replace_string_input as
+values('toast'), ('scone'), ('stuff'), ('sssss'), ('yes'), ('scone'), ('stuff');
+====
+---- QUERY
+# Regression test for IMPALA-4266: memory management bugs with output strings from
+# Java UDFS, exposed by using the UDF as a grouping key in an aggregation.
+# The UDF replaces "s" with "ss" in the strings.
+select distinct udf_test.replace_string(_c0) as es
+from replace_string_input
+order by 1;
+---- TYPES
+string
+---- RESULTS
+'sscone'
+'ssssssssss'
+'sstuff'
+'toasst'
+'yess'
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/381e7190/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test b/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
index 3f86a9e..ab0c8bb 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/load-java-udfs.test
@@ -29,6 +29,8 @@ drop function if exists udf_test.throws_exception();
drop function if exists java_udfs_test.identity;
+drop function if exists udf_test.replace_string(string);
+
create function udf_test.hive_pi() returns double
location '$FILESYSTEM_PREFIX/test-warehouse/hive-exec.jar'
symbol='org.apache.hadoop.hive.ql.udf.UDFPI';
@@ -121,4 +123,8 @@ symbol='org.apache.impala.TestUdf';
create function udf_test.throws_exception() returns boolean
location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
symbol='org.apache.impala.TestUdfException';
+
+create function udf_test.replace_string(string) returns string
+location '$FILESYSTEM_PREFIX/test-warehouse/impala-hive-udfs.jar'
+symbol='org.apache.impala.ReplaceStringUdf';
====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/381e7190/tests/test-hive-udfs/src/main/java/org/apache/impala/ReplaceStringUdf.java
----------------------------------------------------------------------
diff --git a/tests/test-hive-udfs/src/main/java/org/apache/impala/ReplaceStringUdf.java b/tests/test-hive-udfs/src/main/java/org/apache/impala/ReplaceStringUdf.java
new file mode 100644
index 0000000..c33d846
--- /dev/null
+++ b/tests/test-hive-udfs/src/main/java/org/apache/impala/ReplaceStringUdf.java
@@ -0,0 +1,31 @@
+// 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;
+
+import java.text.ParseException;
+import org.apache.hadoop.hive.ql.exec.UDF;
+import org.apache.hadoop.io.Text;
+
+public class ReplaceStringUdf extends UDF {
+ public Text evaluate(Text para) throws ParseException {
+ if ((null == para) || ("".equals(para.toString()))) {
+ return new Text("");
+ }
+ return new Text(para.toString().replace("s", "ss"));
+ }
+}
[23/50] [abbrv] incubator-impala git commit: IMPALA-4446: expr-test
fails under ASAN
Posted by ta...@apache.org.
IMPALA-4446: expr-test fails under ASAN
Various places in the LikePredicate code assumed StringVal is
null-terminated. There is no such guarantee. By coincidence string
literals were sometimes backed by std::string storage that was
null-terminated, so this bug was latent until recently.
Testing:
Was able to reproduce the failure locally under ASAN, now the test
passes. Running the full ASAN tests to verify, but putting this up
for review first to unbreak the build sooner.
Change-Id: I0ac10d34dd6463ab52e41de1002ef065cfe63a20
Reviewed-on: http://gerrit.cloudera.org:8080/5000
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/27e9f0ae
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/27e9f0ae
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/27e9f0ae
Branch: refs/heads/hadoop-next
Commit: 27e9f0aea1c898b2892b8129c042114d2e67bd6f
Parents: f3d23be
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Tue Nov 8 10:44:38 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 02:03:24 2016 +0000
----------------------------------------------------------------------
be/src/exprs/like-predicate.cc | 30 +++++++++++++++---------------
1 file changed, 15 insertions(+), 15 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/27e9f0ae/be/src/exprs/like-predicate.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/like-predicate.cc b/be/src/exprs/like-predicate.cc
index 2e56370..18e0f9a 100644
--- a/be/src/exprs/like-predicate.cc
+++ b/be/src/exprs/like-predicate.cc
@@ -101,8 +101,7 @@ void LikePredicate::LikePrepareInternal(FunctionContext* context,
opts.set_case_sensitive(case_sensitive);
state->regex_.reset(new RE2(re_pattern, opts));
if (!state->regex_->ok()) {
- context->SetError(
- strings::Substitute("Invalid regex: $0", pattern_val.ptr).c_str());
+ context->SetError(Substitute("Invalid regex: $0", pattern_str).c_str());
}
}
}
@@ -164,9 +163,8 @@ void LikePredicate::RegexPrepareInternal(FunctionContext* context,
opts.set_case_sensitive(case_sensitive);
state->regex_.reset(new RE2(pattern_str, opts));
if (!state->regex_->ok()) {
- stringstream error;
- error << "Invalid regex expression" << pattern->ptr;
- context->SetError(error.str().c_str());
+ context->SetError(
+ Substitute("Invalid regex expression: '$0'", pattern_str).c_str());
}
state->function_ = ConstantRegexFnPartial;
}
@@ -202,8 +200,8 @@ void LikePredicate::RegexpLikePrepare(FunctionContext* context,
string pattern_str(reinterpret_cast<const char*>(pattern->ptr), pattern->len);
state->regex_.reset(new RE2(pattern_str, opts));
if (!state->regex_->ok()) {
- error << "Invalid regex expression" << pattern->ptr;
- context->SetError(error.str().c_str());
+ context->SetError(
+ Substitute("Invalid regex expression: '$0'", pattern_str).c_str());
}
}
}
@@ -226,11 +224,10 @@ BooleanVal LikePredicate::RegexpLikeInternal(FunctionContext* context,
string re_pattern(reinterpret_cast<const char*>(pattern.ptr), pattern.len);
re2::RE2 re(re_pattern, opts);
if (re.ok()) {
- return RE2::PartialMatch(re2::StringPiece(
- reinterpret_cast<const char*>(val.ptr), val.len), re);
+ return RE2::PartialMatch(
+ re2::StringPiece(reinterpret_cast<const char*>(val.ptr), val.len), re);
} else {
- context->SetError(
- strings::Substitute("Invalid regex: $0", pattern.ptr).c_str());
+ context->SetError(Substitute("Invalid regex: $0", re_pattern).c_str());
return BooleanVal(false);
}
}
@@ -353,12 +350,15 @@ BooleanVal LikePredicate::RegexMatch(FunctionContext* context,
return RE2::FullMatch(re2::StringPiece(
reinterpret_cast<const char*>(operand_value.ptr), operand_value.len), re);
} else {
- return RE2::PartialMatch(re2::StringPiece(
- reinterpret_cast<const char*>(operand_value.ptr), operand_value.len), re);
+ return RE2::PartialMatch(
+ re2::StringPiece(
+ reinterpret_cast<const char*>(operand_value.ptr), operand_value.len),
+ re);
}
} else {
- context->SetError(
- strings::Substitute("Invalid regex: $0", pattern_value.ptr).c_str());
+ string pattern_str(
+ reinterpret_cast<const char*>(pattern_value.ptr), pattern_value.len);
+ context->SetError(Substitute("Invalid regex: $0", pattern_str).c_str());
return BooleanVal(false);
}
}
[08/50] [abbrv] incubator-impala git commit: IMPALA-4260: Alter table
add column drops all the column stats
Posted by ta...@apache.org.
IMPALA-4260: Alter table add column drops all the column stats
Hive expects types for column stats to be specified as all lower
case. For some reason, it doesn't check this when the stats are
first written, but it does check when performing an 'alter table'.
This causes it to drop stats that Impala wrote because we specify
type names in upper case.
This patch converts the types that Impala sends to Hive for the
column stats to all lower case and adds a regression test.
I also filed HIVE-15061 to track the issue from the Hive end.
Change-Id: Ia373ec917efa7ab9f2a59b8a870b7ebc30175dda
Reviewed-on: http://gerrit.cloudera.org:8080/4845
Reviewed-by: Matthew Jacobs <mj...@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/5cc13394
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/5cc13394
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/5cc13394
Branch: refs/heads/hadoop-next
Commit: 5cc133947fe26a9ae39b0e7afb4678d251206b6b
Parents: c62d824
Author: Thomas Tauber-Marshall <tm...@cloudera.com>
Authored: Mon Oct 24 15:37:22 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 7 22:29:19 2016 +0000
----------------------------------------------------------------------
.../impala/service/CatalogOpExecutor.java | 2 +-
.../queries/QueryTest/compute-stats.test | 82 ++++++++++++++++++++
2 files changed, 83 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5cc13394/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
index ce5a1b2..884c43a 100644
--- a/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
+++ b/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
@@ -722,7 +722,7 @@ public class CatalogOpExecutor {
entry.getValue().getNum_nulls(), entry.getValue().getMax_size(),
entry.getValue().getAvg_size()));
ColumnStatisticsObj colStatsObj = new ColumnStatisticsObj(colName,
- tableCol.getType().toString(), colStatsData);
+ tableCol.getType().toString().toLowerCase(), colStatsData);
colStats.addToStatsObj(colStatsObj);
}
return colStats;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/5cc13394/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test b/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
index dd3fec8..a5ddb90 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
@@ -67,6 +67,88 @@ COLUMN, TYPE, #DISTINCT VALUES, #NULLS, MAX SIZE, AVG SIZE
STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
====
---- QUERY
+# Adding a column shouldn't cause the stats to be dropped.
+alter table alltypes add columns (new_col int)
+---- RESULTS
+====
+---- QUERY
+show column stats alltypes
+---- LABELS
+COLUMN, TYPE, #DISTINCT VALUES, #NULLS, MAX SIZE, AVG SIZE
+---- RESULTS
+'id','INT',7505,-1,4,4
+'bool_col','BOOLEAN',2,-1,1,1
+'tinyint_col','TINYINT',10,-1,1,1
+'smallint_col','SMALLINT',10,-1,2,2
+'int_col','INT',10,-1,4,4
+'bigint_col','BIGINT',10,-1,8,8
+'float_col','FLOAT',10,-1,4,4
+'double_col','DOUBLE',10,-1,8,8
+'date_string_col','STRING',736,-1,8,8
+'string_col','STRING',10,-1,1,1
+'timestamp_col','TIMESTAMP',7554,-1,16,16
+'year','INT',2,0,4,4
+'month','INT',12,0,4,4
+'new_col','INT',-1,-1,4,4
+---- TYPES
+STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
+====
+---- QUERY
+# Changing a column shouldn't cause the stats of other columns to be dropped.
+# Check that the column's own stats aren't dropped if the type matches once
+# HIVE-15075 is resolved.
+alter table alltypes change new_col new_col2 int
+---- RESULTS
+====
+---- QUERY
+show column stats alltypes
+---- LABELS
+COLUMN, TYPE, #DISTINCT VALUES, #NULLS, MAX SIZE, AVG SIZE
+---- RESULTS
+'id','INT',7505,-1,4,4
+'bool_col','BOOLEAN',2,-1,1,1
+'tinyint_col','TINYINT',10,-1,1,1
+'smallint_col','SMALLINT',10,-1,2,2
+'int_col','INT',10,-1,4,4
+'bigint_col','BIGINT',10,-1,8,8
+'float_col','FLOAT',10,-1,4,4
+'double_col','DOUBLE',10,-1,8,8
+'date_string_col','STRING',736,-1,8,8
+'string_col','STRING',10,-1,1,1
+'timestamp_col','TIMESTAMP',7554,-1,16,16
+'year','INT',2,0,4,4
+'month','INT',12,0,4,4
+'new_col2','INT',-1,-1,4,4
+---- TYPES
+STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
+====
+---- QUERY
+# Removing a column shouldn't cause the stats to be dropped.
+alter table alltypes drop column new_col2
+---- RESULTS
+====
+---- QUERY
+show column stats alltypes
+---- LABELS
+COLUMN, TYPE, #DISTINCT VALUES, #NULLS, MAX SIZE, AVG SIZE
+---- RESULTS
+'id','INT',7505,-1,4,4
+'bool_col','BOOLEAN',2,-1,1,1
+'tinyint_col','TINYINT',10,-1,1,1
+'smallint_col','SMALLINT',10,-1,2,2
+'int_col','INT',10,-1,4,4
+'bigint_col','BIGINT',10,-1,8,8
+'float_col','FLOAT',10,-1,4,4
+'double_col','DOUBLE',10,-1,8,8
+'date_string_col','STRING',736,-1,8,8
+'string_col','STRING',10,-1,1,1
+'timestamp_col','TIMESTAMP',7554,-1,16,16
+'year','INT',2,0,4,4
+'month','INT',12,0,4,4
+---- TYPES
+STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
+====
+---- QUERY
# drop stats from this table
drop stats alltypes
====
[44/50] [abbrv] incubator-impala git commit: IMPALA-4434: In Python,
''.split('\n') is [''], which has length 1
Posted by ta...@apache.org.
IMPALA-4434: In Python, ''.split('\n') is [''], which has length 1
This test simply may have never been run in GMT or UTC - it appears to
have an easy-to-make off-by-one error.
Change-Id: Iac4943085b0693deb380499cd0e141eb672bead8
Reviewed-on: http://gerrit.cloudera.org:8080/5061
Reviewed-by: Jim Apple <jb...@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/b3cbc960
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/b3cbc960
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/b3cbc960
Branch: refs/heads/hadoop-next
Commit: b3cbc960a7e4beebf6cb9076a02b3513bb0b2954
Parents: 91b5264
Author: Jim Apple <jb...@cloudera.com>
Authored: Sat Nov 12 18:56:40 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 15:29:26 2016 +0000
----------------------------------------------------------------------
tests/custom_cluster/test_hive_parquet_timestamp_conversion.py | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/b3cbc960/tests/custom_cluster/test_hive_parquet_timestamp_conversion.py
----------------------------------------------------------------------
diff --git a/tests/custom_cluster/test_hive_parquet_timestamp_conversion.py b/tests/custom_cluster/test_hive_parquet_timestamp_conversion.py
index 6573500..731c766 100644
--- a/tests/custom_cluster/test_hive_parquet_timestamp_conversion.py
+++ b/tests/custom_cluster/test_hive_parquet_timestamp_conversion.py
@@ -93,8 +93,10 @@ class TestHiveParquetTimestampConversion(CustomClusterTestSuite):
WHERE h.timestamp_col != FROM_UTC_TIMESTAMP(i.timestamp_col, '%s')
""" % tz_name)\
.get_data()
- expected_row_count = 0 if tz_name in ("UTC", "GMT") else 10000
- assert len(data.split('\n')) == expected_row_count
+ if tz_name in ("UTC", "GMT"):
+ assert len(data) == 0
+ else:
+ assert len(data.split('\n')) == 10000
# A value should either stay null or stay not null.
data = self.execute_query_expect_success(self.client, """
SELECT h.id, h.day, h.timestamp_col, i.timestamp_col
[36/50] [abbrv] incubator-impala git commit: IMPALA-3552: Make
incremental stats max serialized size configurable
Posted by ta...@apache.org.
IMPALA-3552: Make incremental stats max serialized size configurable
The fix "IMPALA-2648/IMPALA-2664" introduced a conservative limitation
on the maximum serialized size of incremental stats. As a side effect,
some users with very large tables are experiencing regressions
especially when they upgrade impala and the serialized size goes
beyond 200MB.
To mitigate the issue, the change introduces a new gflag,
'inc_stats_size_limit_bytes' to make the max serialized size
configurable, which allows impala users to specify their own maximum
serialized size. Default value for inc_stats_size_limit_bytes is
200MB.
The change introduces a TBackendGflags class to pass the gflags from
backend to the Frontend and the Catalog via thrift. This also revamps
existing query options to use the TBackendConfig.
Change-Id: I33684725a61eabc67237503e61178305d37d3cb5
Reviewed-on: http://gerrit.cloudera.org:8080/4867
Reviewed-by: Bharath Vissapragada <bh...@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/3f2f008a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/3f2f008a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/3f2f008a
Branch: refs/heads/hadoop-next
Commit: 3f2f008ac4365d7f7c616730d3faeebd776b74d2
Parents: cac02d6
Author: Bharath Vissapragada <bh...@cloudera.com>
Authored: Fri Nov 4 16:36:39 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 03:22:11 2016 +0000
----------------------------------------------------------------------
be/generated-sources/gen-cpp/CMakeLists.txt | 2 +
be/src/catalog/catalog.cc | 28 ++------
be/src/common/global-flags.cc | 6 ++
be/src/service/fe-support.cc | 18 -----
be/src/service/frontend.cc | 38 +++-------
be/src/util/CMakeLists.txt | 1 +
be/src/util/backend-gflag-util.cc | 76 ++++++++++++++++++++
be/src/util/backend-gflag-util.h | 31 ++++++++
common/thrift/BackendGflags.thrift | 55 ++++++++++++++
common/thrift/CMakeLists.txt | 1 +
common/thrift/Frontend.thrift | 5 --
.../apache/impala/analysis/AlterViewStmt.java | 3 +-
.../impala/analysis/ComputeStatsStmt.java | 10 +--
.../apache/impala/analysis/CreateViewStmt.java | 3 +-
.../org/apache/impala/authorization/User.java | 26 ++-----
.../org/apache/impala/catalog/HdfsTable.java | 11 +--
.../org/apache/impala/catalog/KuduTable.java | 2 +-
.../org/apache/impala/common/RuntimeEnv.java | 12 ----
.../java/org/apache/impala/planner/Planner.java | 3 +-
.../apache/impala/service/BackendConfig.java | 70 ++++++++++--------
.../org/apache/impala/service/FeSupport.java | 18 -----
.../org/apache/impala/service/JniCatalog.java | 30 ++++----
.../org/apache/impala/service/JniFrontend.java | 26 +++----
.../java/org/apache/impala/util/KuduUtil.java | 4 +-
24 files changed, 280 insertions(+), 199 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/generated-sources/gen-cpp/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/be/generated-sources/gen-cpp/CMakeLists.txt b/be/generated-sources/gen-cpp/CMakeLists.txt
index 35f7d65..ea7735f 100644
--- a/be/generated-sources/gen-cpp/CMakeLists.txt
+++ b/be/generated-sources/gen-cpp/CMakeLists.txt
@@ -39,6 +39,8 @@ set(SRC_FILES
ImpalaHiveServer2Service.cpp
beeswax_constants.cpp
beeswax_types.cpp
+ BackendGflags_constants.cpp
+ BackendGflags_types.cpp
BeeswaxService.cpp
TCLIService.cpp
TCLIService_constants.cpp
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/catalog/catalog.cc
----------------------------------------------------------------------
diff --git a/be/src/catalog/catalog.cc b/be/src/catalog/catalog.cc
index 7d6fdca..b3690f6 100644
--- a/be/src/catalog/catalog.cc
+++ b/be/src/catalog/catalog.cc
@@ -22,15 +22,12 @@
#include "common/logging.h"
#include "rpc/jni-thrift-util.h"
-#include "util/logging-support.h"
+#include "util/backend-gflag-util.h"
#include "common/names.h"
using namespace impala;
-DECLARE_bool(load_auth_to_local_rules);
-DECLARE_string(principal);
-DECLARE_string(local_library_dir);
DEFINE_bool(load_catalog_in_background, false,
"If true, loads catalog metadata in the background. If false, metadata is loaded "
@@ -41,13 +38,9 @@ DEFINE_int32(num_metadata_loading_threads, 16,
DEFINE_string(sentry_config, "", "Local path to a sentry-site.xml configuration "
"file. If set, authorization will be enabled.");
-DECLARE_int32(non_impala_java_vlog);
-DECLARE_int32(kudu_operation_timeout_ms);
-
Catalog::Catalog() {
JniMethodDescriptor methods[] = {
- {"<init>", "(ZILjava/lang/String;IIZLjava/lang/String;Ljava/lang/String;I)V",
- &catalog_ctor_},
+ {"<init>", "([B)V", &catalog_ctor_},
{"updateCatalog", "([B)[B", &update_metastore_id_},
{"execDdl", "([B)[B", &exec_ddl_id_},
{"resetMetadata", "([B)[B", &reset_metadata_id_},
@@ -70,19 +63,10 @@ Catalog::Catalog() {
ABORT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, catalog_class_, &(methods[i])));
}
- jboolean load_in_background = FLAGS_load_catalog_in_background;
- jint num_metadata_loading_threads = FLAGS_num_metadata_loading_threads;
- jstring sentry_config = jni_env->NewStringUTF(FLAGS_sentry_config.c_str());
- // auth_to_local rules are read if --load_auth_to_local_rules is set to true
- // and impala is kerberized.
- jboolean auth_to_local = FLAGS_load_auth_to_local_rules && !FLAGS_principal.empty();
- jstring principal = jni_env->NewStringUTF(FLAGS_principal.c_str());
- jstring local_library_dir = jni_env->NewStringUTF(FLAGS_local_library_dir.c_str());
- jint kudu_operation_timeout = FLAGS_kudu_operation_timeout_ms;
- jobject catalog = jni_env->NewObject(catalog_class_, catalog_ctor_,
- load_in_background, num_metadata_loading_threads, sentry_config,
- FlagToTLogLevel(FLAGS_v), FlagToTLogLevel(FLAGS_non_impala_java_vlog),
- auth_to_local, principal, local_library_dir, kudu_operation_timeout);
+ jbyteArray cfg_bytes;
+ ABORT_IF_ERROR(GetThriftBackendGflags(jni_env, &cfg_bytes));
+
+ jobject catalog = jni_env->NewObject(catalog_class_, catalog_ctor_, cfg_bytes);
EXIT_IF_EXC(jni_env);
ABORT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, catalog, &catalog_));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/common/global-flags.cc
----------------------------------------------------------------------
diff --git a/be/src/common/global-flags.cc b/be/src/common/global-flags.cc
index f75236c..5a3eff4 100644
--- a/be/src/common/global-flags.cc
+++ b/be/src/common/global-flags.cc
@@ -123,3 +123,9 @@ DEFINE_bool(enable_accept_queue_server, true,
"TThreadedServer that accepts connections as quickly as possible and hands them off "
"to a thread pool to finish setup, reducing the chances that connections time out "
"waiting to be accepted.");
+
+DEFINE_int64(inc_stats_size_limit_bytes, 200 * (1LL<<20), "Maximum size of "
+ "incremental stats the catalog is allowed to serialize per table. "
+ "This limit is set as a safety check, to prevent the JVM from "
+ "hitting a maximum array limit of 1GB (or OOM) while building "
+ "the thrift objects to send to impalads. By default, it's set to 200MB");
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/service/fe-support.cc
----------------------------------------------------------------------
diff --git a/be/src/service/fe-support.cc b/be/src/service/fe-support.cc
index 42ceea2..7147964 100644
--- a/be/src/service/fe-support.cc
+++ b/be/src/service/fe-support.cc
@@ -336,20 +336,6 @@ Java_org_apache_impala_service_FeSupport_NativePrioritizeLoad(
return result_bytes;
}
-extern "C"
-JNIEXPORT jbyteArray JNICALL
-Java_org_apache_impala_service_FeSupport_NativeGetStartupOptions(JNIEnv* env,
- jclass caller_class) {
- TStartupOptions options;
- ExecEnv* exec_env = ExecEnv::GetInstance();
- ImpalaServer* impala_server = exec_env->impala_server();
- options.__set_compute_lineage(impala_server->IsLineageLoggingEnabled());
- jbyteArray result_bytes = NULL;
- THROW_IF_ERROR_RET(SerializeThriftMsg(env, &options, &result_bytes), env,
- JniUtil::internal_exc_class(), result_bytes);
- return result_bytes;
-}
-
namespace impala {
static JNINativeMethod native_methods[] = {
@@ -373,10 +359,6 @@ static JNINativeMethod native_methods[] = {
(char*)"NativePrioritizeLoad", (char*)"([B)[B",
(void*)::Java_org_apache_impala_service_FeSupport_NativePrioritizeLoad
},
- {
- (char*)"NativeGetStartupOptions", (char*)"()[B",
- (void*)::Java_org_apache_impala_service_FeSupport_NativeGetStartupOptions
- },
};
void InitFeSupport() {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/service/frontend.cc
----------------------------------------------------------------------
diff --git a/be/src/service/frontend.cc b/be/src/service/frontend.cc
index f8cecfb..b83d091 100644
--- a/be/src/service/frontend.cc
+++ b/be/src/service/frontend.cc
@@ -22,21 +22,13 @@
#include "common/logging.h"
#include "rpc/jni-thrift-util.h"
+#include "util/backend-gflag-util.h"
#include "util/jni-util.h"
-#include "util/logging-support.h"
#include "common/names.h"
using namespace impala;
-DECLARE_string(sentry_config);
-DECLARE_int32(non_impala_java_vlog);
-DECLARE_bool(load_auth_to_local_rules);
-DECLARE_string(principal);
-DECLARE_int32(kudu_operation_timeout_ms);
-
-DEFINE_bool(load_catalog_at_startup, false, "if true, load all catalog data at startup");
-
// Authorization related flags. Must be set to valid values to properly configure
// authorization.
DEFINE_string(server_name, "", "The name to use for securing this impalad "
@@ -62,10 +54,10 @@ DEFINE_string(authorized_proxy_user_config_delimiter, ",",
DEFINE_string(kudu_master_hosts, "", "Specifies the default Kudu master(s). The given "
"value should be a comma separated list of hostnames or IP addresses; ports are "
"optional.");
+
Frontend::Frontend() {
JniMethodDescriptor methods[] = {
- {"<init>", "(ZLjava/lang/String;Ljava/lang/String;Ljava/lang/String;"
- "Ljava/lang/String;IIZLjava/lang/String;I)V", &fe_ctor_},
+ {"<init>", "([B)V", &fe_ctor_},
{"createExecRequest", "([B)[B", &create_exec_request_id_},
{"getExplainPlan", "([B)Ljava/lang/String;", &get_explain_plan_id_},
{"getHadoopConfig", "([B)[B", &get_hadoop_config_id_},
@@ -89,7 +81,7 @@ Frontend::Frontend() {
{"loadTableData", "([B)[B", &load_table_data_id_},
{"getTableFiles", "([B)[B", &get_table_files_id_},
{"showCreateFunction", "([B)Ljava/lang/String;", &show_create_function_id_},
- {"buildTestDescriptorTable", "([B)[B", &build_test_descriptor_table_id_},
+ {"buildTestDescriptorTable", "([B)[B", &build_test_descriptor_table_id_}
};
JNIEnv* jni_env = getJNIEnv();
@@ -102,24 +94,10 @@ Frontend::Frontend() {
ABORT_IF_ERROR(JniUtil::LoadJniMethod(jni_env, fe_class_, &(methods[i])));
};
- jboolean lazy = (FLAGS_load_catalog_at_startup ? false : true);
- jstring policy_file_path =
- jni_env->NewStringUTF(FLAGS_authorization_policy_file.c_str());
- jstring server_name =
- jni_env->NewStringUTF(FLAGS_server_name.c_str());
- jstring sentry_config =
- jni_env->NewStringUTF(FLAGS_sentry_config.c_str());
- jstring auth_provider_class =
- jni_env->NewStringUTF(FLAGS_authorization_policy_provider_class.c_str());
- // auth_to_local rules are read if --load_auth_to_local_rules is set to true
- // and impala is kerberized.
- jboolean auth_to_local = FLAGS_load_auth_to_local_rules && !FLAGS_principal.empty();
- jstring kudu_master_hosts = jni_env->NewStringUTF(FLAGS_kudu_master_hosts.c_str());
- jint kudu_operation_timeout = FLAGS_kudu_operation_timeout_ms;
- jobject fe = jni_env->NewObject(fe_class_, fe_ctor_, lazy, server_name,
- policy_file_path, sentry_config, auth_provider_class, FlagToTLogLevel(FLAGS_v),
- FlagToTLogLevel(FLAGS_non_impala_java_vlog), auth_to_local, kudu_master_hosts,
- kudu_operation_timeout);
+ jbyteArray cfg_bytes;
+ ABORT_IF_ERROR(GetThriftBackendGflags(jni_env, &cfg_bytes));
+
+ jobject fe = jni_env->NewObject(fe_class_, fe_ctor_, cfg_bytes);
EXIT_IF_EXC(jni_env);
ABORT_IF_ERROR(JniUtil::LocalToGlobalRef(jni_env, fe, &fe_));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/util/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/be/src/util/CMakeLists.txt b/be/src/util/CMakeLists.txt
index ecc222a..6656a38 100644
--- a/be/src/util/CMakeLists.txt
+++ b/be/src/util/CMakeLists.txt
@@ -32,6 +32,7 @@ set(EXECUTABLE_OUTPUT_PATH "${BUILD_OUTPUT_ROOT_DIRECTORY}/util")
add_library(Util
auth-util.cc
avro-util.cc
+ backend-gflag-util.cc
benchmark.cc
bitmap.cc
bit-util.cc
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/util/backend-gflag-util.cc
----------------------------------------------------------------------
diff --git a/be/src/util/backend-gflag-util.cc b/be/src/util/backend-gflag-util.cc
new file mode 100644
index 0000000..f504e57
--- /dev/null
+++ b/be/src/util/backend-gflag-util.cc
@@ -0,0 +1,76 @@
+// 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.
+
+#include "util/backend-gflag-util.h"
+
+#include "gen-cpp/BackendGflags_types.h"
+#include "rpc/jni-thrift-util.h"
+#include "util/logging-support.h"
+
+#include <gflags/gflags.h>
+
+// Configs for the Frontend and the Catalog.
+DECLARE_bool(load_catalog_in_background);
+DECLARE_bool(load_auth_to_local_rules);
+DECLARE_int32(non_impala_java_vlog);
+DECLARE_int32(read_size);
+DECLARE_int32(num_metadata_loading_threads);
+DECLARE_int32(kudu_operation_timeout_ms);
+DECLARE_int64(inc_stats_size_limit_bytes);
+DECLARE_string(principal);
+DECLARE_string(lineage_event_log_dir);
+DECLARE_string(principal);
+DECLARE_string(local_library_dir);
+DECLARE_string(server_name);
+DECLARE_string(authorization_policy_file);
+DECLARE_string(authorization_policy_provider_class);
+DECLARE_string(authorized_proxy_user_config);
+DECLARE_string(authorized_proxy_user_config_delimiter);
+DECLARE_string(kudu_master_hosts);
+DECLARE_string(sentry_config);
+DECLARE_string(sentry_config);
+
+namespace impala {
+
+Status GetThriftBackendGflags(JNIEnv* jni_env, jbyteArray* cfg_bytes) {
+ TBackendGflags cfg;
+ cfg.__set_authorization_policy_file(FLAGS_authorization_policy_file);
+ cfg.__set_load_catalog_in_background(FLAGS_load_catalog_in_background);
+ cfg.__set_server_name(FLAGS_server_name);
+ cfg.__set_sentry_config(FLAGS_sentry_config);
+ cfg.__set_authorization_policy_provider_class(
+ FLAGS_authorization_policy_provider_class);
+ cfg.__set_kudu_master_hosts(FLAGS_kudu_master_hosts);
+ cfg.__set_read_size(FLAGS_read_size);
+ cfg.__set_num_metadata_loading_threads(FLAGS_num_metadata_loading_threads);
+ cfg.__set_sentry_config(FLAGS_sentry_config);
+ // auth_to_local rules are read if --load_auth_to_local_rules is set to true
+ // and impala is kerberized.
+ cfg.__set_load_auth_to_local_rules(FLAGS_load_auth_to_local_rules);
+ cfg.__set_principal(FLAGS_principal);
+ cfg.__set_impala_log_lvl(FlagToTLogLevel(FLAGS_v));
+ cfg.__set_non_impala_java_vlog(FlagToTLogLevel(FLAGS_non_impala_java_vlog));
+ cfg.__set_inc_stats_size_limit_bytes(FLAGS_inc_stats_size_limit_bytes);
+ cfg.__set_lineage_event_log_dir(FLAGS_lineage_event_log_dir);
+ cfg.__set_local_library_path(FLAGS_local_library_dir);
+ cfg.__set_kudu_operation_timeout_ms(FLAGS_kudu_operation_timeout_ms);
+ JniLocalFrame jni_frame;
+ RETURN_IF_ERROR(jni_frame.push(jni_env));
+ RETURN_IF_ERROR(SerializeThriftMsg(jni_env, &cfg, cfg_bytes));
+ return Status::OK();
+}
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/be/src/util/backend-gflag-util.h
----------------------------------------------------------------------
diff --git a/be/src/util/backend-gflag-util.h b/be/src/util/backend-gflag-util.h
new file mode 100644
index 0000000..796a2d5
--- /dev/null
+++ b/be/src/util/backend-gflag-util.h
@@ -0,0 +1,31 @@
+// 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.
+
+#ifndef UTIL_BACKEND_CONFIG_H_
+#define UTIL_BACKEND_CONFIG_H_
+
+#include "common/status.h"
+#include "util/jni-util.h"
+
+namespace impala {
+
+/// Builds the TBackendGflags object to pass to JNI. This is used to pass the gflag
+/// configs to the Frontend and the Catalog.
+Status GetThriftBackendGflags(JNIEnv* jni_env, jbyteArray* cfg_bytes);
+}
+
+#endif
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/common/thrift/BackendGflags.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/BackendGflags.thrift b/common/thrift/BackendGflags.thrift
new file mode 100644
index 0000000..ad081a6
--- /dev/null
+++ b/common/thrift/BackendGflags.thrift
@@ -0,0 +1,55 @@
+// 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.
+
+namespace cpp impala
+namespace java org.apache.impala.thrift
+
+// Used to pass gflags from backend to frontend, JniCatalog and JniFrontend
+// Attributes without comments correspond to gflags
+struct TBackendGflags {
+ 1: required string sentry_config
+
+ 2: required bool load_auth_to_local_rules
+
+ 3: required i32 non_impala_java_vlog
+
+ 4: required i32 impala_log_lvl
+
+ 5: required i64 inc_stats_size_limit_bytes
+
+ 6: required string lineage_event_log_dir
+
+ 7: required bool load_catalog_in_background
+
+ 8: required i32 num_metadata_loading_threads
+
+ 9: required string principal
+
+ 10: required string authorization_policy_file
+
+ 11: required string server_name
+
+ 12: required string authorization_policy_provider_class
+
+ 13: required string kudu_master_hosts
+
+ 14: required string local_library_path
+
+ 15: required i32 read_size
+
+ 16: required i32 kudu_operation_timeout_ms
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/common/thrift/CMakeLists.txt
----------------------------------------------------------------------
diff --git a/common/thrift/CMakeLists.txt b/common/thrift/CMakeLists.txt
index 10d363d..1512e52 100644
--- a/common/thrift/CMakeLists.txt
+++ b/common/thrift/CMakeLists.txt
@@ -144,6 +144,7 @@ set (EXT_DATA_SRC_FILES
set (SRC_FILES
ErrorCodes.thrift
beeswax.thrift
+ BackendGflags.thrift
CatalogInternalService.thrift
CatalogObjects.thrift
CatalogService.thrift
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/common/thrift/Frontend.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/Frontend.thrift b/common/thrift/Frontend.thrift
index f6ba35a..8c279f5 100644
--- a/common/thrift/Frontend.thrift
+++ b/common/thrift/Frontend.thrift
@@ -721,11 +721,6 @@ struct TGetAllHadoopConfigsResponse {
1: optional map<string, string> configs;
}
-// BE startup options
-struct TStartupOptions {
- 1: optional bool compute_lineage
-}
-
// For creating a test descriptor table. The tuples and their memory layout are computed
// in the FE.
struct TBuildTestDescriptorTableParams {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/analysis/AlterViewStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterViewStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterViewStmt.java
index e7d3f66..6740f14 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterViewStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterViewStmt.java
@@ -22,6 +22,7 @@ import org.apache.impala.catalog.Table;
import org.apache.impala.catalog.View;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.RuntimeEnv;
+import org.apache.impala.service.BackendConfig;
import com.google.common.base.Preconditions;
@@ -52,7 +53,7 @@ public class AlterViewStmt extends CreateOrAlterViewStmtBase {
}
createColumnAndViewDefs(analyzer);
- if (RuntimeEnv.INSTANCE.computeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
+ if (BackendConfig.INSTANCE.getComputeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
computeLineageGraph(analyzer);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java b/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
index 467faca..5ad3cad 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
@@ -33,6 +33,7 @@ import org.apache.impala.catalog.Type;
import org.apache.impala.catalog.View;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.PrintUtils;
+import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TComputeStatsParams;
import org.apache.impala.thrift.TPartitionStats;
import org.apache.impala.thrift.TTableName;
@@ -284,16 +285,17 @@ public class ComputeStatsStmt extends StatementBase {
}
}
// For incremental stats, estimate the size of intermediate stats and report an
- // error if the estimate is greater than MAX_INCREMENTAL_STATS_SIZE_BYTES.
+ // error if the estimate is greater than --inc_stats_size_limit_bytes in bytes
if (isIncremental_) {
+ long incStatMaxSize = BackendConfig.INSTANCE.getIncStatsMaxSize();
long statsSizeEstimate = hdfsTable.getColumns().size() *
hdfsTable.getPartitions().size() * HdfsTable.STATS_SIZE_PER_COLUMN_BYTES;
- if (statsSizeEstimate > HdfsTable.MAX_INCREMENTAL_STATS_SIZE_BYTES) {
+ if (statsSizeEstimate > incStatMaxSize) {
LOG.error("Incremental stats size estimate for table " + hdfsTable.getName() +
- " exceeded " + HdfsTable.MAX_INCREMENTAL_STATS_SIZE_BYTES + ", estimate = "
+ " exceeded " + incStatMaxSize + ", estimate = "
+ statsSizeEstimate);
throw new AnalysisException("Incremental stats size estimate exceeds "
- + PrintUtils.printBytes(HdfsTable.MAX_INCREMENTAL_STATS_SIZE_BYTES)
+ + PrintUtils.printBytes(incStatMaxSize)
+ ". Please try COMPUTE STATS instead.");
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/analysis/CreateViewStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/CreateViewStmt.java b/fe/src/main/java/org/apache/impala/analysis/CreateViewStmt.java
index 6e30aeb..6b90083 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CreateViewStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CreateViewStmt.java
@@ -24,6 +24,7 @@ import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.RuntimeEnv;
import org.apache.impala.thrift.TAccessEvent;
import org.apache.impala.thrift.TCatalogObjectType;
+import org.apache.impala.service.BackendConfig;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
@@ -60,7 +61,7 @@ public class CreateViewStmt extends CreateOrAlterViewStmtBase {
TCatalogObjectType.VIEW, Privilege.CREATE.toString()));
createColumnAndViewDefs(analyzer);
- if (RuntimeEnv.INSTANCE.computeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
+ if (BackendConfig.INSTANCE.getComputeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
computeLineageGraph(analyzer);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/authorization/User.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/authorization/User.java b/fe/src/main/java/org/apache/impala/authorization/User.java
index 190419b..e29b19f 100644
--- a/fe/src/main/java/org/apache/impala/authorization/User.java
+++ b/fe/src/main/java/org/apache/impala/authorization/User.java
@@ -19,42 +19,24 @@ package org.apache.impala.authorization;
import com.google.common.base.Preconditions;
import com.google.common.annotations.VisibleForTesting;
+
+import org.apache.hadoop.security.authentication.util.KerberosName;
import org.apache.impala.common.InternalException;
import org.apache.impala.common.RuntimeEnv;
import org.apache.impala.service.BackendConfig;
import java.io.IOException;
-import org.apache.hadoop.conf.Configuration;
-import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTH_TO_LOCAL;
-import org.apache.hadoop.security.authentication.util.KerberosName;
/*
* Class that represents a User of an Impala session.
*/
public class User {
- static {
- // If auth_to_local is enabled, we read the configuration hadoop.security.auth_to_local
- // from core-site.xml and use it for principal to short name conversion. If it is not,
- // we use the defaultRule ("RULE:[1:$1] RULE:[2:$1]"), which just extracts the user
- // name from any principal of form a@REALM or a/b@REALM. If auth_to_local is enabled
- // and hadoop.security.auth_to_local is not specified in the hadoop configs, we use
- // the "DEFAULT" rule that just extracts the username from any principal in the
- // cluster's local realm. For more details on principal to short name translation,
- // refer to org.apache.hadoop.security.KerberosName.
- final String defaultRule = "RULE:[1:$1] RULE:[2:$1]";
- final Configuration conf = new Configuration();
- if (BackendConfig.isAuthToLocalEnabled()) {
- KerberosName.setRules(conf.get(HADOOP_SECURITY_AUTH_TO_LOCAL, "DEFAULT"));
- } else {
- // just extract the simple user name
- KerberosName.setRules(defaultRule);
- }
- }
-
private final String name_;
+ // Refer to BackendConfig.initAuthToLocal() for initialization
+ // of static auth_to_local configs in KerberosName class.
private KerberosName kerberosName_;
public User(String name) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
index 97831d7..69b4b4e 100644
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
@@ -63,6 +63,7 @@ import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.FileSystemUtil;
import org.apache.impala.common.Pair;
import org.apache.impala.common.PrintUtils;
+import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.ImpalaInternalServiceConstants;
import org.apache.impala.thrift.TAccessLevel;
import org.apache.impala.thrift.TCatalogObjectType;
@@ -169,12 +170,6 @@ public class HdfsTable extends Table {
// Store all the partition ids of an HdfsTable.
private HashSet<Long> partitionIds_ = Sets.newHashSet();
- // Maximum size (in bytes) of incremental stats the catalog is allowed to serialize per
- // table. This limit is set as a safety check, to prevent the JVM from hitting a
- // maximum array limit of 1GB (or OOM) while building the thrift objects to send to
- // impalads.
- public static final long MAX_INCREMENTAL_STATS_SIZE_BYTES = 200 * 1024 * 1024;
-
// Estimate (in bytes) of the incremental stats size per column per partition
public static final long STATS_SIZE_PER_COLUMN_BYTES = 400;
@@ -1593,7 +1588,7 @@ public class HdfsTable extends Table {
* partitions). To prevent the catalog from hitting an OOM error while trying to
* serialize large partition incremental stats, we estimate the stats size and filter
* the incremental stats data from partition objects if the estimate exceeds
- * MAX_INCREMENTAL_STATS_SIZE_BYTES.
+ * --inc_stats_size_limit_bytes
*/
private THdfsTable getTHdfsTable(boolean includeFileDesc, Set<Long> refPartitions) {
// includeFileDesc implies all partitions should be included (refPartitions == null).
@@ -1603,7 +1598,7 @@ public class HdfsTable extends Table {
long statsSizeEstimate =
numPartitions * getColumns().size() * STATS_SIZE_PER_COLUMN_BYTES;
boolean includeIncrementalStats =
- (statsSizeEstimate < MAX_INCREMENTAL_STATS_SIZE_BYTES);
+ (statsSizeEstimate < BackendConfig.INSTANCE.getIncStatsMaxSize());
Map<Long, THdfsPartition> idToPartition = Maps.newHashMap();
for (HdfsPartition partition: partitionMap_.values()) {
long id = partition.getId();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/catalog/KuduTable.java b/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
index 6c30077..7b906a7 100644
--- a/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/KuduTable.java
@@ -340,7 +340,7 @@ public class KuduTable extends Table {
try (KuduClient client = KuduUtil.createKuduClient(getKuduMasterHosts())) {
org.apache.kudu.client.KuduTable kuduTable = client.openTable(kuduTableName_);
List<LocatedTablet> tablets =
- kuduTable.getTabletsLocations(BackendConfig.getKuduClientTimeoutMs());
+ kuduTable.getTabletsLocations(BackendConfig.INSTANCE.getKuduClientTimeoutMs());
for (LocatedTablet tab: tablets) {
TResultRowBuilder builder = new TResultRowBuilder();
builder.add("-1"); // The Kudu client API doesn't expose tablet row counts.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/common/RuntimeEnv.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/common/RuntimeEnv.java b/fe/src/main/java/org/apache/impala/common/RuntimeEnv.java
index af58b16..d33455a 100644
--- a/fe/src/main/java/org/apache/impala/common/RuntimeEnv.java
+++ b/fe/src/main/java/org/apache/impala/common/RuntimeEnv.java
@@ -21,7 +21,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.impala.service.FeSupport;
-import org.apache.impala.thrift.TStartupOptions;
/**
* Contains runtime-specific parameters such as the number of CPU cores. Currently only
@@ -35,21 +34,11 @@ public class RuntimeEnv {
private int numCores_;
- // Indicates if column lineage information should be computed for each query.
- private boolean computeLineage_;
-
// Indicates whether this is an environment for testing.
private boolean isTestEnv_;
public RuntimeEnv() {
reset();
- try {
- TStartupOptions opts = FeSupport.GetStartupOptions();
- computeLineage_ = opts.compute_lineage;
- } catch (InternalException e) {
- LOG.error("Error retrieving BE startup options. Shutting down JVM");
- System.exit(1);
- }
}
/**
@@ -63,7 +52,6 @@ public class RuntimeEnv {
public void setNumCores(int numCores) { this.numCores_ = numCores; }
public void setTestEnv(boolean v) { isTestEnv_ = v; }
public boolean isTestEnv() { return isTestEnv_; }
- public boolean computeLineage() { return computeLineage_; }
public boolean isKuduSupported() {
return "true".equals(System.getenv("KUDU_IS_SUPPORTED"));
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/planner/Planner.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/planner/Planner.java b/fe/src/main/java/org/apache/impala/planner/Planner.java
index ec4cf7e..52524fb 100644
--- a/fe/src/main/java/org/apache/impala/planner/Planner.java
+++ b/fe/src/main/java/org/apache/impala/planner/Planner.java
@@ -39,6 +39,7 @@ import org.apache.impala.common.ImpalaException;
import org.apache.impala.common.PrintUtils;
import org.apache.impala.common.RuntimeEnv;
import org.apache.impala.common.TreeNode;
+import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TExplainLevel;
import org.apache.impala.thrift.TQueryCtx;
import org.apache.impala.thrift.TQueryExecRequest;
@@ -179,7 +180,7 @@ public class Planner {
ctx_.getRootAnalyzer().getTimeline().markEvent("Distributed plan created");
ColumnLineageGraph graph = ctx_.getRootAnalyzer().getColumnLineageGraph();
- if (RuntimeEnv.INSTANCE.computeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
+ if (BackendConfig.INSTANCE.getComputeLineage() || RuntimeEnv.INSTANCE.isTestEnv()) {
// Compute the column lineage graph
if (ctx_.isInsertOrCtas()) {
Table targetTable = ctx_.getAnalysisResult().getInsertStmt().getTargetTable();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/service/BackendConfig.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/BackendConfig.java b/fe/src/main/java/org/apache/impala/service/BackendConfig.java
index c90f674..47c987e 100644
--- a/fe/src/main/java/org/apache/impala/service/BackendConfig.java
+++ b/fe/src/main/java/org/apache/impala/service/BackendConfig.java
@@ -18,46 +18,60 @@
package org.apache.impala.service;
import com.google.common.base.Preconditions;
+import com.google.common.base.Strings;
+
+import org.apache.hadoop.conf.Configuration;
+import static org.apache.hadoop.fs.CommonConfigurationKeysPublic.HADOOP_SECURITY_AUTH_TO_LOCAL;
+import org.apache.hadoop.security.authentication.util.KerberosName;
+import org.apache.impala.thrift.TBackendGflags;
/**
* This class is meant to provide the FE with impalad backend configuration parameters,
* including command line arguments.
- * TODO: Remove this class and either
- * a) Figure out if there's a standard way to access flags from java
- * b) Create a util/gflags.java that let's us access the be flags
*/
public class BackendConfig {
- public static BackendConfig INSTANCE = new BackendConfig();
-
- // Default read block size (in bytes). This is the same as
- // the default FLAGS_read_size used by the IO manager in the backend.
- private final long READ_SIZE;
-
- // Variables below are overriden by JniFrontend/JniCatalog with user set configuration.
- // TODO: Read from backend instead of using static variables.
-
- // Determines how principal to short name conversion works. See User.java for more info.
- private static boolean allowAuthToLocalRules_ = false;
+ public static BackendConfig INSTANCE;
- // Kudu client timeout (ms).
- private static int kuduOperationTimeoutMs_ = 3 * 60 * 1000;
+ private TBackendGflags backendCfg_;
- private BackendConfig() {
- // TODO: Populate these by making calls to the backend instead of default constants.
- READ_SIZE = 8 * 1024 * 1024L;
+ private BackendConfig(TBackendGflags cfg) {
+ backendCfg_ = cfg;
}
- public long getReadSize() { return READ_SIZE; }
-
- public static boolean isAuthToLocalEnabled() { return allowAuthToLocalRules_; }
- public static void setAuthToLocal(boolean authToLocal) {
- allowAuthToLocalRules_ = authToLocal;
+ public static void create(TBackendGflags cfg) {
+ Preconditions.checkNotNull(cfg);
+ INSTANCE = new BackendConfig(cfg);
+ initAuthToLocal();
}
- public static int getKuduClientTimeoutMs() { return kuduOperationTimeoutMs_; }
+ public long getReadSize() { return backendCfg_.read_size; }
+ public boolean getComputeLineage() {
+ return !Strings.isNullOrEmpty(backendCfg_.lineage_event_log_dir);
+ }
+ public long getIncStatsMaxSize() { return backendCfg_.inc_stats_size_limit_bytes; }
+ public boolean isAuthToLocalEnabled() {
+ return backendCfg_.load_auth_to_local_rules &&
+ !Strings.isNullOrEmpty(backendCfg_.principal);
+ }
+ public int getKuduClientTimeoutMs() { return backendCfg_.kudu_operation_timeout_ms; }
- public static void setKuduClientTimeoutMs(int kuduOperationTimeoutMs) {
- Preconditions.checkArgument(kuduOperationTimeoutMs > 0);
- BackendConfig.kuduOperationTimeoutMs_ = kuduOperationTimeoutMs;
+ // Inits the auth_to_local configuration in the static KerberosName class.
+ private static void initAuthToLocal() {
+ // If auth_to_local is enabled, we read the configuration hadoop.security.auth_to_local
+ // from core-site.xml and use it for principal to short name conversion. If it is not,
+ // we use the defaultRule ("RULE:[1:$1] RULE:[2:$1]"), which just extracts the user
+ // name from any principal of form a@REALM or a/b@REALM. If auth_to_local is enabled
+ // and hadoop.security.auth_to_local is not specified in the hadoop configs, we use
+ // the "DEFAULT" rule that just extracts the username from any principal in the
+ // cluster's local realm. For more details on principal to short name translation,
+ // refer to org.apache.hadoop.security.KerberosName.
+ final String defaultRule = "RULE:[1:$1] RULE:[2:$1]";
+ final Configuration conf = new Configuration();
+ if (INSTANCE.isAuthToLocalEnabled()) {
+ KerberosName.setRules(conf.get(HADOOP_SECURITY_AUTH_TO_LOCAL, "DEFAULT"));
+ } else {
+ // just extract the simple user name
+ KerberosName.setRules(defaultRule);
+ }
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/service/FeSupport.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/FeSupport.java b/fe/src/main/java/org/apache/impala/service/FeSupport.java
index f982df3..c578726 100644
--- a/fe/src/main/java/org/apache/impala/service/FeSupport.java
+++ b/fe/src/main/java/org/apache/impala/service/FeSupport.java
@@ -45,7 +45,6 @@ import org.apache.impala.thrift.TPrioritizeLoadResponse;
import org.apache.impala.thrift.TQueryCtx;
import org.apache.impala.thrift.TResultRow;
import org.apache.impala.thrift.TStatus;
-import org.apache.impala.thrift.TStartupOptions;
import org.apache.impala.thrift.TSymbolLookupParams;
import org.apache.impala.thrift.TSymbolLookupResult;
import org.apache.impala.thrift.TTable;
@@ -84,9 +83,6 @@ public class FeSupport {
// using Java Thrift bindings.
public native static byte[] NativePrioritizeLoad(byte[] thriftReq);
- // Return select BE startup options as a serialized TStartupOptions
- public native static byte[] NativeGetStartupOptions();
-
/**
* Locally caches the jar at the specified HDFS location.
*
@@ -263,20 +259,6 @@ public class FeSupport {
}
}
- public static TStartupOptions GetStartupOptions() throws InternalException {
- try {
- byte[] result = NativeGetStartupOptions();
- Preconditions.checkNotNull(result);
- TDeserializer deserializer = new TDeserializer(new TBinaryProtocol.Factory());
- TStartupOptions options = new TStartupOptions();
- deserializer.deserialize(options, result);
- return options;
- } catch (TException e) {
- throw new InternalException("Error retrieving startup options: " + e.getMessage(),
- e);
- }
- }
-
/**
* This function should only be called explicitly by the FeSupport to ensure that
* native functions are loaded.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/service/JniCatalog.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/JniCatalog.java b/fe/src/main/java/org/apache/impala/service/JniCatalog.java
index 7993191..db9ba63 100644
--- a/fe/src/main/java/org/apache/impala/service/JniCatalog.java
+++ b/fe/src/main/java/org/apache/impala/service/JniCatalog.java
@@ -47,6 +47,7 @@ import org.apache.impala.thrift.TResetMetadataRequest;
import org.apache.impala.thrift.TSentryAdminCheckRequest;
import org.apache.impala.thrift.TUniqueId;
import org.apache.impala.thrift.TUpdateCatalogRequest;
+import org.apache.impala.thrift.TBackendGflags;
import org.apache.impala.util.GlogAppender;
import org.apache.impala.util.PatternMatcher;
import org.apache.thrift.TException;
@@ -78,29 +79,30 @@ public class JniCatalog {
return new TUniqueId(uuid.getMostSignificantBits(), uuid.getLeastSignificantBits());
}
- public JniCatalog(boolean loadInBackground, int numMetadataLoadingThreads,
- String sentryServiceConfig, int impalaLogLevel, int otherLogLevel,
- boolean allowAuthToLocal, String kerberosPrincipal, String localLibraryPath,
- int kuduOperationTimeoutMs) throws InternalException {
- BackendConfig.setAuthToLocal(allowAuthToLocal);
- BackendConfig.setKuduClientTimeoutMs(kuduOperationTimeoutMs);
- Preconditions.checkArgument(numMetadataLoadingThreads > 0);
+ public JniCatalog(byte[] thriftBackendConfig) throws InternalException,
+ ImpalaException, TException {
+ TBackendGflags cfg = new TBackendGflags();
+ JniUtil.deserializeThrift(protocolFactory_, cfg, thriftBackendConfig);
+
+ BackendConfig.create(cfg);
+
+ Preconditions.checkArgument(cfg.num_metadata_loading_threads > 0);
// This trick saves having to pass a TLogLevel enum, which is an object and more
// complex to pass through JNI.
- GlogAppender.Install(TLogLevel.values()[impalaLogLevel],
- TLogLevel.values()[otherLogLevel]);
+ GlogAppender.Install(TLogLevel.values()[cfg.impala_log_lvl],
+ TLogLevel.values()[cfg.non_impala_java_vlog]);
// Check if the Sentry Service is configured. If so, create a configuration object.
SentryConfig sentryConfig = null;
- if (!Strings.isNullOrEmpty(sentryServiceConfig)) {
- sentryConfig = new SentryConfig(sentryServiceConfig);
+ if (!Strings.isNullOrEmpty(cfg.sentry_config)) {
+ sentryConfig = new SentryConfig(cfg.sentry_config);
sentryConfig.loadConfig();
}
LOG.info(JniUtil.getJavaVersion());
- catalog_ = new CatalogServiceCatalog(loadInBackground,
- numMetadataLoadingThreads, sentryConfig, getServiceId(), kerberosPrincipal,
- localLibraryPath);
+ catalog_ = new CatalogServiceCatalog(cfg.load_catalog_in_background,
+ cfg.num_metadata_loading_threads, sentryConfig, getServiceId(), cfg.principal,
+ cfg.local_library_path);
try {
catalog_.reset();
} catch (CatalogException e) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/service/JniFrontend.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/service/JniFrontend.java b/fe/src/main/java/org/apache/impala/service/JniFrontend.java
index 3ef89e3..5e41af4 100644
--- a/fe/src/main/java/org/apache/impala/service/JniFrontend.java
+++ b/fe/src/main/java/org/apache/impala/service/JniFrontend.java
@@ -46,6 +46,7 @@ import org.apache.impala.common.FileSystemUtil;
import org.apache.impala.common.ImpalaException;
import org.apache.impala.common.InternalException;
import org.apache.impala.common.JniUtil;
+import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TBuildTestDescriptorTableParams;
import org.apache.impala.thrift.TCatalogObject;
import org.apache.impala.thrift.TDatabase;
@@ -81,6 +82,7 @@ import org.apache.impala.thrift.TTableName;
import org.apache.impala.thrift.TUniqueId;
import org.apache.impala.thrift.TUpdateCatalogCacheRequest;
import org.apache.impala.thrift.TUpdateMembershipRequest;
+import org.apache.impala.thrift.TBackendGflags;
import org.apache.impala.util.GlogAppender;
import org.apache.impala.util.PatternMatcher;
import org.apache.impala.util.TSessionStateUtil;
@@ -115,20 +117,20 @@ public class JniFrontend {
/**
* Create a new instance of the Jni Frontend.
*/
- public JniFrontend(boolean lazy, String serverName, String authorizationPolicyFile,
- String sentryConfigFile, String authPolicyProviderClass, int impalaLogLevel,
- int otherLogLevel, boolean allowAuthToLocal, String defaultKuduMasterHosts,
- int kuduOperationTimeoutMs)
- throws InternalException {
- BackendConfig.setAuthToLocal(allowAuthToLocal);
- BackendConfig.setKuduClientTimeoutMs(kuduOperationTimeoutMs);
- GlogAppender.Install(TLogLevel.values()[impalaLogLevel],
- TLogLevel.values()[otherLogLevel]);
+ public JniFrontend(byte[] thriftBackendConfig) throws ImpalaException, TException {
+ TBackendGflags cfg = new TBackendGflags();
+ JniUtil.deserializeThrift(protocolFactory_, cfg, thriftBackendConfig);
+
+ BackendConfig.create(cfg);
+
+ GlogAppender.Install(TLogLevel.values()[cfg.impala_log_lvl],
+ TLogLevel.values()[cfg.non_impala_java_vlog]);
// Validate the authorization configuration before initializing the Frontend.
// If there are any configuration problems Impala startup will fail.
- AuthorizationConfig authConfig = new AuthorizationConfig(serverName,
- authorizationPolicyFile, sentryConfigFile, authPolicyProviderClass);
+ AuthorizationConfig authConfig = new AuthorizationConfig(cfg.server_name,
+ cfg.authorization_policy_file, cfg.sentry_config,
+ cfg.authorization_policy_provider_class);
authConfig.validateConfig();
if (authConfig.isEnabled()) {
LOG.info(String.format("Authorization is 'ENABLED' using %s",
@@ -139,7 +141,7 @@ public class JniFrontend {
}
LOG.info(JniUtil.getJavaVersion());
- frontend_ = new Frontend(authConfig, defaultKuduMasterHosts);
+ frontend_ = new Frontend(authConfig, cfg.kudu_master_hosts);
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3f2f008a/fe/src/main/java/org/apache/impala/util/KuduUtil.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/util/KuduUtil.java b/fe/src/main/java/org/apache/impala/util/KuduUtil.java
index c50bf25..65fae74 100644
--- a/fe/src/main/java/org/apache/impala/util/KuduUtil.java
+++ b/fe/src/main/java/org/apache/impala/util/KuduUtil.java
@@ -54,8 +54,8 @@ public class KuduUtil {
*/
public static KuduClient createKuduClient(String kuduMasters) {
KuduClientBuilder b = new KuduClient.KuduClientBuilder(kuduMasters);
- b.defaultAdminOperationTimeoutMs(BackendConfig.getKuduClientTimeoutMs());
- b.defaultOperationTimeoutMs(BackendConfig.getKuduClientTimeoutMs());
+ b.defaultAdminOperationTimeoutMs(BackendConfig.INSTANCE.getKuduClientTimeoutMs());
+ b.defaultOperationTimeoutMs(BackendConfig.INSTANCE.getKuduClientTimeoutMs());
return b.build();
}
[39/50] [abbrv] incubator-impala git commit: IMPALA-1654: General
partition exprs in DDL operations.
Posted by ta...@apache.org.
IMPALA-1654: General partition exprs in DDL operations.
This commit handles partition related DDL in a more general way. We can
now use compound predicates to specify a list of partitions in
statements like ALTER TABLE DROP PARTITION and COMPUTE INCREMENTAL
STATS, etc. It will also make sure some statements only accept one
partition at a time, such as PARTITION SET LOCATION and LOAD DATA. ALTER
TABLE ADD PARTITION remains using the old PartitionKeyValue's logic.
The changed partition related DDLs are as follows,
Table: p (i int) partitioned by (j int, k string)
Partitions:
+-------+---+-------+--------+------+--------------+-------------------+
| j | k | #Rows | #Files | Size | Bytes Cached | Cache Replication |
+-------+---+-------+--------+------+--------------+-------------------+
| 1 | a | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 1 | b | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 1 | c | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 2 | d | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 2 | e | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 2 | f | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| Total | | -1 | 0 | 0B | 0B | |
+-------+---+-------+--------+------+--------------+-------------------+
1. show files in p partition (j<2, k='a');
2. alter table p partition (j<2, k in ("b","c") set cached in 'testPool';
// j can appear more than once,
3.1. alter table p partition (j<2, j>0, k<>"d") set uncached;
// it is the same as
3.2. alter table p partition (j<2 and j>0, not k="e") set uncached;
// we can also do 'or'
3.3. alter table p partition (j<2 or j>0, k like "%") set uncached;
// missing 'k' matches all values of k
4. alter table p partition (j<2) set fileformat textfile;
5. alter table p partition (k rlike ".*") set serdeproperties ("k"="v");
6. alter table p partition (j is not null) set tblproperties ("k"="v");
7. alter table p drop partition (j<2);
8. compute incremental stats p partition(j<2);
The remaining old partition related DDLs are as follows,
1. load data inpath '/path/from' into table p partition (j=2, k="d");
2. alter table p add partition (j=2, k="g");
3. alter table p partition (j=2, k="g") set location '/path/to';
4. insert into p partition (j=2, k="g") values (1), (2), (3);
General partition expressions or partially specified partition specs
allows partition predicates to return empty partition set no matter
'IF EXISTS' is specified.
Examples:
[localhost.localdomain:21000] >
alter table p drop partition (j=2, k="f");
Query: alter table p drop partition (j=2, k="f")
+-------------------------+
| summary |
+-------------------------+
| Dropped 1 partition(s). |
+-------------------------+
Fetched 1 row(s) in 0.78s
[localhost.localdomain:21000] >
alter table p drop partition (j=2, k<"f");
Query: alter table p drop partition (j=2, k<"f")
+-------------------------+
| summary |
+-------------------------+
| Dropped 2 partition(s). |
+-------------------------+
Fetched 1 row(s) in 0.41s
[localhost.localdomain:21000] >
alter table p drop partition (k="a");
Query: alter table p drop partition (k="a")
+-------------------------+
| summary |
+-------------------------+
| Dropped 1 partition(s). |
+-------------------------+
Fetched 1 row(s) in 0.25s
[localhost.localdomain:21000] > show partitions p;
Query: show partitions p
+-------+---+-------+--------+------+--------------+-------------------+
| j | k | #Rows | #Files | Size | Bytes Cached | Cache Replication |
+-------+---+-------+--------+------+--------------+-------------------+
| 1 | b | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| 1 | c | -1 | 0 | 0B | NOT CACHED | NOT CACHED |
| Total | | -1 | 0 | 0B | 0B | |
+-------+---+-------+--------+------+--------------+-------------------+
Fetched 3 row(s) in 0.01s
Change-Id: I2c9162fcf9d227b8daf4c2e761d57bab4e26408f
Reviewed-on: http://gerrit.cloudera.org:8080/3942
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/628685ae
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/628685ae
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/628685ae
Branch: refs/heads/hadoop-next
Commit: 628685ae749daa133c9b7a6184c5523136979974
Parents: 3f2f008
Author: Amos Bird <am...@gmail.com>
Authored: Wed Nov 25 06:20:15 2015 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 03:27:36 2016 +0000
----------------------------------------------------------------------
be/src/service/query-exec-state.cc | 19 +-
be/src/service/query-exec-state.h | 1 +
common/thrift/CatalogService.thrift | 2 +-
common/thrift/Frontend.thrift | 6 +-
common/thrift/JniCatalog.thrift | 24 +-
fe/src/main/cup/sql-parser.cup | 62 ++-
.../analysis/AlterTableDropPartitionStmt.java | 22 +-
.../analysis/AlterTableSetCachedStmt.java | 30 +-
.../analysis/AlterTableSetFileFormatStmt.java | 12 +-
.../analysis/AlterTableSetLocationStmt.java | 50 ++-
.../impala/analysis/AlterTableSetStmt.java | 18 +-
.../analysis/AlterTableSetTblProperties.java | 8 +-
.../apache/impala/analysis/AlterTableStmt.java | 24 +-
.../org/apache/impala/analysis/Analyzer.java | 24 +-
.../apache/impala/analysis/BaseTableRef.java | 2 +-
.../impala/analysis/CollectionTableRef.java | 2 +-
.../impala/analysis/ComputeStatsStmt.java | 105 +++--
.../apache/impala/analysis/DropStatsStmt.java | 55 ++-
.../apache/impala/analysis/InlineViewRef.java | 5 +-
.../apache/impala/analysis/PartitionSet.java | 199 +++++++++
.../apache/impala/analysis/PartitionSpec.java | 62 +--
.../impala/analysis/PartitionSpecBase.java | 94 +++++
.../apache/impala/analysis/ShowFilesStmt.java | 44 +-
.../org/apache/impala/analysis/TableRef.java | 12 +-
.../apache/impala/analysis/TupleDescriptor.java | 14 +
.../impala/catalog/CatalogServiceCatalog.java | 19 +
.../org/apache/impala/catalog/HdfsTable.java | 80 +++-
.../java/org/apache/impala/catalog/Table.java | 4 +
.../impala/planner/HdfsPartitionPruner.java | 19 +-
.../impala/planner/SingleNodePlanner.java | 2 +-
.../impala/service/CatalogOpExecutor.java | 402 +++++++++++--------
.../org/apache/impala/service/Frontend.java | 2 +-
.../apache/impala/analysis/AnalyzeDDLTest.java | 334 +++++++++------
.../impala/analysis/AnalyzeStmtsTest.java | 2 +-
.../org/apache/impala/analysis/ParserTest.java | 17 +-
shell/impala_client.py | 2 +-
.../queries/QueryTest/alter-table.test | 45 +++
.../queries/QueryTest/compute-stats.test | 2 +
.../queries/QueryTest/hdfs-caching.test | 2 +-
.../queries/QueryTest/kudu_alter.test | 6 +
.../QueryTest/partition-ddl-predicates.test | 156 +++++++
tests/metadata/test_ddl.py | 4 +
42 files changed, 1398 insertions(+), 596 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 bfb5a86..6075914 100644
--- a/be/src/service/query-exec-state.cc
+++ b/be/src/service/query-exec-state.cc
@@ -516,6 +516,9 @@ Status ImpalaServer::QueryExecState::ExecDdlRequest() {
DCHECK(exec_request_.__isset.query_exec_request);
RETURN_IF_ERROR(ExecQueryOrDmlRequest(exec_request_.query_exec_request));
}
+
+ // Set the results to be reported to the client.
+ SetResultSet(catalog_op_executor_->ddl_exec_response());
return Status::OK();
}
@@ -919,6 +922,13 @@ Status ImpalaServer::QueryExecState::UpdateCatalog() {
return Status::OK();
}
+void ImpalaServer::QueryExecState::SetResultSet(const TDdlExecResponse* ddl_resp) {
+ if (ddl_resp != NULL && ddl_resp->__isset.result_set) {
+ result_metadata_ = ddl_resp->result_set.schema;
+ request_result_set_.reset(new vector<TResultRow>(ddl_resp->result_set.rows));
+ }
+}
+
void ImpalaServer::QueryExecState::SetResultSet(const vector<string>& results) {
request_result_set_.reset(new vector<TResultRow>);
request_result_set_->resize(results.size());
@@ -1026,14 +1036,7 @@ Status ImpalaServer::QueryExecState::UpdateTableAndColumnStats(
exec_request_.query_options.sync_ddl));
// Set the results to be reported to the client.
- const TDdlExecResponse* ddl_resp = catalog_op_executor_->ddl_exec_response();
- if (ddl_resp != NULL && ddl_resp->__isset.result_set) {
- result_metadata_ = ddl_resp->result_set.schema;
- request_result_set_.reset(new vector<TResultRow>);
- request_result_set_->assign(
- ddl_resp->result_set.rows.begin(), ddl_resp->result_set.rows.end());
- }
-
+ SetResultSet(catalog_op_executor_->ddl_exec_response());
query_events_->MarkEvent("Metastore update finished");
return Status::OK();
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 55e3ffa..28c8cba 100644
--- a/be/src/service/query-exec-state.h
+++ b/be/src/service/query-exec-state.h
@@ -374,6 +374,7 @@ class ImpalaServer::QueryExecState {
/// Copies results into request_result_set_
/// TODO: Have the FE return list<Data.TResultRow> so that this isn't necessary
+ void SetResultSet(const TDdlExecResponse* ddl_resp);
void SetResultSet(const std::vector<std::string>& results);
void SetResultSet(const std::vector<std::string>& col1,
const std::vector<std::string>& col2);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/common/thrift/CatalogService.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/CatalogService.thrift b/common/thrift/CatalogService.thrift
index ec4bde2..188f71a 100644
--- a/common/thrift/CatalogService.thrift
+++ b/common/thrift/CatalogService.thrift
@@ -145,7 +145,7 @@ struct TDdlExecResponse {
2: optional bool new_table_created;
// Result of DDL operation to be returned to the client. Currently only set
- // by COMPUTE STATS.
+ // by COMPUTE STATS and ALTER TABLE.
3: optional Results.TResultSet result_set
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/common/thrift/Frontend.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/Frontend.thrift b/common/thrift/Frontend.thrift
index 8c279f5..6fdf972 100644
--- a/common/thrift/Frontend.thrift
+++ b/common/thrift/Frontend.thrift
@@ -209,9 +209,9 @@ struct TShowTablesParams {
struct TShowFilesParams {
1: required CatalogObjects.TTableName table_name
- // An optional partition spec. Set if this operation should apply to a specific
- // partition rather than the base table.
- 2: optional list<CatalogObjects.TPartitionKeyValue> partition_spec
+ // An optional partition set. Set if this operation should apply to a list of
+ // partitions rather than the base table.
+ 2: optional list<list<CatalogObjects.TPartitionKeyValue>> partition_set
}
// Parameters for SHOW [CURRENT] ROLES and SHOW ROLE GRANT GROUP <groupName> commands
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/common/thrift/JniCatalog.thrift
----------------------------------------------------------------------
diff --git a/common/thrift/JniCatalog.thrift b/common/thrift/JniCatalog.thrift
index 8ed9fe3..7fa7f7b 100644
--- a/common/thrift/JniCatalog.thrift
+++ b/common/thrift/JniCatalog.thrift
@@ -111,10 +111,10 @@ struct TDropStatsParams {
// Fully qualified name of the target table
1: required CatalogObjects.TTableName table_name
- // If set, delete the stats only for a particular partition, but do not recompute the
+ // If set, delete the stats only for specified partitions, but do not recompute the
// stats for the whole table. This is set only for
// DROP INCREMENTAL STATS <table> PARTITION(...)
- 2: optional list<CatalogObjects.TPartitionKeyValue> partition_spec
+ 2: optional list<list<CatalogObjects.TPartitionKeyValue>> partition_set
}
// Parameters of CREATE FUNCTION commands
@@ -194,8 +194,8 @@ struct TAlterTableDropColParams {
// Parameters for ALTER TABLE DROP PARTITION commands
struct TAlterTableDropPartitionParams {
- // The partition spec (list of keys and values) to add.
- 1: required list<CatalogObjects.TPartitionKeyValue> partition_spec
+ // The partition set used to drop partitions.
+ 1: required list<list<CatalogObjects.TPartitionKeyValue>> partition_set
// If true, no error is raised if no partition with the specified spec exists.
2: required bool if_exists
@@ -222,18 +222,18 @@ struct TAlterTableSetTblPropertiesParams {
// Map of property names to property values.
2: required map<string, string> properties
- // If set, alters the properties of the given partition, otherwise
+ // If set, alters the properties of the given partitions, otherwise
// those of the table.
- 3: optional list<CatalogObjects.TPartitionKeyValue> partition_spec
+ 3: optional list<list<CatalogObjects.TPartitionKeyValue>> partition_set
}
-// Parameters for ALTER TABLE SET [PARTITION partitionSpec] FILEFORMAT commands.
+// Parameters for ALTER TABLE SET [PARTITION partitionSet] FILEFORMAT commands.
struct TAlterTableSetFileFormatParams {
// New file format.
1: required CatalogObjects.THdfsFileFormat file_format
- // An optional partition spec, set if modifying the fileformat of a partition.
- 2: optional list<CatalogObjects.TPartitionKeyValue> partition_spec
+ // An optional partition set, set if modifying the fileformat of the partitions.
+ 2: optional list<list<CatalogObjects.TPartitionKeyValue>> partition_set
}
// Parameters for ALTER TABLE SET [PARTITION partitionSpec] location commands.
@@ -270,14 +270,14 @@ struct TAlterTableUpdateStatsParams {
6: optional bool is_incremental
}
-// Parameters for ALTER TABLE SET [PARTITION partitionSpec] CACHED|UNCACHED
+// Parameters for ALTER TABLE SET [PARTITION partitionSet] CACHED|UNCACHED
struct TAlterTableSetCachedParams {
// Details on what operation to perform (cache or uncache)
1: required THdfsCachingOp cache_op
- // An optional partition spec, set if marking a partition as cached/uncached
+ // An optional partition set, set if marking the partitions as cached/uncached
// rather than a table.
- 2: optional list<CatalogObjects.TPartitionKeyValue> partition_spec
+ 2: optional list<list<CatalogObjects.TPartitionKeyValue>> partition_set
}
// Parameters for all ALTER TABLE commands.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/cup/sql-parser.cup
----------------------------------------------------------------------
diff --git a/fe/src/main/cup/sql-parser.cup b/fe/src/main/cup/sql-parser.cup
index 57d5a24..1884036 100644
--- a/fe/src/main/cup/sql-parser.cup
+++ b/fe/src/main/cup/sql-parser.cup
@@ -370,6 +370,10 @@ nonterminal StatementBase explain_stmt;
nonterminal PartitionSpec opt_partition_spec;
// Required partition spec
nonterminal PartitionSpec partition_spec;
+// Optional partition set
+nonterminal PartitionSet opt_partition_set;
+// Required partition set
+nonterminal PartitionSet partition_set;
nonterminal ArrayList<PartitionKeyValue> partition_clause;
nonterminal ArrayList<PartitionKeyValue> static_partition_key_value_list;
nonterminal ArrayList<PartitionKeyValue> partition_key_value_list;
@@ -904,34 +908,39 @@ alter_tbl_stmt ::=
column_def:col_def
{: RESULT = new AlterTableChangeColStmt(table, col_name, col_def); :}
| KW_ALTER KW_TABLE table_name:table KW_DROP if_exists_val:if_exists
- partition_spec:partition purge_val:purge
- {: RESULT = new AlterTableDropPartitionStmt(table, partition, if_exists, purge); :}
- | KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET KW_FILEFORMAT
+ partition_set:partitions purge_val:purge
+ {: RESULT = new AlterTableDropPartitionStmt(table, partitions, if_exists, purge); :}
+ | KW_ALTER KW_TABLE table_name:table opt_partition_set:partitions KW_SET KW_FILEFORMAT
file_format_val:file_format
- {: RESULT = new AlterTableSetFileFormatStmt(table, partition, file_format); :}
- | KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
+ {: RESULT = new AlterTableSetFileFormatStmt(table, partitions, file_format); :}
+ | KW_ALTER KW_TABLE table_name:table opt_partition_set:partitions KW_SET
KW_LOCATION STRING_LITERAL:location
- {: RESULT = new AlterTableSetLocationStmt(table, partition, new HdfsUri(location)); :}
+ {:
+ // Need to check in analysis that the partition set only matches a single partition.
+ // Avoids a reduce/reduce conflict and allows the user to select a partition without
+ // fully specifying all partition-key values.
+ RESULT = new AlterTableSetLocationStmt(table, partitions, new HdfsUri(location));
+ :}
| KW_ALTER KW_TABLE table_name:table KW_RENAME KW_TO table_name:new_table
{: RESULT = new AlterTableOrViewRenameStmt(table, new_table, true); :}
- | KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
+ | KW_ALTER KW_TABLE table_name:table opt_partition_set:partitions KW_SET
table_property_type:target LPAREN properties_map:properties RPAREN
- {: RESULT = new AlterTableSetTblProperties(table, partition, target, properties); :}
- | KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
+ {: RESULT = new AlterTableSetTblProperties(table, partitions, target, properties); :}
+ | KW_ALTER KW_TABLE table_name:table opt_partition_set:partition KW_SET
KW_COLUMN KW_STATS IDENT:col LPAREN properties_map:map RPAREN
{:
- // The opt_partition_spec is used to avoid conflicts even though
+ // The opt_partition_set is used to avoid conflicts even though
// a partition clause does not make sense for this stmt. If a partition
// is given, manually throw a parse error.
if (partition != null) parser.parseError("set", SqlParserSymbols.KW_SET);
RESULT = new AlterTableSetColumnStats(table, col, map);
:}
- | KW_ALTER KW_TABLE table_name:table opt_partition_spec:partition KW_SET
+ | KW_ALTER KW_TABLE table_name:table opt_partition_set:partitions KW_SET
cache_op_val:cache_op
{:
// Ensure a parser error is thrown for ALTER statements if no cache op is specified.
if (cache_op == null) parser.parseError("set", SqlParserSymbols.KW_SET);
- RESULT = new AlterTableSetCachedStmt(table, partition, cache_op);
+ RESULT = new AlterTableSetCachedStmt(table, partitions, cache_op);
:}
| KW_ALTER KW_TABLE table_name:table KW_RECOVER KW_PARTITIONS
{: RESULT = new AlterTableRecoverPartitionsStmt(table); :}
@@ -1550,15 +1559,15 @@ compute_stats_stmt ::=
{: RESULT = new ComputeStatsStmt(table); :}
| KW_COMPUTE KW_INCREMENTAL KW_STATS table_name:table
{: RESULT = new ComputeStatsStmt(table, true, null); :}
- | KW_COMPUTE KW_INCREMENTAL KW_STATS table_name:table partition_spec:spec
- {: RESULT = new ComputeStatsStmt(table, true, spec); :}
+ | KW_COMPUTE KW_INCREMENTAL KW_STATS table_name:table partition_set:partitions
+ {: RESULT = new ComputeStatsStmt(table, true, partitions); :}
;
drop_stats_stmt ::=
KW_DROP KW_STATS table_name:table
{: RESULT = new DropStatsStmt(table); :}
- | KW_DROP KW_INCREMENTAL KW_STATS table_name:table partition_spec:spec
- {: RESULT = new DropStatsStmt(table, spec); :}
+ | KW_DROP KW_INCREMENTAL KW_STATS table_name:table partition_set:partitions
+ {: RESULT = new DropStatsStmt(table, partitions); :}
;
drop_db_stmt ::=
@@ -1626,6 +1635,23 @@ partition_key_value_list ::=
:}
;
+// TODO: reuse this for INSERT statement.
+// A partition set is a set of expressions used to select a list of partitions
+// for certain operation such as DROP PARTITION. This is different than a partition
+// clause in an INSERT statement. Partition clause contains dynamic and static
+// partition key/values.
+partition_set ::=
+ KW_PARTITION LPAREN expr_list:list RPAREN
+ {: RESULT = new PartitionSet(list); :}
+ ;
+
+opt_partition_set ::=
+ partition_set:partition_set
+ {: RESULT = partition_set; :}
+ | /* Empty */
+ {: RESULT = null; :}
+ ;
+
// A partition spec is a set of static partition key/value pairs. This is a bit
// different than a partition clause in an INSERT statement because that allows
// for dynamic and static partition key/values.
@@ -2020,8 +2046,8 @@ show_create_function_stmt ::=
;
show_files_stmt ::=
- KW_SHOW KW_FILES KW_IN table_name:table opt_partition_spec:partition
- {: RESULT = new ShowFilesStmt(table, partition); :}
+ KW_SHOW KW_FILES KW_IN table_name:table opt_partition_set:partitions
+ {: RESULT = new ShowFilesStmt(table, partitions); :}
;
describe_db_stmt ::=
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableDropPartitionStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableDropPartitionStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableDropPartitionStmt.java
index 773fea4..9eb580d 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableDropPartitionStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableDropPartitionStmt.java
@@ -29,18 +29,18 @@ import com.google.common.base.Preconditions;
*/
public class AlterTableDropPartitionStmt extends AlterTableStmt {
private final boolean ifExists_;
- private final PartitionSpec partitionSpec_;
+ private final PartitionSet partitionSet_;
// Setting this value causes dropped partition(s) to be permanently
// deleted. For example, for HDFS tables it skips the trash mechanism
private final boolean purgePartition_;
public AlterTableDropPartitionStmt(TableName tableName,
- PartitionSpec partitionSpec, boolean ifExists, boolean purgePartition) {
+ PartitionSet partitionSet, boolean ifExists, boolean purgePartition) {
super(tableName);
- Preconditions.checkNotNull(partitionSpec);
- partitionSpec_ = partitionSpec;
- partitionSpec_.setTableName(tableName);
+ Preconditions.checkNotNull(partitionSet);
+ partitionSet_ = partitionSet;
+ partitionSet_.setTableName(tableName);
ifExists_ = ifExists;
purgePartition_ = purgePartition;
}
@@ -52,7 +52,7 @@ public class AlterTableDropPartitionStmt extends AlterTableStmt {
StringBuilder sb = new StringBuilder("ALTER TABLE " + getTbl());
sb.append(" DROP ");
if (ifExists_) sb.append("IF EXISTS ");
- sb.append(" DROP " + partitionSpec_.toSql());
+ sb.append(" DROP " + partitionSet_.toSql());
if (purgePartition_) sb.append(" PURGE");
return sb.toString();
}
@@ -62,8 +62,8 @@ public class AlterTableDropPartitionStmt extends AlterTableStmt {
TAlterTableParams params = super.toThrift();
params.setAlter_type(TAlterTableType.DROP_PARTITION);
TAlterTableDropPartitionParams addPartParams = new TAlterTableDropPartitionParams();
- addPartParams.setPartition_spec(partitionSpec_.toThrift());
- addPartParams.setIf_exists(ifExists_);
+ addPartParams.setPartition_set(partitionSet_.toThrift());
+ addPartParams.setIf_exists(!partitionSet_.getPartitionShouldExist());
addPartParams.setPurge(purgePartition_);
params.setDrop_partition_params(addPartParams);
return params;
@@ -72,8 +72,8 @@ public class AlterTableDropPartitionStmt extends AlterTableStmt {
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
super.analyze(analyzer);
- if (!ifExists_) partitionSpec_.setPartitionShouldExist();
- partitionSpec_.setPrivilegeRequirement(Privilege.ALTER);
- partitionSpec_.analyze(analyzer);
+ if (!ifExists_) partitionSet_.setPartitionShouldExist();
+ partitionSet_.setPrivilegeRequirement(Privilege.ALTER);
+ partitionSet_.analyze(analyzer);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableSetCachedStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetCachedStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetCachedStmt.java
index 56122e1..931c6a9 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetCachedStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetCachedStmt.java
@@ -17,6 +17,8 @@
package org.apache.impala.analysis;
+import java.util.List;
+
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.catalog.HdfsPartition;
import org.apache.impala.catalog.Table;
@@ -27,14 +29,14 @@ import org.apache.impala.thrift.TAlterTableType;
import com.google.common.base.Preconditions;
/**
- * Represents an ALTER TABLE [PARTITION partitionSpec] SET [UNCACHED|CACHED 'pool'].
+ * Represents an ALTER TABLE [PARTITION partitionSet] SET [UNCACHED|CACHED 'pool'].
*/
public class AlterTableSetCachedStmt extends AlterTableSetStmt {
private final HdfsCachingOp cacheOp_;
public AlterTableSetCachedStmt(TableName tableName,
- PartitionSpec partitionSpec, HdfsCachingOp cacheOp) {
- super(tableName, partitionSpec);
+ PartitionSet partitionSet, HdfsCachingOp cacheOp) {
+ super(tableName, partitionSet);
Preconditions.checkNotNull(cacheOp);
cacheOp_ = cacheOp;
}
@@ -45,8 +47,8 @@ public class AlterTableSetCachedStmt extends AlterTableSetStmt {
params.setAlter_type(TAlterTableType.SET_CACHED);
TAlterTableSetCachedParams cachingParams =
new TAlterTableSetCachedParams();
- if (getPartitionSpec() != null) {
- cachingParams.setPartition_spec(getPartitionSpec().toThrift());
+ if (getPartitionSet() != null) {
+ cachingParams.setPartition_set(getPartitionSet().toThrift());
}
cachingParams.setCache_op(cacheOp_.toThrift());
params.setSet_cached_params(cachingParams);
@@ -66,18 +68,18 @@ public class AlterTableSetCachedStmt extends AlterTableSetStmt {
}
if (cacheOp_.shouldCache()) {
- boolean isCacheable;
- PartitionSpec partSpec = getPartitionSpec();
+ boolean isCacheable = true;
+ PartitionSet partitionSet = getPartitionSet();
HdfsTable hdfsTable = (HdfsTable)table;
StringBuilder nameSb = new StringBuilder();
- if (partSpec != null) {
- HdfsPartition part = hdfsTable.getPartition(partSpec.getPartitionSpecKeyValues());
- if (part == null) {
- throw new AnalysisException("Partition spec does not exist: " +
- partSpec.toSql());
+ if (partitionSet != null) {
+ List<HdfsPartition> parts = partitionSet.getPartitions();
+ nameSb.append("Partition(s) (");
+ for(HdfsPartition part: parts) {
+ isCacheable = isCacheable && part.isCacheable();
+ if(!part.isCacheable()) nameSb.append(part.getPartitionName());
}
- isCacheable = part.isCacheable();
- nameSb.append("Partition (" + part.getPartitionName() + ")");
+ nameSb.append(")");
} else {
isCacheable = hdfsTable.isCacheable();
nameSb.append("Table ").append(table.getFullName());
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableSetFileFormatStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetFileFormatStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetFileFormatStmt.java
index ff8d878..5b53b80 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetFileFormatStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetFileFormatStmt.java
@@ -24,14 +24,14 @@ import org.apache.impala.thrift.TAlterTableType;
import org.apache.impala.thrift.THdfsFileFormat;
/**
- * Represents an ALTER TABLE [PARTITION partitionSpec] SET FILEFORMAT statement.
+ * Represents an ALTER TABLE [PARTITION partitionSet] SET FILEFORMAT statement.
*/
public class AlterTableSetFileFormatStmt extends AlterTableSetStmt {
private final THdfsFileFormat fileFormat_;
public AlterTableSetFileFormatStmt(TableName tableName,
- PartitionSpec partitionSpec, THdfsFileFormat fileFormat) {
- super(tableName, partitionSpec);
+ PartitionSet partitionSet, THdfsFileFormat fileFormat) {
+ super(tableName, partitionSet);
this.fileFormat_ = fileFormat;
}
@@ -43,8 +43,8 @@ public class AlterTableSetFileFormatStmt extends AlterTableSetStmt {
params.setAlter_type(TAlterTableType.SET_FILE_FORMAT);
TAlterTableSetFileFormatParams fileFormatParams =
new TAlterTableSetFileFormatParams(fileFormat_);
- if (getPartitionSpec() != null) {
- fileFormatParams.setPartition_spec(getPartitionSpec().toThrift());
+ if (getPartitionSet() != null) {
+ fileFormatParams.setPartition_set(getPartitionSet().toThrift());
}
params.setSet_file_format_params(fileFormatParams);
return params;
@@ -54,4 +54,4 @@ public class AlterTableSetFileFormatStmt extends AlterTableSetStmt {
public void analyze(Analyzer analyzer) throws AnalysisException {
super.analyze(analyzer);
}
-}
\ No newline at end of file
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableSetLocationStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetLocationStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetLocationStmt.java
index 0219b8c..d7a7448 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetLocationStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetLocationStmt.java
@@ -17,6 +17,10 @@
package org.apache.impala.analysis;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.hadoop.fs.permission.FsAction;
import org.apache.impala.authorization.Privilege;
import org.apache.impala.catalog.HdfsPartition;
import org.apache.impala.catalog.HdfsTable;
@@ -25,18 +29,23 @@ import org.apache.impala.common.AnalysisException;
import org.apache.impala.thrift.TAlterTableParams;
import org.apache.impala.thrift.TAlterTableSetLocationParams;
import org.apache.impala.thrift.TAlterTableType;
+import org.apache.impala.thrift.TPartitionKeyValue;
+import com.google.common.base.Function;
+import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
-import org.apache.hadoop.fs.permission.FsAction;
+import com.google.common.collect.Lists;
/**
* Represents an ALTER TABLE [PARTITION partitionSpec] SET LOCATION statement.
*/
public class AlterTableSetLocationStmt extends AlterTableSetStmt {
+ // max num of partitions printed during error reporting.
+ private static final int NUM_PARTITION_LOG_LIMIT = 3;
private final HdfsUri location_;
public AlterTableSetLocationStmt(TableName tableName,
- PartitionSpec partitionSpec, HdfsUri location) {
- super(tableName, partitionSpec);
+ PartitionSet partitionSet, HdfsUri location) {
+ super(tableName, partitionSet);
Preconditions.checkNotNull(location);
this.location_ = location;
}
@@ -49,8 +58,10 @@ public class AlterTableSetLocationStmt extends AlterTableSetStmt {
params.setAlter_type(TAlterTableType.SET_LOCATION);
TAlterTableSetLocationParams locationParams =
new TAlterTableSetLocationParams(location_.toString());
- if (getPartitionSpec() != null) {
- locationParams.setPartition_spec(getPartitionSpec().toThrift());
+ if (getPartitionSet() != null) {
+ List<List<TPartitionKeyValue>> tPartitionSet = getPartitionSet().toThrift();
+ Preconditions.checkState(tPartitionSet.size() == 1);
+ locationParams.setPartition_spec(tPartitionSet.get(0));
}
params.setSet_location_params(locationParams);
return params;
@@ -65,16 +76,31 @@ public class AlterTableSetLocationStmt extends AlterTableSetStmt {
Preconditions.checkNotNull(table);
if (table instanceof HdfsTable) {
HdfsTable hdfsTable = (HdfsTable) table;
- if (getPartitionSpec() != null) {
+ if (getPartitionSet() != null) {
// Targeting a partition rather than a table.
- PartitionSpec partitionSpec = getPartitionSpec();
- HdfsPartition partition = hdfsTable.getPartition(
- partitionSpec.getPartitionSpecKeyValues());
- Preconditions.checkNotNull(partition);
- if (partition.isMarkedCached()) {
+ List<HdfsPartition> partitions = getPartitionSet().getPartitions();
+ if (partitions.size() != 1) {
+ // Sort the partitions to get a consistent error reporting.
+ List<HdfsPartition> sortedPartitions = Lists.newArrayList(partitions);
+ Collections.sort(sortedPartitions);
+ List<String> sortedPartitionNames =
+ Lists.transform(sortedPartitions.subList(0, NUM_PARTITION_LOG_LIMIT),
+ new Function<HdfsPartition, String>() {
+ @Override
+ public String apply(HdfsPartition hdfsPartition) {
+ return hdfsPartition.getPartitionName();
+ }
+ });
+ throw new AnalysisException(String.format(
+ "Partition expr in set location statements can only match " +
+ "one partition. Too many matched partitions %s %s",
+ Joiner.on(",").join(sortedPartitionNames),
+ sortedPartitions.size() < partitions.size() ? "..." : "."));
+ }
+ if (partitions.get(0).isMarkedCached()) {
throw new AnalysisException(String.format("Target partition is cached, " +
"please uncache before changing the location using: ALTER TABLE %s %s " +
- "SET UNCACHED", table.getFullName(), partitionSpec.toSql()));
+ "SET UNCACHED", table.getFullName(), getPartitionSet().toSql()));
}
} else if (hdfsTable.isMarkedCached()) {
throw new AnalysisException(String.format("Target table is cached, please " +
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableSetStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetStmt.java
index a37b949..178d28b 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetStmt.java
@@ -26,15 +26,15 @@ import org.apache.impala.common.AnalysisException;
* Base class for all ALTER TABLE ... SET statements
*/
public class AlterTableSetStmt extends AlterTableStmt {
- protected final PartitionSpec partitionSpec_;
+ protected final PartitionSet partitionSet_;
- public AlterTableSetStmt(TableName tableName, PartitionSpec partitionSpec) {
+ public AlterTableSetStmt(TableName tableName, PartitionSet partitionSet) {
super(tableName);
- partitionSpec_ = partitionSpec;
- if (partitionSpec_ != null) partitionSpec_.setTableName(tableName);
+ partitionSet_ = partitionSet;
+ if (partitionSet_ != null) partitionSet_.setTableName(tableName);
}
- public PartitionSpec getPartitionSpec() { return partitionSpec_; }
+ PartitionSet getPartitionSet() { return partitionSet_; }
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
@@ -49,10 +49,10 @@ public class AlterTableSetStmt extends AlterTableStmt {
}
// Altering the table rather than the partition.
- if (partitionSpec_ == null) return;
+ if (partitionSet_ == null) return;
- partitionSpec_.setPartitionShouldExist();
- partitionSpec_.setPrivilegeRequirement(Privilege.ALTER);
- partitionSpec_.analyze(analyzer);
+ partitionSet_.setPartitionShouldExist();
+ partitionSet_.setPrivilegeRequirement(Privilege.ALTER);
+ partitionSet_.analyze(analyzer);
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableSetTblProperties.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetTblProperties.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetTblProperties.java
index f2a81cd..08007b3 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableSetTblProperties.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableSetTblProperties.java
@@ -47,9 +47,9 @@ public class AlterTableSetTblProperties extends AlterTableSetStmt {
private final TTablePropertyType targetProperty_;
private final HashMap<String, String> tblProperties_;
- public AlterTableSetTblProperties(TableName tableName, PartitionSpec partitionSpec,
+ public AlterTableSetTblProperties(TableName tableName, PartitionSet partitionSet,
TTablePropertyType targetProperty, HashMap<String, String> tblProperties) {
- super(tableName, partitionSpec);
+ super(tableName, partitionSet);
Preconditions.checkNotNull(tblProperties);
Preconditions.checkNotNull(targetProperty);
targetProperty_ = targetProperty;
@@ -67,8 +67,8 @@ public class AlterTableSetTblProperties extends AlterTableSetStmt {
new TAlterTableSetTblPropertiesParams();
tblPropertyParams.setTarget(targetProperty_);
tblPropertyParams.setProperties(tblProperties_);
- if (partitionSpec_ != null) {
- tblPropertyParams.setPartition_spec(partitionSpec_.toThrift());
+ if (partitionSet_ != null) {
+ tblPropertyParams.setPartition_set(partitionSet_.toThrift());
}
params.setSet_tbl_properties_params(tblPropertyParams);
return params;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/AlterTableStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/AlterTableStmt.java b/fe/src/main/java/org/apache/impala/analysis/AlterTableStmt.java
index 223abe9..d86448b 100644
--- a/fe/src/main/java/org/apache/impala/analysis/AlterTableStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/AlterTableStmt.java
@@ -69,23 +69,33 @@ public abstract class AlterTableStmt extends StatementBase {
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
- table_ = analyzer.getTable(tableName_, Privilege.ALTER);
+ // Resolve and analyze this table ref so we can evaluate partition predicates.
+ TableRef tableRef = new TableRef(tableName_.toPath(), null, Privilege.ALTER);
+ tableRef = analyzer.resolveTableRef(tableRef);
+ Preconditions.checkNotNull(tableRef);
+ tableRef.analyze(analyzer);
+ if (tableRef instanceof InlineViewRef) {
+ throw new AnalysisException(String.format(
+ "ALTER TABLE not allowed on a view: %s", tableName_));
+ }
+ if (tableRef instanceof CollectionTableRef) {
+ throw new AnalysisException(String.format(
+ "ALTER TABLE not allowed on a nested collection: %s", tableName_));
+ }
+ Preconditions.checkState(tableRef instanceof BaseTableRef);
+ table_ = tableRef.getTable();
if (table_ instanceof KuduTable
&& !(this instanceof AlterTableSetTblProperties)
&& !(this instanceof AlterTableSetColumnStats)
&& !(this instanceof AlterTableOrViewRenameStmt)) {
throw new AnalysisException(String.format(
- "ALTER TABLE not allowed on Kudu table: %s", table_.getFullName()));
- }
- if (table_ instanceof View) {
- throw new AnalysisException(String.format(
- "ALTER TABLE not allowed on a view: %s", table_.getFullName()));
+ "ALTER TABLE not allowed on Kudu table: %s", tableName_));
}
if (table_ instanceof DataSourceTable
&& !(this instanceof AlterTableSetColumnStats)) {
throw new AnalysisException(String.format(
"ALTER TABLE not allowed on a table produced by a data source: %s",
- table_.getFullName()));
+ tableName_));
}
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 5a34fbc..0638bed 100644
--- a/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
+++ b/fe/src/main/java/org/apache/impala/analysis/Analyzer.java
@@ -553,11 +553,11 @@ public class Analyzer {
if (rawPath.size() > 1) {
registerPrivReq(new PrivilegeRequestBuilder()
.onTable(rawPath.get(0), rawPath.get(1))
- .allOf(Privilege.SELECT).toRequest());
+ .allOf(tableRef.getPrivilege()).toRequest());
}
registerPrivReq(new PrivilegeRequestBuilder()
.onTable(getDefaultDb(), rawPath.get(0))
- .allOf(Privilege.SELECT).toRequest());
+ .allOf(tableRef.getPrivilege()).toRequest());
}
throw e;
} catch (TableLoadingException e) {
@@ -2568,28 +2568,28 @@ public class Analyzer {
}
/**
- * Registers a table-level SELECT privilege request and an access event for auditing
- * for the given table. The given table must be a base table or a catalog view (not
- * a local view).
+ * Registers a table-level privilege request and an access event for auditing
+ * for the given table and privilege. The table must be a base table or a
+ * catalog view (not a local view).
*/
- public void registerAuthAndAuditEvent(Table table, Analyzer analyzer) {
+ public void registerAuthAndAuditEvent(Table table, Privilege priv) {
// Add access event for auditing.
if (table instanceof View) {
View view = (View) table;
Preconditions.checkState(!view.isLocalView());
- analyzer.addAccessEvent(new TAccessEvent(
+ addAccessEvent(new TAccessEvent(
table.getFullName(), TCatalogObjectType.VIEW,
- Privilege.SELECT.toString()));
+ priv.toString()));
} else {
- analyzer.addAccessEvent(new TAccessEvent(
+ addAccessEvent(new TAccessEvent(
table.getFullName(), TCatalogObjectType.TABLE,
- Privilege.SELECT.toString()));
+ priv.toString()));
}
// Add privilege request.
TableName tableName = table.getTableName();
- analyzer.registerPrivReq(new PrivilegeRequestBuilder()
+ registerPrivReq(new PrivilegeRequestBuilder()
.onTable(tableName.getDb(), tableName.getTbl())
- .allOf(Privilege.SELECT).toRequest());
+ .allOf(priv).toRequest());
}
/**
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/BaseTableRef.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/BaseTableRef.java b/fe/src/main/java/org/apache/impala/analysis/BaseTableRef.java
index fd1c455..1691315 100644
--- a/fe/src/main/java/org/apache/impala/analysis/BaseTableRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/BaseTableRef.java
@@ -58,7 +58,7 @@ public class BaseTableRef extends TableRef {
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
if (isAnalyzed_) return;
- analyzer.registerAuthAndAuditEvent(resolvedPath_.getRootTable(), analyzer);
+ analyzer.registerAuthAndAuditEvent(resolvedPath_.getRootTable(), priv_);
desc_ = analyzer.registerTableRef(this);
isAnalyzed_ = true;
analyzeHints(analyzer);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/CollectionTableRef.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/CollectionTableRef.java b/fe/src/main/java/org/apache/impala/analysis/CollectionTableRef.java
index e8abaa8..05a3543 100644
--- a/fe/src/main/java/org/apache/impala/analysis/CollectionTableRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/CollectionTableRef.java
@@ -103,7 +103,7 @@ public class CollectionTableRef extends TableRef {
// Register a table-level privilege request as well as a column-level privilege request
// for the collection-typed column.
Preconditions.checkNotNull(resolvedPath_.getRootTable());
- analyzer.registerAuthAndAuditEvent(resolvedPath_.getRootTable(), analyzer);
+ analyzer.registerAuthAndAuditEvent(resolvedPath_.getRootTable(), priv_);
analyzer.registerPrivReq(new PrivilegeRequestBuilder().
allOf(Privilege.SELECT).onColumn(desc_.getTableName().getDb(),
desc_.getTableName().getTbl(), desc_.getPath().getRawPath().get(0))
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java b/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
index 5ad3cad..7aface4 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ComputeStatsStmt.java
@@ -21,8 +21,6 @@ import java.util.Iterator;
import java.util.List;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.log4j.Logger;
-
import org.apache.impala.authorization.Privilege;
import org.apache.impala.catalog.Column;
import org.apache.impala.catalog.HBaseTable;
@@ -30,13 +28,14 @@ import org.apache.impala.catalog.HdfsPartition;
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.catalog.Table;
import org.apache.impala.catalog.Type;
-import org.apache.impala.catalog.View;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.common.PrintUtils;
import org.apache.impala.service.BackendConfig;
import org.apache.impala.thrift.TComputeStatsParams;
import org.apache.impala.thrift.TPartitionStats;
import org.apache.impala.thrift.TTableName;
+import org.apache.log4j.Logger;
+
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
@@ -99,9 +98,9 @@ public class ComputeStatsStmt extends StatementBase {
// PARTITION_ID() builtin)
private final List<List<String>> expectedPartitions_ = Lists.newArrayList();
- // If non-null, the partition that an incremental computation might apply to. Must be
+ // If non-null, partitions that an incremental computation might apply to. Must be
// null if this is a non-incremental computation.
- private PartitionSpec partitionSpec_ = null;
+ private PartitionSet partitionSet_ = null;
// The maximum number of partitions that may be explicitly selected by filter
// predicates. Any query that selects more than this automatically drops back to a full
@@ -120,20 +119,20 @@ public class ComputeStatsStmt extends StatementBase {
/**
* Constructor for the incremental form of COMPUTE STATS. If isIncremental is true,
* statistics will be recomputed incrementally; if false they will be recomputed for the
- * whole table. The partition spec partSpec can specify a single partition whose stats
- * should be recomputed.
+ * whole table. The partition set partitionSet can specify a list of partitions whose
+ * stats should be recomputed.
*/
protected ComputeStatsStmt(TableName tableName, boolean isIncremental,
- PartitionSpec partSpec) {
+ PartitionSet partitionSet) {
Preconditions.checkState(tableName != null && !tableName.isEmpty());
- Preconditions.checkState(isIncremental || partSpec == null);
+ Preconditions.checkState(isIncremental || partitionSet == null);
this.tableName_ = tableName;
this.table_ = null;
this.isIncremental_ = isIncremental;
- this.partitionSpec_ = partSpec;
- if (partitionSpec_ != null) {
- partitionSpec_.setTableName(tableName);
- partitionSpec_.setPrivilegeRequirement(Privilege.ALTER);
+ this.partitionSet_ = partitionSet;
+ if (partitionSet_ != null) {
+ partitionSet_.setTableName(tableName);
+ partitionSet_.setPrivilegeRequirement(Privilege.ALTER);
}
}
@@ -245,17 +244,25 @@ public class ComputeStatsStmt extends StatementBase {
*/
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
- table_ = analyzer.getTable(tableName_, Privilege.ALTER);
- String sqlTableName = table_.getTableName().toSql();
- if (table_ instanceof View) {
+ // Resolve and analyze this table ref so we can evaluate partition predicates.
+ TableRef tableRef = new TableRef(tableName_.toPath(), null, Privilege.ALTER);
+ tableRef = analyzer.resolveTableRef(tableRef);
+ Preconditions.checkNotNull(tableRef);
+ tableRef.analyze(analyzer);
+ if (tableRef instanceof InlineViewRef) {
+ throw new AnalysisException(String.format(
+ "COMPUTE STATS not supported for view: %s", tableName_));
+ }
+ if (tableRef instanceof CollectionTableRef) {
throw new AnalysisException(String.format(
- "COMPUTE STATS not supported for view %s", sqlTableName));
+ "COMPUTE STATS not supported for nested collection: %s", tableName_));
}
+ table_ = analyzer.getTable(tableName_, Privilege.ALTER);
if (!(table_ instanceof HdfsTable)) {
- if (partitionSpec_ != null) {
+ if (partitionSet_ != null) {
throw new AnalysisException("COMPUTE INCREMENTAL ... PARTITION not supported " +
- "for non-HDFS table " + table_.getTableName());
+ "for non-HDFS table " + tableName_);
}
isIncremental_ = false;
}
@@ -267,22 +274,14 @@ public class ComputeStatsStmt extends StatementBase {
if (table_ instanceof HdfsTable) {
hdfsTable = (HdfsTable)table_;
if (isIncremental_ && hdfsTable.getNumClusteringCols() == 0 &&
- partitionSpec_ != null) {
- throw new AnalysisException(String.format(
- "Can't compute PARTITION stats on an unpartitioned table: %s",
- sqlTableName));
- } else if (partitionSpec_ != null) {
- partitionSpec_.setPartitionShouldExist();
- partitionSpec_.analyze(analyzer);
- for (PartitionKeyValue kv: partitionSpec_.getPartitionSpecKeyValues()) {
- // TODO: We could match the dynamic keys (i.e. as wildcards) as well, but that
- // would involve looping over all partitions and seeing which match the
- // partition spec.
- if (!kv.isStatic()) {
- throw new AnalysisException("All partition keys must have values: " +
- kv.toString());
- }
- }
+ partitionSet_ != null) {
+ throw new AnalysisException(String.format(
+ "Can't compute PARTITION stats on an unpartitioned table: %s",
+ tableName_));
+ } else if (partitionSet_ != null) {
+ Preconditions.checkState(tableRef instanceof BaseTableRef);
+ partitionSet_.setPartitionShouldExist();
+ partitionSet_.analyze(analyzer);
}
// For incremental stats, estimate the size of intermediate stats and report an
// error if the estimate is greater than --inc_stats_size_limit_bytes in bytes
@@ -305,7 +304,7 @@ public class ComputeStatsStmt extends StatementBase {
// incremental computation.
List<String> filterPreds = Lists.newArrayList();
if (isIncremental_) {
- if (partitionSpec_ == null) {
+ if (partitionSet_ == null) {
// If any column does not have stats, we recompute statistics for all partitions
// TODO: need a better way to invalidate stats for all partitions, so that we can
// use this logic to only recompute new / changed columns.
@@ -355,23 +354,23 @@ public class ComputeStatsStmt extends StatementBase {
expectAllPartitions_ = true;
}
} else {
- // Always compute stats on a particular partition when told to.
+ List<HdfsPartition> targetPartitions = partitionSet_.getPartitions();
+
+ // Always compute stats on a set of partitions when told to.
List<String> partitionConjuncts = Lists.newArrayList();
- for (PartitionKeyValue kv: partitionSpec_.getPartitionSpecKeyValues()) {
- partitionConjuncts.add(kv.toPredicateSql());
+ for (HdfsPartition targetPartition : targetPartitions) {
+ partitionConjuncts.add(targetPartition.getConjunctSql());
+ List<String> partValues = Lists.newArrayList();
+ for (LiteralExpr partValue: targetPartition.getPartitionValues()) {
+ partValues.add(PartitionKeyValue.getPartitionKeyValueString(partValue,
+ "NULL"));
+ }
+ expectedPartitions_.add(partValues);
}
filterPreds.add("(" + Joiner.on(" AND ").join(partitionConjuncts) + ")");
- HdfsPartition targetPartition =
- hdfsTable.getPartition(partitionSpec_.getPartitionSpecKeyValues());
- List<String> partValues = Lists.newArrayList();
- for (LiteralExpr partValue: targetPartition.getPartitionValues()) {
- partValues.add(PartitionKeyValue.getPartitionKeyValueString(partValue,
- "NULL"));
- }
- expectedPartitions_.add(partValues);
- for (HdfsPartition p: hdfsTable.getPartitions()) {
+ for (HdfsPartition p : hdfsTable.getPartitions()) {
if (p.isDefaultPartition()) continue;
- if (p == targetPartition) continue;
+ if (targetPartitions.contains(p)) continue;
TPartitionStats partStats = p.getPartitionStats();
if (partStats != null) validPartStats_.add(partStats);
}
@@ -408,7 +407,7 @@ public class ComputeStatsStmt extends StatementBase {
tableStatsSelectList.addAll(partitionColsSelectList);
tableStatsQueryBuilder.append(Joiner.on(", ").join(tableStatsSelectList));
- tableStatsQueryBuilder.append(" FROM " + sqlTableName);
+ tableStatsQueryBuilder.append(" FROM " + tableName_.toSql());
// Query for getting the per-column NDVs and number of NULLs.
List<String> columnStatsSelectList = getBaseColumnStatsQuerySelectList(analyzer);
@@ -417,7 +416,7 @@ public class ComputeStatsStmt extends StatementBase {
StringBuilder columnStatsQueryBuilder = new StringBuilder("SELECT ");
columnStatsQueryBuilder.append(Joiner.on(", ").join(columnStatsSelectList));
- columnStatsQueryBuilder.append(" FROM " + sqlTableName);
+ columnStatsQueryBuilder.append(" FROM " + tableName_.toSql());
// Add the WHERE clause to filter out partitions that we don't want to compute
// incremental stats for. While this is a win in most situations, we would like to
@@ -426,7 +425,7 @@ public class ComputeStatsStmt extends StatementBase {
// selected in) and there is no partition spec (so no single partition was explicitly
// selected in).
if (filterPreds.size() > 0 &&
- (validPartStats_.size() > 0 || partitionSpec_ != null)) {
+ (validPartStats_.size() > 0 || partitionSet_ != null)) {
String filterClause = " WHERE " + Joiner.on(" OR ").join(filterPreds);
columnStatsQueryBuilder.append(filterClause);
tableStatsQueryBuilder.append(filterClause);
@@ -529,7 +528,7 @@ public class ComputeStatsStmt extends StatementBase {
return "COMPUTE STATS " + tableName_.toSql();
} else {
return "COMPUTE INCREMENTAL STATS " + tableName_.toSql() +
- partitionSpec_ == null ? "" : partitionSpec_.toSql();
+ partitionSet_ == null ? "" : partitionSet_.toSql();
}
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/DropStatsStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/DropStatsStmt.java b/fe/src/main/java/org/apache/impala/analysis/DropStatsStmt.java
index fe2ff84..e39071f 100644
--- a/fe/src/main/java/org/apache/impala/analysis/DropStatsStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/DropStatsStmt.java
@@ -18,10 +18,10 @@
package org.apache.impala.analysis;
import org.apache.impala.authorization.Privilege;
-import org.apache.impala.catalog.Table;
import org.apache.impala.common.AnalysisException;
import org.apache.impala.thrift.TDropStatsParams;
import org.apache.impala.thrift.TTableName;
+
import com.google.common.base.Preconditions;
/**
@@ -31,28 +31,29 @@ import com.google.common.base.Preconditions;
public class DropStatsStmt extends StatementBase {
protected final TableName tableName_;
- // If non-null, only drop the statistics for a given partition
- PartitionSpec partitionSpec_ = null;
-
// Set during analysis
- protected String dbName_;
+ protected TableRef tableRef_;
+
+ // If non-null, only drop the statistics for a given partition
+ private final PartitionSet partitionSet_;
/**
* Constructor for building the DROP TABLE/VIEW statement
*/
public DropStatsStmt(TableName tableName) {
this.tableName_ = tableName;
+ this.partitionSet_ = null;
}
- public DropStatsStmt(TableName tableName, PartitionSpec partSpec) {
+ public DropStatsStmt(TableName tableName, PartitionSet partitionSet) {
this.tableName_ = tableName;
- this.partitionSpec_ = partSpec;
+ this.partitionSet_ = partitionSet;
}
@Override
public String toSql() {
StringBuilder sb = new StringBuilder("DROP ");
- if (partitionSpec_ == null) {
+ if (partitionSet_ == null) {
sb.append(" STATS ");
if (tableName_.getDb() != null) sb.append(tableName_.getDb() + ".");
sb.append(tableName_.toSql());
@@ -60,7 +61,7 @@ public class DropStatsStmt extends StatementBase {
sb.append(" INCREMENTAL STATS ");
if (tableName_.getDb() != null) sb.append(tableName_.getDb() + ".");
sb.append(tableName_.toSql());
- sb.append(partitionSpec_.toSql());
+ sb.append(partitionSet_.toSql());
}
return sb.toString();
}
@@ -68,9 +69,8 @@ public class DropStatsStmt extends StatementBase {
public TDropStatsParams toThrift() {
TDropStatsParams params = new TDropStatsParams();
params.setTable_name(new TTableName(getDb(), getTbl()));
-
- if (partitionSpec_ != null) {
- params.setPartition_spec(partitionSpec_.toThrift());
+ if (partitionSet_ != null) {
+ params.setPartition_set(partitionSet_.toThrift());
}
return params;
}
@@ -81,14 +81,25 @@ public class DropStatsStmt extends StatementBase {
*/
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
- dbName_ = analyzer.getTargetDbName(tableName_);
- Table table = analyzer.getTable(tableName_, Privilege.ALTER);
- Preconditions.checkNotNull(table);
- if (partitionSpec_ != null) {
- partitionSpec_.setTableName(tableName_);
- partitionSpec_.setPrivilegeRequirement(Privilege.ALTER);
- partitionSpec_.setPartitionShouldExist();
- partitionSpec_.analyze(analyzer);
+ // Resolve and analyze table ref to register privilege and audit events
+ // and to allow us to evaluate partition predicates.
+ tableRef_ = new TableRef(tableName_.toPath(), null, Privilege.ALTER);
+ tableRef_ = analyzer.resolveTableRef(tableRef_);
+ Preconditions.checkNotNull(tableRef_);
+ if (tableRef_ instanceof InlineViewRef) {
+ throw new AnalysisException(
+ String.format("DROP STATS not allowed on a view: %s", tableName_));
+ }
+ if (tableRef_ instanceof CollectionTableRef) {
+ throw new AnalysisException(
+ String.format("DROP STATS not allowed on a nested collection: %s", tableName_));
+ }
+ tableRef_.analyze(analyzer);
+ if (partitionSet_ != null) {
+ partitionSet_.setTableName(tableRef_.getTable().getTableName());
+ partitionSet_.setPrivilegeRequirement(Privilege.ALTER);
+ partitionSet_.setPartitionShouldExist();
+ partitionSet_.analyze(analyzer);
}
}
@@ -97,8 +108,8 @@ public class DropStatsStmt extends StatementBase {
* the target drop table resides in.
*/
public String getDb() {
- Preconditions.checkNotNull(dbName_);
- return dbName_;
+ Preconditions.checkNotNull(tableRef_);
+ return tableRef_.getTable().getDb().getName();
}
public String getTbl() { return tableName_.getTbl(); }
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 3ee2070..42f9400 100644
--- a/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/InlineViewRef.java
@@ -93,7 +93,8 @@ public class InlineViewRef extends TableRef {
* C'tor for creating inline views that replace a local or catalog view ref.
*/
public InlineViewRef(View view, TableRef origTblRef) {
- super(view.getTableName().toPath(), origTblRef.getExplicitAlias());
+ super(view.getTableName().toPath(), origTblRef.getExplicitAlias(),
+ origTblRef.getPrivilege());
queryStmt_ = view.getQueryStmt().clone();
queryStmt_.reset();
if (view.isLocalView()) queryStmt_.reset();
@@ -142,7 +143,7 @@ public class InlineViewRef extends TableRef {
// Catalog views refs require special analysis settings for authorization.
boolean isCatalogView = (view_ != null && !view_.isLocalView());
if (isCatalogView) {
- analyzer.registerAuthAndAuditEvent(view_, analyzer);
+ analyzer.registerAuthAndAuditEvent(view_, priv_);
if (inlineViewAnalyzer_.isExplain()) {
// If the user does not have privileges on the view's definition
// then we report a masked authorization error so as not to reveal
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/PartitionSet.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/PartitionSet.java b/fe/src/main/java/org/apache/impala/analysis/PartitionSet.java
new file mode 100644
index 0000000..b41f2f9
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/analysis/PartitionSet.java
@@ -0,0 +1,199 @@
+// 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 java.util.Set;
+
+import org.apache.impala.analysis.BinaryPredicate.Operator;
+import org.apache.impala.catalog.Column;
+import org.apache.impala.catalog.HdfsPartition;
+import org.apache.impala.catalog.Table;
+import org.apache.impala.common.AnalysisException;
+import org.apache.impala.common.InternalException;
+import org.apache.impala.common.Reference;
+import org.apache.impala.planner.HdfsPartitionPruner;
+import org.apache.impala.thrift.TPartitionKeyValue;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+import com.google.common.collect.Sets;
+
+/**
+ * Represents a set of partitions resulting from evaluating a list of partition conjuncts
+ * against a table's partition list.
+ */
+public class PartitionSet extends PartitionSpecBase {
+ private final List<Expr> partitionExprs_;
+
+ // Result of analysis
+ private List<HdfsPartition> partitions_ = Lists.newArrayList();
+
+ public PartitionSet(List<Expr> partitionExprs) {
+ this.partitionExprs_ = ImmutableList.copyOf(partitionExprs);
+ }
+
+ public List<HdfsPartition> getPartitions() { return partitions_; }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException {
+ super.analyze(analyzer);
+ List<Expr> conjuncts = Lists.newArrayList();
+ // Do not register column-authorization requests.
+ analyzer.setEnablePrivChecks(false);
+ for (Expr e: partitionExprs_) {
+ e.analyze(analyzer);
+ e.checkReturnsBool("Partition expr", false);
+ conjuncts.addAll(e.getConjuncts());
+ }
+
+ TupleDescriptor desc = analyzer.getDescriptor(tableName_.toString());
+ List<SlotId> partitionSlots = desc.getPartitionSlots();
+ for (Expr e: conjuncts) {
+ e.foldConstantChildren(analyzer);
+ // Make sure there are no constant predicates in the partition exprs.
+ if (e.isConstant()) {
+ throw new AnalysisException(String.format("Invalid partition expr %s. A " +
+ "partition spec may not contain constant predicates.", e.toSql()));
+ }
+
+ // Make sure every conjunct only contains partition slot refs.
+ if(!e.isBoundBySlotIds(partitionSlots)) {
+ throw new AnalysisException("Partition exprs cannot contain non-partition " +
+ "column(s): " + e.toSql() + ".");
+ }
+ }
+
+ List<Expr> transformedConjuncts = transformPartitionConjuncts(analyzer, conjuncts);
+ addIfExists(analyzer, table_, transformedConjuncts);
+
+ try {
+ HdfsPartitionPruner pruner = new HdfsPartitionPruner(desc);
+ partitions_ = pruner.prunePartitions(analyzer, transformedConjuncts, true);
+ } catch (InternalException e) {
+ throw new AnalysisException("Partition expr evaluation failed in the backend.", e);
+ }
+
+ if (partitionShouldExist_ != null) {
+ if (partitionShouldExist_ && partitions_.isEmpty()) {
+ throw new AnalysisException("No matching partition(s) found.");
+ } else if (!partitionShouldExist_ && !partitions_.isEmpty()) {
+ throw new AnalysisException("Partition already exists.");
+ }
+ }
+ analyzer.setEnablePrivChecks(true);
+ }
+
+ // Check if we should add IF EXISTS. Fully-specified partition specs don't add it for
+ // backwards compatibility, while more general partition expressions or partially
+ // specified partition specs add IF EXISTS by setting partitionShouldExists_ to null.
+ // The given conjuncts are assumed to only reference partition columns.
+ private void addIfExists(
+ Analyzer analyzer, Table table, List<Expr> conjuncts) {
+ boolean add = false;
+ Set<String> partColNames = Sets.newHashSet();
+ Reference<SlotRef> slotRef = new Reference<>();
+ for (Expr e : conjuncts) {
+ if (e instanceof BinaryPredicate) {
+ BinaryPredicate bp = (BinaryPredicate) e;
+ if (bp.getOp() != Operator.EQ || !bp.isSingleColumnPredicate(slotRef, null)) {
+ add = true;
+ break;
+ }
+ Column partColumn = slotRef.getRef().getDesc().getColumn();
+ Preconditions.checkState(table.isClusteringColumn(partColumn));
+ partColNames.add(partColumn.getName());
+ } else if (e instanceof IsNullPredicate) {
+ IsNullPredicate nullPredicate = (IsNullPredicate) e;
+ Column partColumn = nullPredicate.getBoundSlot().getDesc().getColumn();
+ Preconditions.checkState(table.isClusteringColumn(partColumn));
+ partColNames.add(partColumn.getName());
+ } else {
+ add = true;
+ break;
+ }
+ }
+
+ if (add || partColNames.size() < table.getNumClusteringCols()) {
+ partitionShouldExist_ = null;
+ }
+ }
+
+ // Transform <COL> = NULL into IsNull expr; <String COL> = '' into IsNull expr and
+ // <String COL> = 'String Value' into lower case.
+ // The reason is that COL = NULL is allowed for selecting the NULL
+ // partition, but a COL = NULL predicate can never be true, so we
+ // need to transform such predicates before feeding them into the
+ // partition pruner. Same logic goes to String transformation.
+ private List<Expr> transformPartitionConjuncts(Analyzer analyzer, List<Expr> conjuncts)
+ throws AnalysisException {
+ List<Expr> transformedConjuncts = Lists.newArrayList();
+ for (Expr e : conjuncts) {
+ Expr result = e;
+ if (e instanceof BinaryPredicate) {
+ BinaryPredicate bp = ((BinaryPredicate) e);
+ if (bp.getOp() == Operator.EQ) {
+ SlotRef leftChild =
+ bp.getChild(0) instanceof SlotRef ? ((SlotRef) bp.getChild(0)) : null;
+ NullLiteral nullChild = bp.getChild(1) instanceof NullLiteral ?
+ ((NullLiteral) bp.getChild(1)) : null;
+ StringLiteral stringChild = bp.getChild(1) instanceof StringLiteral ?
+ ((StringLiteral) bp.getChild(1)) : null;
+ if (leftChild != null && nullChild != null) {
+ result = new IsNullPredicate(leftChild, false);
+ } else if (leftChild != null && stringChild != null) {
+ if (stringChild.getStringValue().isEmpty()) {
+ result = new IsNullPredicate(leftChild, false);
+ } else {
+ stringChild = new StringLiteral(stringChild.getStringValue().toLowerCase());
+ result.setChild(1, stringChild);
+ }
+ }
+ }
+ }
+ result.analyze(analyzer);
+ transformedConjuncts.add(result);
+ }
+ return transformedConjuncts;
+ }
+
+ public List<List<TPartitionKeyValue>> toThrift() {
+ List<List<TPartitionKeyValue>> thriftPartitionSet = Lists.newArrayList();
+ for (HdfsPartition hdfsPartition : partitions_) {
+ List<TPartitionKeyValue> thriftPartitionSpec = Lists.newArrayList();
+ for (int i = 0; i < table_.getNumClusteringCols(); ++i) {
+ String key = table_.getColumns().get(i).getName();
+ String value = PartitionKeyValue.getPartitionKeyValueString(
+ hdfsPartition.getPartitionValue(i), nullPartitionKeyValue_);
+ thriftPartitionSpec.add(new TPartitionKeyValue(key, value));
+ }
+ thriftPartitionSet.add(thriftPartitionSpec);
+ }
+ return thriftPartitionSet;
+ }
+
+ @Override
+ public String toSql() {
+ List<String> partitionExprStr = Lists.newArrayList();
+ for (Expr e : partitionExprs_) {
+ partitionExprStr.add(e.toSql());
+ }
+ return String.format("PARTITION (%s)", Joiner.on(", ").join(partitionExprStr));
+ }
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/PartitionSpec.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/PartitionSpec.java b/fe/src/main/java/org/apache/impala/analysis/PartitionSpec.java
index 39cc1bb..b89e586 100644
--- a/fe/src/main/java/org/apache/impala/analysis/PartitionSpec.java
+++ b/fe/src/main/java/org/apache/impala/analysis/PartitionSpec.java
@@ -38,20 +38,13 @@ import com.google.common.collect.Sets;
/*
* Represents a partition spec - a collection of partition key/values.
*/
-public class PartitionSpec implements ParseNode {
+public class PartitionSpec extends PartitionSpecBase {
private final ImmutableList<PartitionKeyValue> partitionSpec_;
- private TableName tableName_;
- private Boolean partitionShouldExist_;
- private Privilege privilegeRequirement_;
// Flag to determine if the partition already exists in the target table.
// Set during analysis.
private Boolean partitionExists_;
- // The value Hive is configured to use for NULL partition key values.
- // Set during analysis.
- private String nullPartitionKeyValue_;
-
public PartitionSpec(List<PartitionKeyValue> partitionSpec) {
this.partitionSpec_ = ImmutableList.copyOf(partitionSpec);
}
@@ -60,48 +53,14 @@ public class PartitionSpec implements ParseNode {
return partitionSpec_;
}
- public String getTbl() { return tableName_.getTbl(); }
- public void setTableName(TableName tableName) { this.tableName_ = tableName; }
public boolean partitionExists() {
Preconditions.checkNotNull(partitionExists_);
return partitionExists_;
}
- // The value Hive is configured to use for NULL partition key values.
- // Set during analysis.
- public String getNullPartitionKeyValue() {
- Preconditions.checkNotNull(nullPartitionKeyValue_);
- return nullPartitionKeyValue_;
- }
-
- // If set, an additional analysis check will be performed to validate the target table
- // contains the given partition spec.
- public void setPartitionShouldExist() { partitionShouldExist_ = Boolean.TRUE; }
-
- // If set, an additional analysis check will be performed to validate the target table
- // does not contain the given partition spec.
- public void setPartitionShouldNotExist() { partitionShouldExist_ = Boolean.FALSE; }
-
- // Set the privilege requirement for this partition spec. Must be set prior to
- // analysis.
- public void setPrivilegeRequirement(Privilege privilege) {
- privilegeRequirement_ = privilege;
- }
-
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
- Preconditions.checkNotNull(tableName_);
- Preconditions.checkNotNull(privilegeRequirement_);
-
- // Skip adding an audit event when analyzing partitions. The parent table should
- // be audited outside of the PartitionSpec.
- Table table = analyzer.getTable(tableName_, privilegeRequirement_, false);
- String tableName = table.getDb().getName() + "." + getTbl();
-
- // Make sure the target table is partitioned.
- if (table.getMetaStoreTable().getPartitionKeysSize() == 0) {
- throw new AnalysisException("Table is not partitioned: " + tableName);
- }
+ super.analyze(analyzer);
// Make sure static partition key values only contain constant exprs.
for (PartitionKeyValue kv: partitionSpec_) {
@@ -110,7 +69,7 @@ public class PartitionSpec implements ParseNode {
// Get all keys in the target table.
Set<String> targetPartitionKeys = Sets.newHashSet();
- for (FieldSchema fs: table.getMetaStoreTable().getPartitionKeys()) {
+ for (FieldSchema fs: table_.getMetaStoreTable().getPartitionKeys()) {
targetPartitionKeys.add(fs.getName().toLowerCase());
}
@@ -118,7 +77,7 @@ public class PartitionSpec implements ParseNode {
if (targetPartitionKeys.size() != partitionSpec_.size()) {
throw new AnalysisException(String.format("Items in partition spec must exactly " +
"match the partition columns in the table definition: %s (%d vs %d)",
- tableName, partitionSpec_.size(), targetPartitionKeys.size()));
+ tableName_, partitionSpec_.size(), targetPartitionKeys.size()));
}
Set<String> keyNames = Sets.newHashSet();
@@ -130,14 +89,14 @@ public class PartitionSpec implements ParseNode {
throw new AnalysisException("Duplicate partition key name: " + pk.getColName());
}
- Column c = table.getColumn(pk.getColName());
+ Column c = table_.getColumn(pk.getColName());
if (c == null) {
throw new AnalysisException(String.format(
- "Partition column '%s' not found in table: %s", pk.getColName(), tableName));
+ "Partition column '%s' not found in table: %s", pk.getColName(), tableName_));
} else if (!targetPartitionKeys.contains(pk.getColName().toLowerCase())) {
throw new AnalysisException(String.format(
"Column '%s' is not a partition column in table: %s",
- pk.getColName(), tableName));
+ pk.getColName(), tableName_));
} else if (pk.getValue() instanceof NullLiteral) {
// No need for further analysis checks of this partition key value.
continue;
@@ -160,12 +119,7 @@ public class PartitionSpec implements ParseNode {
pk.getValue().toSql(), colType.toString(), pk.getColName()));
}
}
- // Only HDFS tables are partitioned.
- Preconditions.checkState(table instanceof HdfsTable);
- HdfsTable hdfsTable = (HdfsTable) table;
- nullPartitionKeyValue_ = hdfsTable.getNullPartitionKeyValue();
-
- partitionExists_ = hdfsTable.getPartition(partitionSpec_) != null;
+ partitionExists_ = table_.getPartition(partitionSpec_) != null;
if (partitionShouldExist_ != null) {
if (partitionShouldExist_ && !partitionExists_) {
throw new AnalysisException("Partition spec does not exist: (" +
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/PartitionSpecBase.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/PartitionSpecBase.java b/fe/src/main/java/org/apache/impala/analysis/PartitionSpecBase.java
new file mode 100644
index 0000000..7d9a800
--- /dev/null
+++ b/fe/src/main/java/org/apache/impala/analysis/PartitionSpecBase.java
@@ -0,0 +1,94 @@
+// 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 com.cloudera.impala.analysis;
+
+package org.apache.impala.analysis;
+
+import org.apache.impala.authorization.Privilege;
+import org.apache.impala.catalog.Table;
+import org.apache.impala.catalog.HdfsTable;
+import org.apache.impala.common.AnalysisException;
+import com.google.common.base.Preconditions;
+
+/**
+ * Base class for PartitionSpec and PartitionSet containing the partition
+ * specifications of related DDL operations.
+ */
+public abstract class PartitionSpecBase implements ParseNode {
+ protected HdfsTable table_;
+ protected TableName tableName_;
+ protected Boolean partitionShouldExist_;
+ protected Privilege privilegeRequirement_;
+ // The value Hive is configured to use for NULL partition key values.
+ // Set during analysis.
+ protected String nullPartitionKeyValue_;
+
+ public String getTbl() { return tableName_.getTbl(); }
+
+ public void setTableName(TableName tableName) {this.tableName_ = tableName; }
+
+ // The value Hive is configured to use for NULL partition key values.
+ // Set during analysis.
+ public String getNullPartitionKeyValue() {
+ Preconditions.checkNotNull(nullPartitionKeyValue_);
+ return nullPartitionKeyValue_;
+ }
+
+ // If set, an additional analysis check will be performed to validate the target table
+ // contains the given partition spec.
+ public void setPartitionShouldExist() { partitionShouldExist_ = Boolean.TRUE; }
+
+ // If set, an additional analysis check will be performed to validate the target table
+ // does not contain the given partition spec.
+ public void setPartitionShouldNotExist() { partitionShouldExist_ = Boolean.FALSE; }
+
+ public boolean getPartitionShouldExist() {
+ return partitionShouldExist_ != null && partitionShouldExist_;
+ }
+
+ public boolean getPartitionShouldNotExist() {
+ return partitionShouldExist_ != null && !partitionShouldExist_;
+ }
+
+ // Set the privilege requirement for this partition spec. Must be set prior to
+ // analysis.
+ public void setPrivilegeRequirement(Privilege privilege) {
+ privilegeRequirement_ = privilege;
+ }
+
+ @Override
+ public void analyze(Analyzer analyzer) throws AnalysisException {
+ Preconditions.checkNotNull(tableName_);
+ Preconditions.checkNotNull(privilegeRequirement_);
+
+ // Skip adding an audit event when analyzing partitions. The parent table should
+ // be audited outside of the PartitionSpec.
+ Table table = analyzer.getTable(tableName_, privilegeRequirement_, false);
+
+ // Make sure the target table is partitioned.
+ if (table.getMetaStoreTable().getPartitionKeysSize() == 0) {
+ throw new AnalysisException("Table is not partitioned: " + tableName_);
+ }
+
+ // Only HDFS tables are partitioned.
+ Preconditions.checkState(table instanceof HdfsTable);
+ table_ = (HdfsTable) table;
+ nullPartitionKeyValue_ = table_.getNullPartitionKeyValue();
+ }
+
+ @Override
+ public abstract String toSql();
+}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/fe/src/main/java/org/apache/impala/analysis/ShowFilesStmt.java
----------------------------------------------------------------------
diff --git a/fe/src/main/java/org/apache/impala/analysis/ShowFilesStmt.java b/fe/src/main/java/org/apache/impala/analysis/ShowFilesStmt.java
index bec1ed3..d102bb9 100644
--- a/fe/src/main/java/org/apache/impala/analysis/ShowFilesStmt.java
+++ b/fe/src/main/java/org/apache/impala/analysis/ShowFilesStmt.java
@@ -27,8 +27,6 @@ import org.apache.impala.catalog.Table;
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.thrift.TTableName;
import com.google.common.base.Preconditions;
-import com.google.common.base.Joiner;
-import com.google.common.collect.Lists;
/**
* Representation of a SHOW FILES statement.
@@ -38,52 +36,60 @@ import com.google.common.collect.Lists;
*
*/
public class ShowFilesStmt extends StatementBase {
- private TableName tableName_;
+ private final TableName tableName_;
// Show files for all the partitions if this is null.
- private final PartitionSpec partitionSpec_;
+ private final PartitionSet partitionSet_;
// Set during analysis.
protected Table table_;
- public ShowFilesStmt(TableName tableName, PartitionSpec partitionSpec) {
+ public ShowFilesStmt(TableName tableName, PartitionSet partitionSet) {
this.tableName_ = tableName;
- this.partitionSpec_ = partitionSpec;
+ this.partitionSet_ = partitionSet;
}
@Override
public String toSql() {
StringBuilder strBuilder = new StringBuilder();
strBuilder.append("SHOW FILES IN " + tableName_.toString());
- if (partitionSpec_ != null) strBuilder.append(" " + partitionSpec_.toSql());
+ if (partitionSet_ != null) strBuilder.append(" " + partitionSet_.toSql());
return strBuilder.toString();
}
@Override
public void analyze(Analyzer analyzer) throws AnalysisException {
- if (!tableName_.isFullyQualified()) {
- tableName_ = new TableName(analyzer.getDefaultDb(), tableName_.getTbl());
+ // Resolve and analyze table ref to register privilege and audit events
+ // and to allow us to evaluate partition predicates.
+ TableRef tableRef = new TableRef(tableName_.toPath(), null, Privilege.VIEW_METADATA);
+ tableRef = analyzer.resolveTableRef(tableRef);
+ if (tableRef instanceof InlineViewRef ||
+ tableRef instanceof CollectionTableRef) {
+ throw new AnalysisException(String.format(
+ "SHOW FILES not applicable to a non hdfs table: %s", tableName_));
}
- table_ = analyzer.getTable(tableName_, Privilege.VIEW_METADATA);
+ table_ = tableRef.getTable();
+ Preconditions.checkNotNull(table_);
if (!(table_ instanceof HdfsTable)) {
throw new AnalysisException(String.format(
- "SHOW FILES not applicable to a non hdfs table: %s", table_.getFullName()));
+ "SHOW FILES not applicable to a non hdfs table: %s", tableName_));
}
+ tableRef.analyze(analyzer);
// Analyze the partition spec, if one was specified.
- if (partitionSpec_ != null) {
- partitionSpec_.setTableName(tableName_);
- partitionSpec_.setPartitionShouldExist();
- partitionSpec_.setPrivilegeRequirement(Privilege.VIEW_METADATA);
- partitionSpec_.analyze(analyzer);
+ if (partitionSet_ != null) {
+ partitionSet_.setTableName(table_.getTableName());
+ partitionSet_.setPartitionShouldExist();
+ partitionSet_.setPrivilegeRequirement(Privilege.VIEW_METADATA);
+ partitionSet_.analyze(analyzer);
}
}
public TShowFilesParams toThrift() {
TShowFilesParams params = new TShowFilesParams();
- params.setTable_name(new TTableName(tableName_.getDb(), tableName_.getTbl()));
- if (partitionSpec_ != null) {
- params.setPartition_spec(partitionSpec_.toThrift());
+ params.setTable_name(new TTableName(table_.getDb().getName(), table_.getName()));
+ if (partitionSet_ != null) {
+ params.setPartition_set(partitionSet_.toThrift());
}
return params;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/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 6403091..d6bbfd2 100644
--- a/fe/src/main/java/org/apache/impala/analysis/TableRef.java
+++ b/fe/src/main/java/org/apache/impala/analysis/TableRef.java
@@ -22,6 +22,7 @@ import java.util.Collections;
import java.util.List;
import java.util.Set;
+import org.apache.impala.authorization.Privilege;
import org.apache.impala.catalog.HdfsTable;
import org.apache.impala.catalog.Table;
import org.apache.impala.common.AnalysisException;
@@ -77,6 +78,9 @@ public class TableRef implements ParseNode {
// Indicates whether this table ref is given an explicit alias,
protected boolean hasExplicitAlias_;
+ // Analysis registers privilege and/or audit requests based on this privilege.
+ protected final Privilege priv_;
+
protected JoinOperator joinOp_;
protected ArrayList<String> joinHints_;
protected List<String> usingColNames_;
@@ -125,7 +129,10 @@ public class TableRef implements ParseNode {
/////////////////////////////////////////
public TableRef(List<String> path, String alias) {
- super();
+ this(path, alias, Privilege.SELECT);
+ }
+
+ public TableRef(List<String> path, String alias, Privilege priv) {
rawPath_ = path;
if (alias != null) {
aliases_ = new String[] { alias.toLowerCase() };
@@ -133,6 +140,7 @@ public class TableRef implements ParseNode {
} else {
hasExplicitAlias_ = false;
}
+ priv_ = priv;
isAnalyzed_ = false;
replicaPreference_ = null;
randomReplica_ = false;
@@ -146,6 +154,7 @@ public class TableRef implements ParseNode {
resolvedPath_ = other.resolvedPath_;
aliases_ = other.aliases_;
hasExplicitAlias_ = other.hasExplicitAlias_;
+ priv_ = other.priv_;
joinOp_ = other.joinOp_;
joinHints_ =
(other.joinHints_ != null) ? Lists.newArrayList(other.joinHints_) : null;
@@ -252,6 +261,7 @@ public class TableRef implements ParseNode {
Preconditions.checkNotNull(resolvedPath_);
return resolvedPath_.getRootTable();
}
+ public Privilege getPrivilege() { return priv_; }
public ArrayList<String> getJoinHints() { return joinHints_; }
public ArrayList<String> getTableHints() { return tableHints_; }
public Expr getOnClause() { return onClause_; }
[50/50] [abbrv] incubator-impala git commit: Merge remote-tracking
branch 'origin/master' into hadoop-next
Posted by ta...@apache.org.
Merge remote-tracking branch 'origin/master' into hadoop-next
Change-Id: I493d811bb72949f315fd131ae7cbf886a3d0efd5
Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/32dfcebf
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/32dfcebf
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/32dfcebf
Branch: refs/heads/hadoop-next
Commit: 32dfcebfa2316316daa9ec901009084e5b3a7ad3
Parents: eae4f30 0a654b3
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Wed Nov 16 13:23:01 2016 -0800
Committer: Tim Armstrong <ta...@cloudera.com>
Committed: Thu Nov 17 08:07:40 2016 -0800
----------------------------------------------------------------------
.clang-tidy | 94 ++
.gitignore | 1 -
CMakeLists.txt | 3 +-
EXPORT_CONTROL.md | 45 +
README.md | 7 +-
be/CMakeLists.txt | 20 +-
be/generated-sources/gen-cpp/CMakeLists.txt | 2 +
be/src/benchmarks/bloom-filter-benchmark.cc | 179 +--
be/src/benchmarks/expr-benchmark.cc | 2 +-
be/src/benchmarks/hash-benchmark.cc | 2 +-
be/src/benchmarks/in-predicate-benchmark.cc | 8 +-
be/src/benchmarks/parse-timestamp-benchmark.cc | 15 -
be/src/catalog/catalog-server.cc | 2 +-
be/src/catalog/catalog-server.h | 2 +-
be/src/catalog/catalog.cc | 23 +-
be/src/codegen/codegen-anyval.cc | 64 +-
be/src/codegen/codegen-anyval.h | 55 +-
be/src/codegen/gen_ir_descriptions.py | 8 +-
be/src/codegen/impala-ir.cc | 6 +
be/src/codegen/llvm-codegen-test.cc | 16 +-
be/src/codegen/llvm-codegen.cc | 56 +-
be/src/codegen/llvm-codegen.h | 43 +-
be/src/common/compiler-util.h | 3 -
be/src/common/global-flags.cc | 14 +
be/src/common/init.cc | 2 +-
be/src/common/logging.h | 5 -
be/src/common/status.h | 10 +-
be/src/exec/aggregation-node.cc | 78 +-
be/src/exec/analytic-eval-node.cc | 32 +-
be/src/exec/analytic-eval-node.h | 6 +-
be/src/exec/base-sequence-scanner.cc | 8 +-
be/src/exec/data-sink.cc | 17 +-
be/src/exec/data-sink.h | 9 +-
be/src/exec/delimited-text-parser.cc | 12 +-
be/src/exec/delimited-text-parser.h | 62 +-
be/src/exec/exec-node.cc | 4 +-
be/src/exec/exec-node.h | 8 +-
be/src/exec/external-data-source-executor.h | 2 +-
be/src/exec/hash-join-node.cc | 12 +-
be/src/exec/hash-table-test.cc | 2 +-
be/src/exec/hash-table.cc | 42 +-
be/src/exec/hbase-scan-node.h | 2 +-
be/src/exec/hdfs-avro-scanner.cc | 45 +-
be/src/exec/hdfs-parquet-scanner.cc | 91 +-
be/src/exec/hdfs-parquet-scanner.h | 7 +-
be/src/exec/hdfs-parquet-table-writer.cc | 4 +-
be/src/exec/hdfs-rcfile-scanner.cc | 9 +-
be/src/exec/hdfs-rcfile-scanner.h | 4 +-
be/src/exec/hdfs-scan-node-base.cc | 28 +-
be/src/exec/hdfs-scan-node-base.h | 11 +-
be/src/exec/hdfs-scan-node.cc | 1 -
be/src/exec/hdfs-scan-node.h | 5 -
be/src/exec/hdfs-scanner.cc | 15 +-
be/src/exec/hdfs-scanner.h | 13 +-
be/src/exec/hdfs-sequence-scanner.cc | 2 +-
be/src/exec/hdfs-table-sink.cc | 2 +-
be/src/exec/hdfs-table-writer.h | 2 +-
be/src/exec/hdfs-text-scanner.cc | 10 +-
be/src/exec/kudu-scan-node.cc | 10 +-
be/src/exec/kudu-scan-node.h | 4 +-
be/src/exec/kudu-scanner.cc | 188 +--
be/src/exec/kudu-scanner.h | 28 -
be/src/exec/kudu-table-sink.cc | 112 +-
be/src/exec/kudu-table-sink.h | 36 +-
be/src/exec/kudu-util.cc | 11 +
be/src/exec/kudu-util.h | 5 +
be/src/exec/nested-loop-join-builder.cc | 2 +-
be/src/exec/nested-loop-join-node.cc | 2 +-
be/src/exec/old-hash-table.cc | 10 +-
be/src/exec/parquet-column-readers.h | 2 +-
be/src/exec/partitioned-aggregation-node-ir.cc | 2 +-
be/src/exec/partitioned-aggregation-node.cc | 670 ++++++-----
be/src/exec/partitioned-aggregation-node.h | 25 +-
be/src/exec/partitioned-hash-join-builder-ir.cc | 4 +-
be/src/exec/partitioned-hash-join-builder.cc | 14 +-
be/src/exec/partitioned-hash-join-node.cc | 46 +-
be/src/exec/plan-root-sink.cc | 5 +-
be/src/exec/plan-root-sink.h | 25 +-
be/src/exec/scanner-context.cc | 2 +-
be/src/exec/scanner-context.inline.h | 3 +-
be/src/exec/text-converter.cc | 12 +-
be/src/exec/union-node.cc | 192 ++-
be/src/exec/union-node.h | 36 +-
be/src/exec/write-stream.h | 2 +-
.../experiments/bit-stream-utils.8byte.inline.h | 4 +-
be/src/experiments/tuple-splitter-test.cc | 1 -
be/src/exprs/agg-fn-evaluator.cc | 29 +-
be/src/exprs/aggregate-functions-ir.cc | 60 +-
be/src/exprs/aggregate-functions.h | 9 +-
be/src/exprs/anyval-util.cc | 37 +-
be/src/exprs/anyval-util.h | 44 +-
be/src/exprs/case-expr.cc | 17 +-
be/src/exprs/compound-predicates.cc | 7 +-
be/src/exprs/compound-predicates.h | 2 +-
be/src/exprs/expr-codegen-test.cc | 2 +-
be/src/exprs/expr-context.h | 11 +-
be/src/exprs/expr-test.cc | 8 +-
be/src/exprs/expr.cc | 93 +-
be/src/exprs/expr.h | 20 +-
be/src/exprs/hive-udf-call.cc | 29 +-
be/src/exprs/in-predicate-ir.cc | 110 --
be/src/exprs/in-predicate.h | 152 ++-
be/src/exprs/like-predicate.cc | 30 +-
be/src/exprs/literal.cc | 9 +-
be/src/exprs/null-literal.cc | 2 +-
be/src/exprs/scalar-fn-call.cc | 232 ++--
be/src/exprs/scalar-fn-call.h | 24 +-
be/src/exprs/slot-ref.cc | 51 +-
be/src/exprs/string-functions-ir.cc | 6 +-
be/src/exprs/utility-functions-ir.cc | 1 +
be/src/rpc/TAcceptQueueServer.h | 6 +-
be/src/rpc/authentication.cc | 1 +
be/src/rpc/authentication.h | 5 +-
be/src/rpc/thrift-server.h | 2 +
be/src/runtime/CMakeLists.txt | 1 +
be/src/runtime/buffered-block-mgr.cc | 27 +-
be/src/runtime/buffered-block-mgr.h | 2 +-
be/src/runtime/buffered-tuple-stream-test.cc | 81 +-
be/src/runtime/buffered-tuple-stream.cc | 39 +-
be/src/runtime/buffered-tuple-stream.h | 58 +-
be/src/runtime/coordinator.cc | 478 ++------
be/src/runtime/coordinator.h | 87 +-
be/src/runtime/data-stream-sender.cc | 4 +-
be/src/runtime/data-stream-sender.h | 1 -
be/src/runtime/decimal-test.cc | 18 +
be/src/runtime/descriptors.cc | 133 ++-
be/src/runtime/descriptors.h | 49 +-
be/src/runtime/disk-io-mgr-internal.h | 3 +-
be/src/runtime/disk-io-mgr-scan-range.cc | 93 +-
be/src/runtime/disk-io-mgr-stress-test.cc | 1 +
be/src/runtime/disk-io-mgr-stress.cc | 16 +-
be/src/runtime/disk-io-mgr-stress.h | 8 +-
be/src/runtime/disk-io-mgr-test.cc | 102 +-
be/src/runtime/disk-io-mgr.cc | 160 +--
be/src/runtime/disk-io-mgr.h | 163 ++-
be/src/runtime/exec-env.h | 2 +-
be/src/runtime/free-pool-test.cc | 41 +-
be/src/runtime/free-pool.h | 7 +-
be/src/runtime/hbase-table.cc | 2 +-
be/src/runtime/hdfs-fs-cache.h | 2 +-
be/src/runtime/mem-pool-test.cc | 38 +-
be/src/runtime/mem-pool.cc | 8 +-
be/src/runtime/mem-pool.h | 72 +-
be/src/runtime/multi-precision-test.cc | 2 +-
be/src/runtime/plan-fragment-executor.cc | 42 +-
be/src/runtime/plan-fragment-executor.h | 6 +-
be/src/runtime/row-batch-test.cc | 18 +-
be/src/runtime/row-batch.cc | 53 +-
be/src/runtime/row-batch.h | 92 +-
be/src/runtime/runtime-filter-bank.h | 2 +-
be/src/runtime/runtime-filter.h | 2 +-
be/src/runtime/scoped-buffer.h | 2 +-
be/src/runtime/sorted-run-merger.cc | 5 +-
be/src/runtime/sorted-run-merger.h | 6 +-
be/src/runtime/sorter.cc | 15 +-
be/src/runtime/string-buffer.h | 7 +-
be/src/runtime/string-compare-test.cc | 67 ++
be/src/runtime/string-value.inline.h | 4 +-
be/src/runtime/timestamp-parse-util.cc | 2 +-
be/src/runtime/timestamp-value.cc | 4 +-
be/src/runtime/tmp-file-mgr-test.cc | 2 +-
be/src/runtime/tmp-file-mgr.cc | 10 +-
be/src/runtime/tmp-file-mgr.h | 2 +-
be/src/runtime/tuple.cc | 5 +-
be/src/runtime/types.h | 29 +-
be/src/scheduling/admission-controller.cc | 2 +
be/src/scheduling/query-schedule.cc | 175 +--
be/src/scheduling/query-schedule.h | 77 +-
be/src/scheduling/simple-scheduler-test-util.cc | 10 +-
be/src/scheduling/simple-scheduler-test-util.h | 14 +-
be/src/scheduling/simple-scheduler-test.cc | 2 +-
be/src/scheduling/simple-scheduler.cc | 443 +++----
be/src/scheduling/simple-scheduler.h | 81 +-
be/src/service/fe-support.cc | 19 +-
be/src/service/frontend.cc | 35 +-
be/src/service/impala-beeswax-server.cc | 3 +-
be/src/service/impala-hs2-server.cc | 3 +-
be/src/service/impala-http-handler.cc | 28 +-
be/src/service/impala-server.cc | 38 +-
be/src/service/impala-server.h | 80 +-
be/src/service/query-exec-state.cc | 62 +-
be/src/service/query-exec-state.h | 33 +-
be/src/service/query-options.cc | 5 +
be/src/service/query-options.h | 5 +-
be/src/service/query-result-set.cc | 2 +-
be/src/statestore/failure-detector.h | 2 +-
be/src/statestore/statestore-subscriber.h | 2 +-
be/src/statestore/statestore.cc | 4 +-
be/src/statestore/statestore.h | 31 +-
be/src/testutil/test-macros.h | 55 -
be/src/testutil/test-udas.cc | 51 +-
be/src/testutil/test-udas.h | 2 +-
be/src/testutil/test-udfs.cc | 6 +-
be/src/thirdparty/mustache/mustache.cc | 2 +
be/src/transport/TSasl.h | 9 +-
be/src/transport/TSaslClientTransport.h | 8 +-
be/src/transport/TSaslServerTransport.h | 6 +-
be/src/transport/TSaslTransport.h | 6 +-
be/src/udf/uda-test-harness.h | 6 +-
be/src/udf/uda-test.cc | 2 +-
be/src/udf/udf-internal.h | 63 +-
be/src/udf/udf-ir.cc | 2 -
be/src/udf/udf-test-harness.cc | 2 +-
be/src/udf/udf.cc | 30 +-
be/src/udf/udf.h | 17 +-
be/src/udf_samples/uda-sample.cc | 2 +-
be/src/util/CMakeLists.txt | 1 +
be/src/util/aligned-new.h | 55 +
be/src/util/avro-util.cc | 42 +-
be/src/util/avro-util.h | 7 +-
be/src/util/backend-gflag-util.cc | 76 ++
be/src/util/backend-gflag-util.h | 31 +
be/src/util/benchmark-test.cc | 2 +-
be/src/util/bit-stream-utils.inline.h | 2 +
be/src/util/bit-util-test.cc | 7 +-
be/src/util/bit-util.h | 2 +-
be/src/util/blocking-queue-test.cc | 2 +-
be/src/util/blocking-queue.h | 5 +-
be/src/util/bloom-filter-test.cc | 57 +-
be/src/util/bloom-filter.cc | 40 +-
be/src/util/buffer-builder.h | 22 +-
be/src/util/compress.cc | 2 +-
be/src/util/decompress.cc | 2 +-
be/src/util/metrics.h | 6 +-
be/src/util/minidump.cc | 10 +-
be/src/util/network-util.cc | 1 +
be/src/util/parquet-reader.cc | 4 +-
be/src/util/periodic-counter-updater.h | 2 +-
be/src/util/pprof-path-handlers.cc | 2 +-
be/src/util/progress-updater.cc | 8 +-
be/src/util/rle-test.cc | 4 +-
be/src/util/runtime-profile-counters.h | 74 +-
be/src/util/runtime-profile-test.cc | 59 +
be/src/util/runtime-profile.cc | 123 +-
be/src/util/runtime-profile.h | 17 +-
be/src/util/thread-pool.h | 3 +-
be/src/util/tuple-row-compare.cc | 2 +-
be/src/util/webserver.cc | 6 +
bin/bootstrap_development.sh | 2 +-
bin/check-rat-report.py | 13 +-
bin/distcc/README.md | 16 +-
bin/generate_minidump_collection_testdata.py | 6 +-
bin/impala-config.sh | 4 +-
bin/load-data.py | 12 +
bin/make_impala.sh | 6 +-
bin/rat_exclude_files.txt | 2 +
bin/remote_data_load.py | 560 +++++++++
bin/run-backend-tests.sh | 1 +
bin/run_clang_tidy.sh | 54 +
buildall.sh | 9 +
cmake_modules/asan_toolchain.cmake | 44 -
cmake_modules/clang_toolchain.cmake | 54 +
common/thrift/BackendGflags.thrift | 55 +
common/thrift/CMakeLists.txt | 11 +-
common/thrift/CatalogObjects.thrift | 40 +-
common/thrift/CatalogService.thrift | 2 +-
common/thrift/DataSinks.thrift | 4 +-
common/thrift/Descriptors.thrift | 1 +
common/thrift/Frontend.thrift | 61 +-
common/thrift/ImpalaInternalService.thrift | 30 +-
common/thrift/ImpalaService.thrift | 4 +
common/thrift/JniCatalog.thrift | 24 +-
common/thrift/Planner.thrift | 4 +-
common/thrift/RuntimeProfile.thrift | 13 +
common/thrift/cli_service.thrift | 1126 ------------------
common/thrift/generate_error_codes.py | 12 +-
common/thrift/generate_metrics.py | 2 +-
fe/src/main/cup/sql-parser.cup | 229 ++--
.../analysis/AlterTableDropPartitionStmt.java | 22 +-
.../analysis/AlterTableSetCachedStmt.java | 30 +-
.../analysis/AlterTableSetFileFormatStmt.java | 12 +-
.../analysis/AlterTableSetLocationStmt.java | 50 +-
.../impala/analysis/AlterTableSetStmt.java | 18 +-
.../analysis/AlterTableSetTblProperties.java | 22 +-
.../apache/impala/analysis/AlterTableStmt.java | 24 +-
.../apache/impala/analysis/AlterViewStmt.java | 3 +-
.../apache/impala/analysis/AnalysisContext.java | 72 +-
.../org/apache/impala/analysis/Analyzer.java | 52 +-
.../apache/impala/analysis/BaseTableRef.java | 2 +-
.../impala/analysis/BetweenPredicate.java | 111 +-
.../impala/analysis/CollectionTableRef.java | 2 +-
.../org/apache/impala/analysis/ColumnDef.java | 7 +-
.../impala/analysis/CompoundPredicate.java | 26 +-
.../impala/analysis/ComputeStatsStmt.java | 115 +-
.../analysis/CreateOrAlterViewStmtBase.java | 8 +-
.../analysis/CreateTableAsSelectStmt.java | 23 +-
.../apache/impala/analysis/CreateTableStmt.java | 15 +-
.../apache/impala/analysis/CreateViewStmt.java | 3 +-
.../org/apache/impala/analysis/DeleteStmt.java | 14 +-
.../apache/impala/analysis/DescriptorTable.java | 80 +-
.../apache/impala/analysis/DistributeParam.java | 150 +--
.../apache/impala/analysis/DropStatsStmt.java | 55 +-
.../apache/impala/analysis/ExistsPredicate.java | 10 +-
.../java/org/apache/impala/analysis/Expr.java | 21 +-
.../apache/impala/analysis/InlineViewRef.java | 19 +-
.../org/apache/impala/analysis/InsertStmt.java | 305 +++--
.../org/apache/impala/analysis/LiteralExpr.java | 2 +-
.../org/apache/impala/analysis/ModifyStmt.java | 27 +-
.../apache/impala/analysis/PartitionSet.java | 199 ++++
.../apache/impala/analysis/PartitionSpec.java | 62 +-
.../impala/analysis/PartitionSpecBase.java | 94 ++
.../org/apache/impala/analysis/QueryStmt.java | 41 +-
.../apache/impala/analysis/RangePartition.java | 227 ++++
.../org/apache/impala/analysis/SelectList.java | 11 +
.../apache/impala/analysis/SelectListItem.java | 3 +-
.../org/apache/impala/analysis/SelectStmt.java | 32 +-
.../apache/impala/analysis/ShowFilesStmt.java | 44 +-
.../apache/impala/analysis/SlotDescriptor.java | 3 +-
.../org/apache/impala/analysis/SortInfo.java | 63 +-
.../apache/impala/analysis/StatementBase.java | 13 +-
.../apache/impala/analysis/StmtRewriter.java | 30 +-
.../org/apache/impala/analysis/Subquery.java | 17 +-
.../org/apache/impala/analysis/TableRef.java | 20 +-
.../apache/impala/analysis/TupleDescriptor.java | 83 +-
.../org/apache/impala/analysis/UnionStmt.java | 187 +--
.../org/apache/impala/analysis/UpdateStmt.java | 21 +-
.../org/apache/impala/authorization/User.java | 26 +-
.../org/apache/impala/catalog/BuiltinsDb.java | 20 +-
.../impala/catalog/CatalogServiceCatalog.java | 52 +-
.../java/org/apache/impala/catalog/Column.java | 2 +-
.../apache/impala/catalog/DataSourceTable.java | 9 +-
.../org/apache/impala/catalog/HBaseTable.java | 8 +-
.../org/apache/impala/catalog/HdfsTable.java | 73 +-
.../apache/impala/catalog/IncompleteTable.java | 18 +-
.../org/apache/impala/catalog/KuduTable.java | 58 +-
.../java/org/apache/impala/catalog/Table.java | 35 +-
.../java/org/apache/impala/catalog/TableId.java | 42 -
.../org/apache/impala/catalog/TableLoader.java | 9 +-
.../apache/impala/catalog/TableLoadingMgr.java | 4 +-
.../java/org/apache/impala/catalog/View.java | 12 +-
.../apache/impala/common/FileSystemUtil.java | 13 +
.../main/java/org/apache/impala/common/Id.java | 2 -
.../org/apache/impala/common/RuntimeEnv.java | 12 -
.../impala/planner/DataSourceScanNode.java | 4 +-
.../apache/impala/planner/HBaseScanNode.java | 6 +-
.../apache/impala/planner/HBaseTableSink.java | 3 +-
.../impala/planner/HdfsPartitionPruner.java | 50 +-
.../org/apache/impala/planner/HdfsScanNode.java | 6 +-
.../apache/impala/planner/HdfsTableSink.java | 3 +-
.../org/apache/impala/planner/JoinTableId.java | 6 +-
.../org/apache/impala/planner/KuduScanNode.java | 22 +-
.../apache/impala/planner/KuduTableSink.java | 20 +-
.../org/apache/impala/planner/PlanNode.java | 8 +-
.../java/org/apache/impala/planner/Planner.java | 55 +-
.../org/apache/impala/planner/ScanNode.java | 6 +-
.../impala/planner/SingleNodePlanner.java | 6 +-
.../org/apache/impala/planner/TableSink.java | 16 +-
.../org/apache/impala/planner/UnionNode.java | 17 +-
.../impala/rewrite/BetweenToCompoundRule.java | 63 +
.../apache/impala/rewrite/ExprRewriteRule.java | 39 +
.../org/apache/impala/rewrite/ExprRewriter.java | 97 ++
.../rewrite/ExtractCommonConjunctRule.java | 102 ++
.../apache/impala/service/BackendConfig.java | 62 +-
.../impala/service/CatalogOpExecutor.java | 404 ++++---
.../org/apache/impala/service/FeSupport.java | 18 -
.../org/apache/impala/service/Frontend.java | 222 +---
.../org/apache/impala/service/JniCatalog.java | 40 +-
.../org/apache/impala/service/JniFrontend.java | 24 +-
.../impala/service/KuduCatalogOpExecutor.java | 71 +-
.../java/org/apache/impala/util/KuduUtil.java | 180 ++-
fe/src/main/jflex/sql-scanner.flex | 1 +
.../apache/impala/analysis/AnalyzeDDLTest.java | 521 +++++---
.../impala/analysis/AnalyzeModifyStmtsTest.java | 2 -
.../impala/analysis/AnalyzeStmtsTest.java | 26 +-
.../impala/analysis/AnalyzeSubqueriesTest.java | 10 +-
.../impala/analysis/AnalyzeUpsertStmtTest.java | 132 ++
.../apache/impala/analysis/AnalyzerTest.java | 8 +
.../impala/analysis/ExprRewriteRulesTest.java | 201 ++++
.../impala/analysis/ExprRewriterTest.java | 175 +++
.../org/apache/impala/analysis/ExprTest.java | 3 +-
.../org/apache/impala/analysis/ParserTest.java | 198 +--
.../org/apache/impala/analysis/ToSqlTest.java | 30 +
.../apache/impala/common/FrontendTestBase.java | 14 +-
.../impala/hive/executor/UdfExecutorTest.java | 188 +--
.../org/apache/impala/planner/PlannerTest.java | 6 +
.../apache/impala/planner/PlannerTestBase.java | 232 ++--
.../testutil/CatalogServiceTestCatalog.java | 3 +-
.../org/apache/impala/util/KuduUtilTest.java | 120 --
infra/python/deps/download_requirements | 2 +-
infra/python/deps/pip_download.py | 10 +-
infra/python/deps/requirements.txt | 2 +-
shell/impala_client.py | 2 +-
testdata/bad_avro_snap/README | 13 +-
.../bad_avro_snap/invalid_decimal_schema.avro | Bin 0 -> 328 bytes
testdata/bin/compute-table-stats.sh | 8 +-
testdata/bin/copy-udfs-udas.sh | 8 +-
testdata/bin/create-load-data.sh | 176 ++-
testdata/bin/create-table-many-blocks.sh | 14 +-
testdata/bin/generate-schema-statements.py | 3 +-
testdata/bin/load-test-warehouse-snapshot.sh | 37 +-
testdata/bin/load_nested.py | 13 +-
testdata/bin/run-step.sh | 1 +
testdata/bin/setup-hdfs-env.sh | 32 +-
testdata/bin/wait-for-hiveserver2.py | 12 +-
testdata/bin/wait-for-metastore.py | 2 +-
.../functional/functional_schema_template.sql | 39 +-
.../datasets/functional/schema_constraints.csv | 1 +
testdata/datasets/tpcds/tpcds_kudu_template.sql | 246 ++--
testdata/datasets/tpch/tpch_kudu_template.sql | 102 +-
.../impala/datagenerator/TestDataGenerator.java | 5 +
.../queries/PlannerTest/insert.test | 135 +++
.../queries/PlannerTest/kudu-delete.test | 18 -
.../queries/PlannerTest/kudu-update.test | 14 -
.../queries/PlannerTest/kudu-upsert.test | 92 ++
.../queries/PlannerTest/kudu.test | 97 +-
.../queries/PlannerTest/mt-dop-validation.test | 50 +-
.../queries/PlannerTest/subquery-rewrite.test | 34 +-
.../queries/PlannerTest/tpcds-all.test | 12 +-
.../queries/PlannerTest/tpch-all.test | 12 +-
.../queries/PlannerTest/tpch-kudu.test | 5 +-
.../queries/PlannerTest/tpch-nested.test | 12 +-
.../queries/PlannerTest/tpch-views.test | 4 +-
.../queries/DataErrorsTest/avro-errors.test | 8 +
.../queries/QueryTest/alter-table.test | 45 +
.../queries/QueryTest/avro-schema-changes.test | 6 +-
.../queries/QueryTest/compute-stats.test | 84 ++
.../queries/QueryTest/exprs.test | 29 +
.../queries/QueryTest/hdfs-caching.test | 2 +-
.../queries/QueryTest/insert.test | 14 +
.../queries/QueryTest/java-udf.test | 125 +-
.../queries/QueryTest/kudu-scan-node.test | 8 +
.../QueryTest/kudu-timeouts-catalogd.test | 25 +
.../QueryTest/kudu-timeouts-impalad.test | 13 +
.../queries/QueryTest/kudu_alter.test | 6 +
.../queries/QueryTest/kudu_create.test | 35 +-
.../queries/QueryTest/kudu_crud.test | 271 ++++-
.../queries/QueryTest/kudu_partition_ddl.test | 216 +++-
.../queries/QueryTest/kudu_stats.test | 4 +-
.../QueryTest/libs_with_same_filenames.test | 11 +-
.../queries/QueryTest/load-java-udfs.test | 79 +-
.../queries/QueryTest/mt-dop-compute-stats.test | 8 +
.../queries/QueryTest/mt-dop-parquet.test | 7 +
.../QueryTest/partition-ddl-predicates.test | 156 +++
.../queries/QueryTest/scanners.test | 26 +
.../queries/QueryTest/uda-mem-limit.test | 3 -
.../functional-query/queries/QueryTest/uda.test | 35 +
.../queries/QueryTest/udf-codegen-required.test | 10 +
.../queries/QueryTest/udf-errors.test | 37 +-
.../queries/QueryTest/udf-mem-limit.test | 5 -
.../functional-query/queries/QueryTest/udf.test | 7 -
.../queries/QueryTest/union.test | 28 +
.../queries/primitive_filter_in_predicate.test | 10 +
tests/benchmark/report_benchmark_results.py | 2 +-
tests/common/impala_service.py | 4 +
tests/common/impala_test_suite.py | 24 +-
tests/common/kudu_test_suite.py | 4 +-
tests/common/test_result_verifier.py | 22 +
tests/comparison/POSTGRES.txt | 84 ++
tests/comparison/README | 4 +
tests/comparison/common.py | 46 +-
tests/comparison/db_connection.py | 146 ++-
tests/comparison/leopard/controller.py | 5 +-
tests/comparison/leopard/impala_docker_env.py | 4 +-
tests/comparison/tests/fake_query.py | 9 +-
tests/comparison/tests/test_cursor.py | 184 +++
tests/conftest.py | 51 +-
.../custom_cluster/test_admission_controller.py | 40 +
.../test_hive_parquet_timestamp_conversion.py | 6 +-
tests/custom_cluster/test_kudu.py | 24 +
tests/custom_cluster/test_permanent_udfs.py | 9 +
tests/failure/test_failpoints.py | 4 +
tests/metadata/test_ddl.py | 4 +
.../metadata/test_metadata_query_statements.py | 47 +-
tests/metadata/test_show_create_table.py | 63 +-
tests/performance/query_exec_functions.py | 10 +-
tests/performance/query_executor.py | 1 +
tests/query_test/test_aggregation.py | 124 +-
tests/query_test/test_kudu.py | 62 +-
tests/query_test/test_mt_dop.py | 59 +-
tests/query_test/test_scanners.py | 18 +
tests/query_test/test_udfs.py | 88 +-
tests/run-custom-cluster-tests.sh | 5 +-
tests/run-process-failure-tests.sh | 12 +-
.../org/apache/impala/ReplaceStringUdf.java | 31 +
.../java/org/apache/impala/UnresolvedUdf.java | 25 +-
www/queries.tmpl | 6 +
www/sessions.tmpl | 94 +-
477 files changed, 12455 insertions(+), 7916 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/bin/impala-config.sh
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/analysis/ColumnDef.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/analysis/Subquery.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
----------------------------------------------------------------------
diff --cc fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
index 7326670,21b5359..6530502
--- a/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
+++ b/fe/src/main/java/org/apache/impala/catalog/HdfsTable.java
@@@ -45,9 -47,9 +45,6 @@@ import org.apache.hadoop.hive.metastore
import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
import org.apache.hadoop.hive.serde.serdeConstants;
import org.apache.hadoop.util.StringUtils;
--import org.slf4j.Logger;
--import org.slf4j.LoggerFactory;
--
import org.apache.impala.analysis.ColumnDef;
import org.apache.impala.analysis.Expr;
import org.apache.impala.analysis.LiteralExpr;
@@@ -67,7 -70,7 +65,6 @@@ import org.apache.impala.thrift.TCatalo
import org.apache.impala.thrift.TColumn;
import org.apache.impala.thrift.THdfsFileBlock;
import org.apache.impala.thrift.THdfsPartition;
--import org.apache.impala.thrift.THdfsPartitionLocation;
import org.apache.impala.thrift.THdfsTable;
import org.apache.impala.thrift.TNetworkAddress;
import org.apache.impala.thrift.TPartitionKeyValue;
@@@ -86,14 -89,44 +83,14 @@@ import org.apache.impala.util.ListMap
import org.apache.impala.util.MetaStoreUtil;
import org.apache.impala.util.TAccessLevelUtil;
import org.apache.impala.util.TResultRowBuilder;
++import org.slf4j.Logger;
++import org.slf4j.LoggerFactory;
++
import com.google.common.base.Preconditions;
- import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
- import com.google.common.collect.ImmutableSet;
- import com.google.common.collect.ImmutableMap;
-import org.apache.avro.Schema;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.BlockLocation;
-import org.apache.hadoop.fs.BlockStorageLocation;
-import org.apache.hadoop.fs.FileStatus;
-import org.apache.hadoop.fs.FileSystem;
-import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.fs.VolumeId;
-import org.apache.hadoop.hbase.util.Bytes;
-import org.apache.hadoop.hdfs.DFSConfigKeys;
-import org.apache.hadoop.hdfs.DistributedFileSystem;
-import org.apache.hadoop.hive.metastore.IMetaStoreClient;
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-import org.apache.hadoop.hive.metastore.api.Partition;
-import org.apache.hadoop.hive.metastore.api.StorageDescriptor;
-import org.apache.hadoop.hive.serde.serdeConstants;
-import org.apache.hadoop.util.StringUtils;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.IOException;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.TreeMap;
-
/**
* Internal representation of table-related metadata of a file-resident table on a
* Hadoop filesystem. The table data can be accessed through libHDFS (which is more of
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/service/CatalogOpExecutor.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/service/Frontend.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/main/java/org/apache/impala/service/JniFrontend.java
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/32dfcebf/fe/src/test/java/org/apache/impala/analysis/ParserTest.java
----------------------------------------------------------------------
[48/50] [abbrv] incubator-impala git commit: clang-tidy should tidy
tests; fix alignas error in clang builds.
Posted by ta...@apache.org.
clang-tidy should tidy tests; fix alignas error in clang builds.
run_clang_tidy.sh was mistakenly using -notests, which doesn't even
compile the tests, rather than -skiptests, which compiles (but does
not run) the backend tests.
When I discovered this, I also found that all clang builds (including
tidy and asan) had been broken by my previous alignas commit
(10a4c5a2e47ec7bf1e563b6a75d1bf2afb47ebd8). This patch fixes that as
well.
Change-Id: Ib7066039f78d7ee039db619b96e25665b4d63503
Reviewed-on: http://gerrit.cloudera.org:8080/5094
Reviewed-by: Sailesh Mukil <sa...@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/9434e38a
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/9434e38a
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/9434e38a
Branch: refs/heads/hadoop-next
Commit: 9434e38abb515da25a3adbe43a217d4361ee531c
Parents: 38ee3b6
Author: Jim Apple <jb...@cloudera.com>
Authored: Tue Nov 15 06:22:13 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 15 23:33:45 2016 +0000
----------------------------------------------------------------------
be/src/runtime/mem-pool.cc | 2 +-
bin/run_clang_tidy.sh | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9434e38a/be/src/runtime/mem-pool.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.cc b/be/src/runtime/mem-pool.cc
index 5f3feca..0ca3822 100644
--- a/be/src/runtime/mem-pool.cc
+++ b/be/src/runtime/mem-pool.cc
@@ -37,7 +37,7 @@ const int MemPool::MAX_CHUNK_SIZE;
const char* MemPool::LLVM_CLASS_NAME = "class.impala::MemPool";
const int MemPool::DEFAULT_ALIGNMENT;
-uint32_t MemPool::zero_length_region_ = MEM_POOL_POISON;
+uint32_t MemPool::zero_length_region_ alignas(std::max_align_t) = MEM_POOL_POISON;
MemPool::MemPool(MemTracker* mem_tracker)
: current_chunk_idx_(-1),
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/9434e38a/bin/run_clang_tidy.sh
----------------------------------------------------------------------
diff --git a/bin/run_clang_tidy.sh b/bin/run_clang_tidy.sh
index aa95845..7d42597 100755
--- a/bin/run_clang_tidy.sh
+++ b/bin/run_clang_tidy.sh
@@ -30,7 +30,7 @@
set -euo pipefail
echo "Compiling"
-if ! ./buildall.sh -notests -tidy -so -noclean 1>/dev/null 2>/dev/null
+if ! ./buildall.sh -skiptests -tidy -so -noclean 1>/dev/null 2>/dev/null
then
echo "WARNING: compile failed" >&2
fi
[10/50] [abbrv] incubator-impala git commit: IMPALA-1169: Admission
control info on the queries debug webpage
Posted by ta...@apache.org.
IMPALA-1169: Admission control info on the queries debug webpage
This patch adds a new event, 'Queued', to the query event log to
indicate when a query is queued by the admission controller. This
means that queries on the '/queries' page that are currently
queued will display this as their 'Last Event', making it possible
to see which queries are current queued.
It also adds a column to show the resource pool associated with
the queries, and it updates the wording of the first event that
gets marked for each query from 'Start execution' to 'Query
submitted', since this is before planning and admission control
and therefore execution hasn't actually startd yet.
Change-Id: I504e3c829a14318721e3a42de6281bcc578f7283
Reviewed-on: http://gerrit.cloudera.org:8080/4756
Reviewed-by: Matthew Jacobs <mj...@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/3be4b3ef
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/3be4b3ef
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/3be4b3ef
Branch: refs/heads/hadoop-next
Commit: 3be4b3efd032a6723042aa2e9b087ff03b021872
Parents: 9bc90fa
Author: Thomas Tauber-Marshall <tm...@cloudera.com>
Authored: Mon Oct 17 15:01:51 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Mon Nov 7 23:26:02 2016 +0000
----------------------------------------------------------------------
be/src/scheduling/admission-controller.cc | 2 +
be/src/service/impala-http-handler.cc | 3 ++
be/src/service/impala-server.cc | 3 +-
be/src/service/impala-server.h | 4 ++
be/src/service/query-exec-state.h | 7 ++++
tests/common/impala_service.py | 4 ++
.../custom_cluster/test_admission_controller.py | 40 ++++++++++++++++++++
www/queries.tmpl | 6 +++
8 files changed, 68 insertions(+), 1 deletion(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/be/src/scheduling/admission-controller.cc
----------------------------------------------------------------------
diff --git a/be/src/scheduling/admission-controller.cc b/be/src/scheduling/admission-controller.cc
index 8151798..a5d8457 100644
--- a/be/src/scheduling/admission-controller.cc
+++ b/be/src/scheduling/admission-controller.cc
@@ -98,6 +98,7 @@ const string POOL_MAX_QUEUED_METRIC_KEY_FORMAT =
// Profile query events
const string QUERY_EVENT_SUBMIT_FOR_ADMISSION = "Submit for admission";
+const string QUERY_EVENT_QUEUED = "Queued";
const string QUERY_EVENT_COMPLETED_ADMISSION = "Completed admission";
// Profile info strings
@@ -469,6 +470,7 @@ Status AdmissionController::AdmitQuery(QuerySchedule* schedule) {
PROFILE_INFO_VAL_QUEUED);
schedule->summary_profile()->AddInfoString(PROFILE_INFO_KEY_QUEUE_DETAIL,
not_admitted_reason);
+ schedule->query_events()->MarkEvent(QUERY_EVENT_QUEUED);
int64_t queue_wait_timeout_ms = FLAGS_queue_wait_timeout_ms;
if (pool_cfg.__isset.queue_timeout_ms) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/be/src/service/impala-http-handler.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-http-handler.cc b/be/src/service/impala-http-handler.cc
index 834fd42..b675f3a 100644
--- a/be/src/service/impala-http-handler.cc
+++ b/be/src/service/impala-http-handler.cc
@@ -352,6 +352,9 @@ void ImpalaHttpHandler::QueryStateToJson(const ImpalaServer::QueryStateRecord& r
}
Value val_waiting_time(waiting_time_str.c_str(), document->GetAllocator());
value->AddMember("waiting_time", val_waiting_time, document->GetAllocator());
+
+ Value resource_pool(record.request_pool.c_str(), document->GetAllocator());
+ value->AddMember("resource_pool", resource_pool, document->GetAllocator());
}
void ImpalaHttpHandler::QueryStateHandler(const Webserver::ArgumentMap& args,
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/be/src/service/impala-server.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.cc b/be/src/service/impala-server.cc
index 024cd24..730dfbf 100644
--- a/be/src/service/impala-server.cc
+++ b/be/src/service/impala-server.cc
@@ -777,7 +777,7 @@ Status ImpalaServer::ExecuteInternal(
exec_state->reset(new QueryExecState(query_ctx, exec_env_, exec_env_->frontend(),
this, session_state));
- (*exec_state)->query_events()->MarkEvent("Start execution");
+ (*exec_state)->query_events()->MarkEvent("Query submitted");
TExecRequest result;
{
@@ -1604,6 +1604,7 @@ ImpalaServer::QueryStateRecord::QueryStateRecord(const QueryExecState& exec_stat
}
all_rows_returned = exec_state.eos();
last_active_time = exec_state.last_active();
+ request_pool = exec_state.request_pool();
}
bool ImpalaServer::QueryStateRecordLessThan::operator() (
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/be/src/service/impala-server.h
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.h b/be/src/service/impala-server.h
index 836e619..9d14ecd 100644
--- a/be/src/service/impala-server.h
+++ b/be/src/service/impala-server.h
@@ -491,6 +491,10 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
// The most recent time this query was actively being processed, in Unix milliseconds.
int64_t last_active_time;
+ /// Request pool to which the request was submitted for admission, or an empty string
+ /// if this request doesn't have a pool.
+ std::string request_pool;
+
/// Initialise from an exec_state. If copy_profile is true, print the query
/// profile to a string and copy that into this.profile (which is expensive),
/// otherwise leave this.profile empty.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/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 26dcf4d..55e3ffa 100644
--- a/be/src/service/query-exec-state.h
+++ b/be/src/service/query-exec-state.h
@@ -154,6 +154,13 @@ class ImpalaServer::QueryExecState {
bool eos() const { return eos_; }
Coordinator* coord() const { return coord_.get(); }
QuerySchedule* schedule() { return schedule_.get(); }
+
+ /// Resource pool associated with this query, or an empty string if the schedule has not
+ /// been created and had the pool set yet, or this StmtType doesn't go through admission
+ /// control.
+ std::string request_pool() const {
+ return schedule_ == nullptr ? "" : schedule_->request_pool();
+ }
int num_rows_fetched() const { return num_rows_fetched_; }
void set_fetched_rows() { fetched_rows_ = true; }
bool fetched_rows() const { return fetched_rows_; }
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/tests/common/impala_service.py
----------------------------------------------------------------------
diff --git a/tests/common/impala_service.py b/tests/common/impala_service.py
index fe141bf..4e9c815 100644
--- a/tests/common/impala_service.py
+++ b/tests/common/impala_service.py
@@ -53,6 +53,10 @@ class BaseImpalaService(object):
def read_debug_webpage(self, page_name, timeout=10, interval=1):
return self.open_debug_webpage(page_name, timeout=timeout, interval=interval).read()
+ def get_debug_webpage_json(self, page_name):
+ """Returns the json for the given Impala debug webpage, eg. '/queries'"""
+ return json.loads(self.read_debug_webpage(page_name + "?json"))
+
def get_metric_value(self, metric_name, default_value=None):
"""Returns the value of the the given metric name from the Impala debug webpage"""
metrics = json.loads(self.read_debug_webpage('jsonmetrics?json'))
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/tests/custom_cluster/test_admission_controller.py
----------------------------------------------------------------------
diff --git a/tests/custom_cluster/test_admission_controller.py b/tests/custom_cluster/test_admission_controller.py
index 136436b..3992e3a 100644
--- a/tests/custom_cluster/test_admission_controller.py
+++ b/tests/custom_cluster/test_admission_controller.py
@@ -17,6 +17,7 @@
# Tests admission control
+import itertools
import logging
import os
import pytest
@@ -599,6 +600,33 @@ class TestAdmissionControllerStress(TestAdmissionControllerBase):
if client is not None:
client.close()
+ def _check_queries_page_resource_pools(self):
+ """Checks that all queries in the '/queries' webpage json have the correct resource
+ pool (this is called after all queries have been admitted, queued, or rejected, so
+ they should already have the pool set), or no pool for queries that don't go through
+ admission control."""
+ for impalad in self.impalads:
+ queries_json = impalad.service.get_debug_webpage_json('/queries')
+ for query in itertools.chain(queries_json['in_flight_queries'], \
+ queries_json['completed_queries']):
+ if query['stmt_type'] == 'QUERY' or query['stmt_type'] == 'DML':
+ assert query['last_event'] != 'Registered' and \
+ query['last_event'] != 'Planning finished'
+ assert query['resource_pool'] == self.pool_name
+ else:
+ assert query['resource_pool'] == ''
+
+ def _get_queries_page_num_queued(self):
+ """Returns the number of queries currently in the 'queued' state from the '/queries'
+ webpage json"""
+ num_queued = 0
+ for impalad in self.impalads:
+ queries_json = impalad.service.get_debug_webpage_json('/queries')
+ for query in queries_json['in_flight_queries']:
+ if query['last_event'] == 'Queued':
+ num_queued += 1
+ return num_queued
+
def run_admission_test(self, vector, additional_query_options):
LOG.debug("Starting test case with parameters: %s", vector)
self.impalads = self.cluster.impalads
@@ -644,6 +672,13 @@ class TestAdmissionControllerStress(TestAdmissionControllerBase):
num_queries - metric_deltas['admitted'] - metric_deltas['queued']
initial_metric_deltas = metric_deltas
+ # Like above, check that the count from the queries webpage json is reasonable.
+ queries_page_num_queued = self._get_queries_page_num_queued()
+ assert queries_page_num_queued >=\
+ min(num_queries - metric_deltas['admitted'], MAX_NUM_QUEUED_QUERIES)
+ assert queries_page_num_queued <= MAX_NUM_QUEUED_QUERIES * len(self.impalads)
+ self._check_queries_page_resource_pools()
+
while len(self.executing_threads) > 0:
curr_metrics = self.get_admission_metrics();
log_metrics("Main loop, curr_metrics: ", curr_metrics);
@@ -685,6 +720,11 @@ class TestAdmissionControllerStress(TestAdmissionControllerBase):
assert metric_deltas['queued'] == MAX_NUM_QUEUED_QUERIES
assert metric_deltas['rejected'] == num_queries - expected_admitted
+ # All queries should be completed by now.
+ queries_page_num_queued = self._get_queries_page_num_queued()
+ assert queries_page_num_queued == 0
+ self._check_queries_page_resource_pools()
+
for thread in self.all_threads:
if thread.error is not None:
raise thread.error
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/3be4b3ef/www/queries.tmpl
----------------------------------------------------------------------
diff --git a/www/queries.tmpl b/www/queries.tmpl
index cacd147..2f26b92 100644
--- a/www/queries.tmpl
+++ b/www/queries.tmpl
@@ -36,6 +36,7 @@ archived in memory. The size of that archive is controlled with the
<th>State</th>
<th>Last Event</th>
<th># rows fetched</th>
+ <th>Resource Pool</th>
<th>Details</th>
<th>Action</th>
</tr>
@@ -53,6 +54,7 @@ archived in memory. The size of that archive is controlled with the
<td><samp>{{state}}</samp></td>
<td><samp>{{last_event}}</samp></td>
<td>{{rows_fetched}}</td>
+ <td>{{resource_pool}}</td>
<td><a href='/query_plan?query_id={{query_id}}'>Details</a></td>
<td><a href='/cancel_query?query_id={{query_id}}'>Cancel</a></td>
</tr>
@@ -78,6 +80,7 @@ archived in memory. The size of that archive is controlled with the
<th>State</th>
<th>Last Event</th>
<th># rows fetched</th>
+ <th>Resource Pool</th>
<th>Details</th>
<th>Action</th>
</tr>
@@ -96,6 +99,7 @@ archived in memory. The size of that archive is controlled with the
<td><samp>{{state}}</samp></td>
<td><samp>{{last_event}}</samp></td>
<td>{{rows_fetched}}</td>
+ <td>{{resource_pool}}</td>
<td><a href='/query_plan?query_id={{query_id}}'>Details</a></td>
<td><a href='/cancel_query?query_id={{query_id}}'>Close</a></td>
</tr>
@@ -117,6 +121,7 @@ archived in memory. The size of that archive is controlled with the
<th>Scan Progress</th>
<th>State</th>
<th># rows fetched</th>
+ <th>Resource Pool</th>
<th>Details</th>
</tr>
{{#completed_queries}}
@@ -131,6 +136,7 @@ archived in memory. The size of that archive is controlled with the
<td>{{progress}}</td>
<td><samp>{{state}}</samp></td>
<td>{{rows_fetched}}</td>
+ <td>{{resource_pool}}</td>
<td><a href='/query_plan?query_id={{query_id}}'>Details</a></td>
</tr>
{{/completed_queries}}
[17/50] [abbrv] incubator-impala git commit: IMPALA-4437: fix crash
in disk-io-mgr
Posted by ta...@apache.org.
IMPALA-4437: fix crash in disk-io-mgr
This fixes another issue where the 'buffer_' field was not set to NULL
on an error, triggering a DCHECK.
Testing:
Added a unit test that triggers the bug on the two different codepaths
that I fixed.
Change-Id: Ib76cf5ba8d368b2b37bdc1d2133b8ddcb39f9e00
Reviewed-on: http://gerrit.cloudera.org:8080/4979
Reviewed-by: Dan Hecht <dh...@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/ef689edf
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/ef689edf
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/ef689edf
Branch: refs/heads/hadoop-next
Commit: ef689edf36dd5715f17438e07a16fd4e38af5fb9
Parents: 51b1310
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Mon Nov 7 14:38:07 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 08:29:58 2016 +0000
----------------------------------------------------------------------
be/src/runtime/disk-io-mgr-test.cc | 38 +++++++++++++++++++++++++++++++++
be/src/runtime/disk-io-mgr.cc | 2 ++
2 files changed, 40 insertions(+)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ef689edf/be/src/runtime/disk-io-mgr-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr-test.cc b/be/src/runtime/disk-io-mgr-test.cc
index ef7e12f..9f8d6d7 100644
--- a/be/src/runtime/disk-io-mgr-test.cc
+++ b/be/src/runtime/disk-io-mgr-test.cc
@@ -1090,6 +1090,44 @@ TEST_F(DiskIoMgrTest, ReadIntoClientBuffer) {
io_mgr.reset();
EXPECT_EQ(mem_tracker.consumption(), 0);
}
+
+// Test reading into a client-allocated buffer where the read fails.
+TEST_F(DiskIoMgrTest, ReadIntoClientBufferError) {
+ MemTracker mem_tracker(LARGE_MEM_LIMIT);
+ const char* tmp_file = "/file/that/does/not/exist";
+ const int SCAN_LEN = 128;
+
+ scoped_ptr<DiskIoMgr> io_mgr(new DiskIoMgr(1, 1, SCAN_LEN, SCAN_LEN));
+
+ ASSERT_OK(io_mgr->Init(&mem_tracker));
+ // Reader doesn't need to provide mem tracker if it's providing buffers.
+ MemTracker* reader_mem_tracker = NULL;
+ DiskIoRequestContext* reader;
+ vector<uint8_t> client_buffer(SCAN_LEN);
+ for (int i = 0; i < 1000; ++i) {
+ ASSERT_OK(io_mgr->RegisterContext(&reader, reader_mem_tracker));
+ DiskIoMgr::ScanRange* range = AllocateRange(1);
+ range->Reset(NULL, tmp_file, SCAN_LEN, 0, 0, true,
+ DiskIoMgr::BufferOpts::ReadInto(&client_buffer[0], SCAN_LEN));
+ ASSERT_OK(io_mgr->AddScanRange(reader, range, true));
+
+ /// Also test the cancellation path. Run multiple iterations since it is racy whether
+ /// the read fails before the cancellation.
+ if (i >= 1) io_mgr->CancelContext(reader);
+
+ DiskIoMgr::BufferDescriptor* io_buffer;
+ ASSERT_FALSE(range->GetNext(&io_buffer).ok());
+
+ // DiskIoMgr should not have allocated memory.
+ EXPECT_EQ(mem_tracker.consumption(), 0);
+
+ io_mgr->UnregisterContext(reader);
+ }
+
+ pool_.reset();
+ io_mgr.reset();
+ EXPECT_EQ(mem_tracker.consumption(), 0);
+}
}
int main(int argc, char** argv) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ef689edf/be/src/runtime/disk-io-mgr.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/disk-io-mgr.cc b/be/src/runtime/disk-io-mgr.cc
index 265b49a..87ac33a 100644
--- a/be/src/runtime/disk-io-mgr.cc
+++ b/be/src/runtime/disk-io-mgr.cc
@@ -981,6 +981,7 @@ void DiskIoMgr::HandleReadFinished(DiskQueue* disk_queue, DiskIoRequestContext*
state.DecrementRequestThreadAndCheckDone(reader);
DCHECK(reader->Validate()) << endl << reader->DebugString();
if (!buffer->is_client_buffer()) FreeBufferMemory(buffer);
+ buffer->buffer_ = NULL;
buffer->scan_range_->Cancel(reader->status_);
// Enqueue the buffer to use the scan range's buffer cleanup path.
buffer->scan_range_->EnqueueBuffer(buffer);
@@ -997,6 +998,7 @@ void DiskIoMgr::HandleReadFinished(DiskQueue* disk_queue, DiskIoRequestContext*
if (!buffer->status_.ok()) {
// Error case
if (!buffer->is_client_buffer()) FreeBufferMemory(buffer);
+ buffer->buffer_ = NULL;
buffer->eosr_ = true;
--state.num_remaining_ranges();
buffer->scan_range_->Cancel(buffer->status_);
[27/50] [abbrv] incubator-impala git commit: IMPALA-1430,
IMPALA-4108: codegen all builtin aggregate functions
Posted by ta...@apache.org.
IMPALA-1430,IMPALA-4108: codegen all builtin aggregate functions
This change enables codegen for all builtin aggregate functions,
e.g. timestamp functions and group_concat.
There are several parts to the change:
* Adding support for generic UDAs. Previous the codegen code did not
handle multiple input arguments or NULL return values.
* Defaulting to using the UDA interface when there is not a special
codegen path (we have implementations of all builtin aggregate
functions for the interpreted path).
* Remove all the logic to disable codegen for the special cases that now
are supported.
Also fix the generation of code to get/set NULL bits since I needed
to add functionality there anyway.
Testing:
Add tests that check that codegen was enabled for builtin aggregate
functions. Also fix some gaps in the preexisting tests.
Also add tests for UDAs that check input/output nulls are handled
correctly, in anticipation of enabling codegen for arbitrary UDAs.
The tests are run with both codegen enabled and disabled. To avoid
flaky tests, we switch the UDF tests to use "unique_database".
Perf:
Ran local TPC-H and targeted perf. Spent a lot of time on TPC-H Q1,
since my original approach regressed it ~5%. In the end the problem was
to do with the ordering of loads/stores to the slot and null bit in the
generated code: the previous version of the code exploited some
properties of the particular aggregate function. I ended up replicating
this behaviour to avoid regressing perf.
Change-Id: Id9dc21d1d676505d3617e1e4f37557397c4fb260
Reviewed-on: http://gerrit.cloudera.org:8080/4655
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/d7246d64
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/d7246d64
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/d7246d64
Branch: refs/heads/hadoop-next
Commit: d7246d64c777384f29fe0f824ee0036b58e8aa2d
Parents: 6775893
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Wed Sep 28 13:04:07 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Wed Nov 9 03:27:12 2016 +0000
----------------------------------------------------------------------
be/src/benchmarks/hash-benchmark.cc | 2 +-
be/src/codegen/codegen-anyval.cc | 63 +-
be/src/codegen/codegen-anyval.h | 55 +-
be/src/codegen/gen_ir_descriptions.py | 4 +-
be/src/codegen/llvm-codegen-test.cc | 16 +-
be/src/codegen/llvm-codegen.cc | 19 +-
be/src/codegen/llvm-codegen.h | 29 +-
be/src/exec/aggregation-node.cc | 43 +-
be/src/exec/exec-node.cc | 2 +-
be/src/exec/hash-join-node.cc | 12 +-
be/src/exec/hash-table.cc | 42 +-
be/src/exec/hdfs-avro-scanner.cc | 23 +-
be/src/exec/hdfs-scanner.cc | 15 +-
be/src/exec/old-hash-table.cc | 10 +-
be/src/exec/partitioned-aggregation-node-ir.cc | 2 +-
be/src/exec/partitioned-aggregation-node.cc | 611 ++++++++++---------
be/src/exec/partitioned-aggregation-node.h | 25 +-
be/src/exec/partitioned-hash-join-node.cc | 12 +-
be/src/exec/text-converter.cc | 12 +-
be/src/exprs/aggregate-functions-ir.cc | 24 +-
be/src/exprs/case-expr.cc | 2 +-
be/src/exprs/compound-predicates.cc | 7 +-
be/src/exprs/expr-codegen-test.cc | 2 +-
be/src/exprs/expr.cc | 4 +-
be/src/exprs/literal.cc | 4 +-
be/src/exprs/null-literal.cc | 2 +-
be/src/exprs/scalar-fn-call.cc | 12 +-
be/src/exprs/slot-ref.cc | 48 +-
be/src/runtime/descriptors.cc | 132 ++--
be/src/runtime/descriptors.h | 40 +-
be/src/runtime/tuple.cc | 5 +-
be/src/runtime/types.h | 19 +-
be/src/testutil/test-udas.cc | 36 ++
be/src/testutil/test-udfs.cc | 6 +-
be/src/util/tuple-row-compare.cc | 2 +-
.../queries/QueryTest/java-udf.test | 104 ++--
.../QueryTest/libs_with_same_filenames.test | 11 +-
.../queries/QueryTest/load-java-udfs.test | 79 +--
.../queries/QueryTest/uda-mem-limit.test | 3 -
.../functional-query/queries/QueryTest/uda.test | 28 +
.../queries/QueryTest/udf-codegen-required.test | 10 +
.../queries/QueryTest/udf-errors.test | 37 +-
.../queries/QueryTest/udf-mem-limit.test | 5 -
.../functional-query/queries/QueryTest/udf.test | 7 -
tests/common/test_result_verifier.py | 22 +
tests/query_test/test_aggregation.py | 124 +++-
tests/query_test/test_udfs.py | 83 ++-
47 files changed, 1046 insertions(+), 809 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/benchmarks/hash-benchmark.cc
----------------------------------------------------------------------
diff --git a/be/src/benchmarks/hash-benchmark.cc b/be/src/benchmarks/hash-benchmark.cc
index 5ab7f5c..4f6d7f1 100644
--- a/be/src/benchmarks/hash-benchmark.cc
+++ b/be/src/benchmarks/hash-benchmark.cc
@@ -343,7 +343,7 @@ Function* CodegenCrcHash(LlvmCodeGen* codegen, bool mixed) {
prototype.AddArgument(
LlvmCodeGen::NamedVariable("results", codegen->GetPtrType(TYPE_INT)));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[3];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/codegen-anyval.cc
----------------------------------------------------------------------
diff --git a/be/src/codegen/codegen-anyval.cc b/be/src/codegen/codegen-anyval.cc
index a1ca6d9..bd27409 100644
--- a/be/src/codegen/codegen-anyval.cc
+++ b/be/src/codegen/codegen-anyval.cc
@@ -120,8 +120,7 @@ Type* CodegenAnyVal::GetUnloweredPtrType(LlvmCodeGen* cg, const ColumnType& type
return GetUnloweredType(cg, type)->getPointerTo();
}
-Value* CodegenAnyVal::CreateCall(
- LlvmCodeGen* cg, LlvmCodeGen::LlvmBuilder* builder, Function* fn,
+Value* CodegenAnyVal::CreateCall(LlvmCodeGen* cg, LlvmBuilder* builder, Function* fn,
ArrayRef<Value*> args, const char* name, Value* result_ptr) {
if (fn->getReturnType()->isVoidTy()) {
// Void return type indicates that this function returns a DecimalVal via the first
@@ -152,20 +151,15 @@ Value* CodegenAnyVal::CreateCall(
}
}
-CodegenAnyVal CodegenAnyVal::CreateCallWrapped(
- LlvmCodeGen* cg, LlvmCodeGen::LlvmBuilder* builder, const ColumnType& type,
- Function* fn, ArrayRef<Value*> args, const char* name) {
+CodegenAnyVal CodegenAnyVal::CreateCallWrapped(LlvmCodeGen* cg, LlvmBuilder* builder,
+ const ColumnType& type, Function* fn, ArrayRef<Value*> args, const char* name) {
Value* v = CreateCall(cg, builder, fn, args, name);
return CodegenAnyVal(cg, builder, type, v, name);
}
-CodegenAnyVal::CodegenAnyVal(LlvmCodeGen* codegen, LlvmCodeGen::LlvmBuilder* builder,
- const ColumnType& type, Value* value, const char* name)
- : type_(type),
- value_(value),
- name_(name),
- codegen_(codegen),
- builder_(builder) {
+CodegenAnyVal::CodegenAnyVal(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const ColumnType& type, Value* value, const char* name)
+ : type_(type), value_(value), name_(name), codegen_(codegen), builder_(builder) {
Type* value_type = GetLoweredType(codegen, type);
if (value_ == NULL) {
// No Value* was specified, so allocate one on the stack and load it.
@@ -175,7 +169,7 @@ CodegenAnyVal::CodegenAnyVal(LlvmCodeGen* codegen, LlvmCodeGen::LlvmBuilder* bui
DCHECK_EQ(value_->getType(), value_type);
}
-Value* CodegenAnyVal::GetIsNull(const char* name) {
+Value* CodegenAnyVal::GetIsNull(const char* name) const {
switch (type_.type) {
case TYPE_BIGINT:
case TYPE_DOUBLE: {
@@ -448,23 +442,28 @@ void CodegenAnyVal::SetDate(Value* date) {
value_ = builder_->CreateInsertValue(value_, v, 0, name_);
}
-Value* CodegenAnyVal::GetUnloweredPtr() {
- Value* value_ptr = codegen_->CreateEntryBlockAlloca(*builder_, value_->getType());
- builder_->CreateStore(value_, value_ptr);
- return builder_->CreateBitCast(value_ptr, GetUnloweredPtrType(codegen_, type_));
+Value* CodegenAnyVal::GetLoweredPtr(const string& name) const {
+ Value* lowered_ptr =
+ codegen_->CreateEntryBlockAlloca(*builder_, value_->getType(), name.c_str());
+ builder_->CreateStore(GetLoweredValue(), lowered_ptr);
+ return lowered_ptr;
}
-void CodegenAnyVal::SetFromRawPtr(Value* raw_ptr) {
- Value* val_ptr =
- builder_->CreateBitCast(raw_ptr, codegen_->GetPtrType(type_), "val_ptr");
- Value* val = builder_->CreateLoad(val_ptr);
- SetFromRawValue(val);
+Value* CodegenAnyVal::GetUnloweredPtr(const string& name) const {
+ // Get an unlowered pointer by creating a lowered pointer then bitcasting it.
+ // TODO: if the original value was unlowered, this generates roundabout code that
+ // lowers the value and casts it back. Generally LLVM's optimiser can reason
+ // about what's going on and undo our shenanigans to generate sane code, but it
+ // would be nice to just emit reasonable code in the first place.
+ return builder_->CreateBitCast(
+ GetLoweredPtr(), GetUnloweredPtrType(codegen_, type_), name);
}
void CodegenAnyVal::SetFromRawValue(Value* raw_val) {
DCHECK_EQ(raw_val->getType(), codegen_->GetType(type_))
- << endl << LlvmCodeGen::Print(raw_val)
- << endl << type_ << " => " << LlvmCodeGen::Print(codegen_->GetType(type_));
+ << endl
+ << LlvmCodeGen::Print(raw_val) << endl
+ << type_ << " => " << LlvmCodeGen::Print(codegen_->GetType(type_));
switch (type_.type) {
case TYPE_STRING:
case TYPE_VARCHAR: {
@@ -614,9 +613,7 @@ void CodegenAnyVal::WriteToSlot(const SlotDescriptor& slot_desc, Value* tuple,
// Null block: set null bit
builder_->SetInsertPoint(null_block);
- Function* set_null_fn = slot_desc.GetUpdateNullFn(codegen_, true);
- DCHECK(set_null_fn != NULL);
- builder_->CreateCall(set_null_fn, tuple);
+ slot_desc.CodegenSetNullIndicator(codegen_, builder_, tuple, codegen_->true_value());
builder_->CreateBr(insert_before);
// Leave builder_ after conditional blocks
@@ -704,6 +701,14 @@ Value* CodegenAnyVal::Compare(CodegenAnyVal* other, const char* name) {
return builder_->CreateCall(compare_fn, args, name);
}
+void CodegenAnyVal::CodegenBranchIfNull(LlvmBuilder* builder, BasicBlock* null_block) {
+ Value* is_null = GetIsNull();
+ BasicBlock* not_null_block = BasicBlock::Create(
+ codegen_->context(), "not_null", builder->GetInsertBlock()->getParent());
+ builder->CreateCondBr(is_null, null_block, not_null_block);
+ builder->SetInsertPoint(not_null_block);
+}
+
Value* CodegenAnyVal::GetHighBits(int num_bits, Value* v, const char* name) {
DCHECK_EQ(v->getType()->getIntegerBitWidth(), num_bits * 2);
Value* shifted = builder_->CreateAShr(v, num_bits);
@@ -762,8 +767,8 @@ Value* CodegenAnyVal::GetNullVal(LlvmCodeGen* codegen, Type* val_type) {
return ConstantInt::get(val_type, 1);
}
-CodegenAnyVal CodegenAnyVal::GetNonNullVal(LlvmCodeGen* codegen,
- LlvmCodeGen::LlvmBuilder* builder, const ColumnType& type, const char* name) {
+CodegenAnyVal CodegenAnyVal::GetNonNullVal(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const ColumnType& type, const char* name) {
Type* val_type = GetLoweredType(codegen, type);
// All zeros => 'is_null' = false
Value* value = Constant::getNullValue(val_type);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/codegen-anyval.h
----------------------------------------------------------------------
diff --git a/be/src/codegen/codegen-anyval.h b/be/src/codegen/codegen-anyval.h
index 290ca03..c07f3eb 100644
--- a/be/src/codegen/codegen-anyval.h
+++ b/be/src/codegen/codegen-anyval.h
@@ -51,6 +51,8 @@ namespace impala {
/// TYPE_DOUBLE/DoubleVal: { i8, double }
/// TYPE_STRING/StringVal: { i64, i8* }
/// TYPE_TIMESTAMP/TimestampVal: { i64, i64 }
+/// TYPE_DECIMAL/DecimalVal (isn't lowered):
+/// %"struct.impala_udf::DecimalVal" { {i8}, [15 x i8], {i128} }
//
/// TODO:
/// - unit tests
@@ -78,14 +80,14 @@ class CodegenAnyVal {
/// result will not be a pointer in this case).
//
/// 'name' optionally specifies the name of the returned value.
- static llvm::Value* CreateCall(LlvmCodeGen* cg, LlvmCodeGen::LlvmBuilder* builder,
+ static llvm::Value* CreateCall(LlvmCodeGen* cg, LlvmBuilder* builder,
llvm::Function* fn, llvm::ArrayRef<llvm::Value*> args, const char* name = "",
llvm::Value* result_ptr = NULL);
/// Same as above but wraps the result in a CodegenAnyVal.
- static CodegenAnyVal CreateCallWrapped(LlvmCodeGen* cg,
- LlvmCodeGen::LlvmBuilder* builder, const ColumnType& type, llvm::Function* fn,
- llvm::ArrayRef<llvm::Value*> args, const char* name = "");
+ static CodegenAnyVal CreateCallWrapped(LlvmCodeGen* cg, LlvmBuilder* builder,
+ const ColumnType& type, llvm::Function* fn, llvm::ArrayRef<llvm::Value*> args,
+ const char* name = "");
/// Returns the lowered AnyVal type associated with 'type'.
/// E.g.: TYPE_BOOLEAN (which corresponds to a BooleanVal) => i16
@@ -116,8 +118,8 @@ class CodegenAnyVal {
/// E.g.: TYPE_DOUBLE (lowered DoubleVal: { i8, double }) => { 0, 0 }
/// This returns a CodegenAnyVal, rather than the unwrapped Value*, because the actual
/// value still needs to be set.
- static CodegenAnyVal GetNonNullVal(LlvmCodeGen* codegen,
- LlvmCodeGen::LlvmBuilder* builder, const ColumnType& type, const char* name = "");
+ static CodegenAnyVal GetNonNullVal(LlvmCodeGen* codegen, LlvmBuilder* builder,
+ const ColumnType& type, const char* name = "");
/// Creates a wrapper around a lowered *Val value.
//
@@ -132,14 +134,14 @@ class CodegenAnyVal {
/// must be of the correct lowered type.
//
/// If 'name' is specified, it will be used when generated instructions that set value_.
- CodegenAnyVal(LlvmCodeGen* codegen, LlvmCodeGen::LlvmBuilder* builder,
- const ColumnType& type, llvm::Value* value = NULL, const char* name = "");
+ CodegenAnyVal(LlvmCodeGen* codegen, LlvmBuilder* builder, const ColumnType& type,
+ llvm::Value* value = NULL, const char* name = "");
/// Returns the current type-lowered value.
- llvm::Value* value() { return value_; }
+ llvm::Value* GetLoweredValue() const { return value_; }
/// Gets the 'is_null' field of the *Val.
- llvm::Value* GetIsNull(const char* name = "is_null");
+ llvm::Value* GetIsNull(const char* name = "is_null") const;
/// Get the 'val' field of the *Val. Do not call if this represents a StringVal or
/// TimestampVal. If this represents a DecimalVal, returns 'val4', 'val8', or 'val16'
@@ -180,19 +182,18 @@ class CodegenAnyVal {
void SetDate(llvm::Value* date);
void SetTimeOfDay(llvm::Value* time_of_day);
- /// Allocas and stores this value in an unlowered pointer, and returns the pointer. This
- /// *Val should be non-null.
- llvm::Value* GetUnloweredPtr();
+ /// Stores this value in an alloca allocation, and returns the pointer, which has the
+ /// lowered type. This *Val should be non-null. The output variable is called 'name'.
+ llvm::Value* GetLoweredPtr(const std::string& name = "") const;
+
+ /// Stores this value in an alloca allocation, and returns the pointer, which has the
+ /// unlowered type. This *Val should be non-null. The output variable is called 'name'.
+ llvm::Value* GetUnloweredPtr(const std::string& name = "") const;
/// Set this *Val's value based on 'raw_val'. 'raw_val' should be a native type,
/// StringValue, or TimestampValue.
void SetFromRawValue(llvm::Value* raw_val);
- /// Set this *Val's value based on void* 'raw_ptr'. 'raw_ptr' should be a pointer to a
- /// native type, StringValue, or TimestampValue (i.e. the value returned by an
- /// interpreted compute fn).
- void SetFromRawPtr(llvm::Value* raw_ptr);
-
/// Converts this *Val's value to a native type, StringValue, TimestampValue, etc.
/// This should only be used if this *Val is not null.
///
@@ -235,9 +236,23 @@ class CodegenAnyVal {
/// this < 'other', 0 if this == 'other', > 0 if this > 'other'.
llvm::Value* Compare(CodegenAnyVal* other, const char* name = "result");
+ /// Generate code to branch to 'null_block' if this value is NULL. The branch terminates
+ /// the current BasicBlock, so a new BasicBlock for the non-NULL case is also created,
+ /// and builder's insert position is set to the start of the non-NULL block.
+ ///
+ /// This corresponds to the C++ code:
+ /// if (val.is_null) goto null_block;
+ ///
+ /// non_null_block:
+ /// <-- Builder insert position after this function returns.
+ /// ...
+ /// null_block:
+ /// ...
+ void CodegenBranchIfNull(LlvmBuilder* builder, llvm::BasicBlock* null_block);
+
/// Ctor for created an uninitialized CodegenAnYVal that can be assigned to later.
CodegenAnyVal()
- : type_(INVALID_TYPE), value_(NULL), name_(NULL), codegen_(NULL), builder_(NULL) { }
+ : type_(INVALID_TYPE), value_(NULL), name_(NULL), codegen_(NULL), builder_(NULL) {}
private:
ColumnType type_;
@@ -245,7 +260,7 @@ class CodegenAnyVal {
const char* name_;
LlvmCodeGen* codegen_;
- LlvmCodeGen::LlvmBuilder* builder_;
+ LlvmBuilder* builder_;
/// Helper function for getting the top (most significant) half of 'v'.
/// 'v' should have width = 'num_bits' * 2 and be an integer type.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/gen_ir_descriptions.py
----------------------------------------------------------------------
diff --git a/be/src/codegen/gen_ir_descriptions.py b/be/src/codegen/gen_ir_descriptions.py
index ddcd1db..09f3a20 100755
--- a/be/src/codegen/gen_ir_descriptions.py
+++ b/be/src/codegen/gen_ir_descriptions.py
@@ -59,8 +59,8 @@ ir_functions = [
"_ZN6impala26PartitionedAggregationNode22ProcessBatchNoGroupingEPNS_8RowBatchE"],
["PART_AGG_NODE_PROCESS_BATCH_STREAMING",
"_ZN6impala26PartitionedAggregationNode21ProcessBatchStreamingEbNS_13TPrefetchMode4typeEPNS_8RowBatchES4_PNS_12HashTableCtxEPi"],
- ["PART_AGG_NODE_GET_EXPR_CTX",
- "_ZNK6impala26PartitionedAggregationNode17GetAggExprContextEi"],
+ ["PART_AGG_NODE_GET_EXPR_CTXS",
+ "_ZNK6impala26PartitionedAggregationNode18GetAggExprContextsEi"],
["AVG_UPDATE_BIGINT",
"_ZN6impala18AggregateFunctions9AvgUpdateIN10impala_udf9BigIntValEEEvPNS2_15FunctionContextERKT_PNS2_9StringValE"],
["AVG_UPDATE_DOUBLE",
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/llvm-codegen-test.cc
----------------------------------------------------------------------
diff --git a/be/src/codegen/llvm-codegen-test.cc b/be/src/codegen/llvm-codegen-test.cc
index e6f2f79..178baa2 100644
--- a/be/src/codegen/llvm-codegen-test.cc
+++ b/be/src/codegen/llvm-codegen-test.cc
@@ -124,7 +124,7 @@ TEST_F(LlvmCodeGenTest, BadIRFile) {
// The random int in there is the address of jitted_counter
Function* CodegenInnerLoop(LlvmCodeGen* codegen, int64_t* jitted_counter, int delta) {
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
LlvmCodeGen::FnPrototype fn_prototype(codegen, "JittedInnerLoop", codegen->void_type());
Function* jitted_loop_call = fn_prototype.GeneratePrototype();
@@ -173,10 +173,10 @@ TEST_F(LlvmCodeGenTest, ReplaceFnCall) {
ASSERT_OK(LlvmCodeGenTest::CreateFromFile(&pool, module_file.c_str(), &codegen));
EXPECT_TRUE(codegen.get() != NULL);
- Function* loop_call = codegen->GetFunction(loop_call_name);
+ Function* loop_call = codegen->GetFunction(loop_call_name, false);
EXPECT_TRUE(loop_call != NULL);
EXPECT_TRUE(loop_call->arg_empty());
- Function* loop = codegen->GetFunction(loop_name);
+ Function* loop = codegen->GetFunction(loop_name, false);
EXPECT_TRUE(loop != NULL);
EXPECT_EQ(loop->arg_size(), 1);
@@ -261,7 +261,7 @@ Function* CodegenStringTest(LlvmCodeGen* codegen) {
LlvmCodeGen::FnPrototype prototype(codegen, "StringTest", codegen->GetType(TYPE_INT));
prototype.AddArgument(LlvmCodeGen::NamedVariable("str", string_val_ptr_type));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* str;
Function* interop_fn = prototype.GeneratePrototype(&builder, &str);
@@ -340,7 +340,7 @@ TEST_F(LlvmCodeGenTest, MemcpyTest) {
prototype.AddArgument(LlvmCodeGen::NamedVariable("src", codegen->ptr_type()));
prototype.AddArgument(LlvmCodeGen::NamedVariable("n", codegen->GetType(TYPE_INT)));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
char src[] = "abcd";
char dst[] = "aaaa";
@@ -396,9 +396,9 @@ TEST_F(LlvmCodeGenTest, HashTest) {
// Create a codegen'd function that hashes all the types and returns the results.
// The tuple/values to hash are baked into the codegen for simplicity.
- LlvmCodeGen::FnPrototype prototype(codegen.get(), "HashTest",
- codegen->GetType(TYPE_INT));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmCodeGen::FnPrototype prototype(
+ codegen.get(), "HashTest", codegen->GetType(TYPE_INT));
+ LlvmBuilder builder(codegen->context());
// Test both byte-size specific hash functions and the generic loop hash function
Function* fn_fixed = prototype.GeneratePrototype(&builder, NULL);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/llvm-codegen.cc
----------------------------------------------------------------------
diff --git a/be/src/codegen/llvm-codegen.cc b/be/src/codegen/llvm-codegen.cc
index f629d35..f6e7e97 100644
--- a/be/src/codegen/llvm-codegen.cc
+++ b/be/src/codegen/llvm-codegen.cc
@@ -671,7 +671,7 @@ Status LlvmCodeGen::MaterializeFunction(Function *fn) {
return MaterializeFunctionHelper(fn);
}
-Function* LlvmCodeGen::GetFunction(const string& symbol) {
+Function* LlvmCodeGen::GetFunction(const string& symbol, bool clone) {
Function* fn = module_->getFunction(symbol.c_str());
if (fn == NULL) {
LOG(ERROR) << "Unable to locate function " << symbol;
@@ -679,6 +679,7 @@ Function* LlvmCodeGen::GetFunction(const string& symbol) {
}
Status status = MaterializeFunction(fn);
if (UNLIKELY(!status.ok())) return NULL;
+ if (clone) return CloneFunction(fn);
return fn;
}
@@ -1335,15 +1336,15 @@ Function* LlvmCodeGen::GetHashFunction(int num_bytes) {
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_BIGINT));
int i = 0;
while (num_bytes >= 8) {
- Value* index[] = { GetIntConstant(TYPE_INT, i++) };
- Value* d = builder.CreateLoad(builder.CreateGEP(ptr, index));
+ Value* index[] = {GetIntConstant(TYPE_INT, i++)};
+ Value* d = builder.CreateLoad(builder.CreateInBoundsGEP(ptr, index));
result_64 = builder.CreateCall(crc64_fn, ArrayRef<Value*>({result_64, d}));
num_bytes -= 8;
}
result = builder.CreateTrunc(result_64, GetType(TYPE_INT));
- Value* index[] = { GetIntConstant(TYPE_INT, i * 8) };
+ Value* index[] = {GetIntConstant(TYPE_INT, i * 8)};
// Update data to past the 8-byte chunks
- data = builder.CreateGEP(data, index);
+ data = builder.CreateInBoundsGEP(data, index);
}
if (num_bytes >= 4) {
@@ -1351,8 +1352,8 @@ Function* LlvmCodeGen::GetHashFunction(int num_bytes) {
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_INT));
Value* d = builder.CreateLoad(ptr);
result = builder.CreateCall(crc32_fn, ArrayRef<Value*>({result, d}));
- Value* index[] = { GetIntConstant(TYPE_INT, 4) };
- data = builder.CreateGEP(data, index);
+ Value* index[] = {GetIntConstant(TYPE_INT, 4)};
+ data = builder.CreateInBoundsGEP(data, index);
num_bytes -= 4;
}
@@ -1361,8 +1362,8 @@ Function* LlvmCodeGen::GetHashFunction(int num_bytes) {
Value* ptr = builder.CreateBitCast(data, GetPtrType(TYPE_SMALLINT));
Value* d = builder.CreateLoad(ptr);
result = builder.CreateCall(crc16_fn, ArrayRef<Value*>({result, d}));
- Value* index[] = { GetIntConstant(TYPE_INT, 2) };
- data = builder.CreateGEP(data, index);
+ Value* index[] = {GetIntConstant(TYPE_INT, 2)};
+ data = builder.CreateInBoundsGEP(data, index);
num_bytes -= 2;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/codegen/llvm-codegen.h
----------------------------------------------------------------------
diff --git a/be/src/codegen/llvm-codegen.h b/be/src/codegen/llvm-codegen.h
index 095f939..21f9f71 100644
--- a/be/src/codegen/llvm-codegen.h
+++ b/be/src/codegen/llvm-codegen.h
@@ -71,11 +71,15 @@ namespace llvm {
namespace impala {
-class CodegenAnyVal;
class CodegenSymbolEmitter;
class SubExprElimination;
class TupleDescriptor;
+/// Define builder subclass in case we want to change the template arguments later
+class LlvmBuilder : public llvm::IRBuilder<> {
+ using llvm::IRBuilder<>::IRBuilder;
+};
+
/// LLVM code generator. This is the top level object to generate jitted code.
//
/// LLVM provides a c++ IR builder interface so IR does not need to be written
@@ -157,9 +161,6 @@ class LlvmCodeGen {
/// If false, only output IR for functions which were generated.
std::string GetIR(bool full_module) const;
- /// Typedef builder in case we want to change the template arguments later
- typedef llvm::IRBuilder<> LlvmBuilder;
-
/// Utility struct that wraps a variable name and llvm type.
struct NamedVariable {
std::string name;
@@ -330,18 +331,22 @@ class LlvmCodeGen {
/// recursively. Returns NULL if there is any error.
///
/// If 'clone' is true, a clone of the function will be returned. Clones should be used
- /// iff the caller will modify the returned function. This avoids clobbering the
- /// function in case other users need it, but we don't clone if we can avoid it to
- /// reduce compilation time.
+ /// iff the caller will modify the returned function so that the original unmodified
+ /// function remains available. Avoid cloning if possible to reduce compilation time.
///
/// TODO: Return Status instead.
llvm::Function* GetFunction(IRFunction::Type ir_type, bool clone);
/// Return the function with the symbol name 'symbol' from the module. The returned
- /// function and its callee will be recursively materialized. The returned function
- /// isn't cloned. Returns NULL if there is any error.
+ /// function and its callee will be recursively materialized. Returns NULL if there is
+ /// any error.
+ ///
+ /// If 'clone' is true, a clone of the function will be returned. Clones should be used
+ /// iff the caller will modify the returned function so that the original unmodified
+ /// function remains available. Avoid cloning if possible to reduce compilation time.
+ ///
/// TODO: Return Status instead.
- llvm::Function* GetFunction(const string& symbol);
+ llvm::Function* GetFunction(const string& symbol, bool clone);
/// Returns the hash function with signature:
/// int32_t Hash(int8_t* data, int len, int32_t seed);
@@ -442,8 +447,8 @@ class LlvmCodeGen {
/// Codegens IR to load array[idx] and returns the loaded value. 'array' should be a
/// C-style array (e.g. i32*) or an IR array (e.g. [10 x i32]). This function does not
/// do bounds checking.
- llvm::Value* CodegenArrayAt(LlvmBuilder*, llvm::Value* array, int idx,
- const char* name = "");
+ llvm::Value* CodegenArrayAt(
+ LlvmBuilder*, llvm::Value* array, int idx, const char* name = "");
/// Loads a module at 'file' and links it to the module associated with
/// this LlvmCodeGen object. The module must be on the local filesystem.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/aggregation-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/aggregation-node.cc b/be/src/exec/aggregation-node.cc
index 67928ca..0607aa3 100644
--- a/be/src/exec/aggregation-node.cc
+++ b/be/src/exec/aggregation-node.cc
@@ -550,6 +550,10 @@ llvm::Function* AggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
codegen->GetPtrType(FunctionContextImpl::LLVM_FUNCTIONCONTEXT_NAME);
PointerType* expr_ctx_ptr_type = codegen->GetPtrType(ExprContext::LLVM_CLASS_NAME);
StructType* tuple_struct = intermediate_tuple_desc_->GetLlvmStruct(codegen);
+ if (tuple_struct == NULL) {
+ VLOG_QUERY << "Could not codegen UpdateSlot(): could not generate tuple struct.";
+ return NULL;
+ }
PointerType* tuple_ptr_type = codegen->GetPtrType(tuple_struct);
PointerType* tuple_row_ptr_type = codegen->GetPtrType(TupleRow::LLVM_CLASS_NAME);
@@ -560,7 +564,7 @@ llvm::Function* AggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_tuple", tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[4];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
Value* fn_ctx_arg = args[0];
@@ -588,8 +592,8 @@ llvm::Function* AggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
if (slot_desc->is_nullable()) {
// Dst is NULL, just update dst slot to src slot and clear null bit
- Function* clear_null_fn = slot_desc->GetUpdateNullFn(codegen, false);
- builder.CreateCall(clear_null_fn, ArrayRef<Value*>({agg_tuple_arg}));
+ slot_desc->CodegenSetNullIndicator(
+ codegen, &builder, agg_tuple_arg, codegen->false_value());
}
// Update the slot
@@ -630,32 +634,23 @@ llvm::Function* AggregationNode::CodegenUpdateSlot(LlvmCodeGen* codegen,
// Create pointer to src_anyval to pass to HllUpdate() function. We must use the
// unlowered type.
- Value* src_lowered_ptr = codegen->CreateEntryBlockAlloca(
- fn, LlvmCodeGen::NamedVariable("src_lowered_ptr", src.value()->getType()));
- builder.CreateStore(src.value(), src_lowered_ptr);
- Type* unlowered_ptr_type =
- CodegenAnyVal::GetUnloweredType(codegen, input_expr->type())->getPointerTo();
- Value* src_unlowered_ptr =
- builder.CreateBitCast(src_lowered_ptr, unlowered_ptr_type, "src_unlowered_ptr");
+ Value* src_unlowered_ptr = src.GetUnloweredPtr("src_unlowered_ptr");
// Create StringVal* intermediate argument from dst_value
- CodegenAnyVal dst_stringval = CodegenAnyVal::GetNonNullVal(
- codegen, &builder, TYPE_STRING, "dst_stringval");
+ CodegenAnyVal dst_stringval =
+ CodegenAnyVal::GetNonNullVal(codegen, &builder, TYPE_STRING, "dst_stringval");
dst_stringval.SetFromRawValue(dst_value);
// Create pointer to dst_stringval to pass to HllUpdate() function. We must use
// the unlowered type.
- Value* dst_lowered_ptr = codegen->CreateEntryBlockAlloca(
- fn, LlvmCodeGen::NamedVariable("dst_lowered_ptr",
- dst_stringval.value()->getType()));
- builder.CreateStore(dst_stringval.value(), dst_lowered_ptr);
- unlowered_ptr_type =
+ Value* dst_lowered_ptr = dst_stringval.GetLoweredPtr("dst_lowered_ptr");
+ Type* dst_unlowered_ptr_type =
codegen->GetPtrType(CodegenAnyVal::GetUnloweredType(codegen, TYPE_STRING));
- Value* dst_unlowered_ptr =
- builder.CreateBitCast(dst_lowered_ptr, unlowered_ptr_type, "dst_unlowered_ptr");
+ Value* dst_unlowered_ptr = builder.CreateBitCast(
+ dst_lowered_ptr, dst_unlowered_ptr_type, "dst_unlowered_ptr");
// Call 'hll_fn'
- builder.CreateCall(hll_fn,
- ArrayRef<Value*>({fn_ctx_arg, src_unlowered_ptr, dst_unlowered_ptr}));
+ builder.CreateCall(
+ hll_fn, ArrayRef<Value*>({fn_ctx_arg, src_unlowered_ptr, dst_unlowered_ptr}));
// Convert StringVal intermediate 'dst_arg' back to StringValue
Value* anyval_result = builder.CreateLoad(dst_lowered_ptr, "anyval_result");
@@ -765,13 +760,17 @@ Function* AggregationNode::CodegenUpdateTuple(LlvmCodeGen* codegen) {
// ExprContext** expr_ctx, Tuple* tuple, TupleRow* row)
// This signature needs to match the non-codegen'd signature exactly.
StructType* tuple_struct = intermediate_tuple_desc_->GetLlvmStruct(codegen);
+ if (tuple_struct == NULL) {
+ VLOG_QUERY << "Could not codegen UpdateSlot(): could not generate tuple struct.";
+ return NULL;
+ }
PointerType* tuple_ptr = PointerType::get(tuple_struct, 0);
LlvmCodeGen::FnPrototype prototype(codegen, "UpdateTuple", codegen->void_type());
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", agg_node_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("agg_tuple", agg_tuple_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("tuple_row", tuple_row_ptr_type));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[3];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/exec-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/exec-node.cc b/be/src/exec/exec-node.cc
index 510a7d9..255217f 100644
--- a/be/src/exec/exec-node.cc
+++ b/be/src/exec/exec-node.cc
@@ -519,7 +519,7 @@ Status ExecNode::CodegenEvalConjuncts(LlvmCodeGen* codegen,
LlvmCodeGen::NamedVariable("num_ctxs", codegen->GetType(TYPE_INT)));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
- LlvmCodeGen::LlvmBuilder builder(codegen->context());
+ LlvmBuilder builder(codegen->context());
Value* args[3];
*fn = prototype.GeneratePrototype(&builder, args);
Value* ctxs_arg = args[0];
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/hash-join-node.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hash-join-node.cc b/be/src/exec/hash-join-node.cc
index f2ac928..7c335be 100644
--- a/be/src/exec/hash-join-node.cc
+++ b/be/src/exec/hash-join-node.cc
@@ -548,7 +548,7 @@ Function* HashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen) {
prototype.AddArgument(LlvmCodeGen::NamedVariable("build_arg", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[4];
Function* fn = prototype.GeneratePrototype(&builder, args);
Value* out_row_arg = builder.CreateBitCast(args[1], tuple_row_working_type, "out");
@@ -560,8 +560,9 @@ Function* HashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen) {
// Copy probe row
codegen->CodegenMemcpy(&builder, out_row_arg, probe_row_arg, probe_tuple_row_size_);
- Value* build_row_idx[] = { codegen->GetIntConstant(TYPE_INT, num_probe_tuples) };
- Value* build_row_dst = builder.CreateGEP(out_row_arg, build_row_idx, "build_dst_ptr");
+ Value* build_row_idx[] = {codegen->GetIntConstant(TYPE_INT, num_probe_tuples)};
+ Value* build_row_dst =
+ builder.CreateInBoundsGEP(out_row_arg, build_row_idx, "build_dst_ptr");
// Copy build row.
BasicBlock* build_not_null_block = BasicBlock::Create(context, "build_not_null", fn);
@@ -578,9 +579,8 @@ Function* HashJoinNode::CodegenCreateOutputRow(LlvmCodeGen* codegen) {
// to work.
builder.SetInsertPoint(build_null_block);
for (int i = 0; i < num_build_tuples; ++i) {
- Value* array_idx[] =
- { codegen->GetIntConstant(TYPE_INT, i + num_probe_tuples) };
- Value* dst = builder.CreateGEP(out_row_arg, array_idx, "dst_tuple_ptr");
+ Value* array_idx[] = {codegen->GetIntConstant(TYPE_INT, i + num_probe_tuples)};
+ Value* dst = builder.CreateInBoundsGEP(out_row_arg, array_idx, "dst_tuple_ptr");
builder.CreateStore(codegen->null_ptr_value(), dst);
}
builder.CreateRetVoid();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/hash-table.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hash-table.cc b/be/src/exec/hash-table.cc
index 74fc534..8d45ec7 100644
--- a/be/src/exec/hash-table.cc
+++ b/be/src/exec/hash-table.cc
@@ -567,8 +567,8 @@ string HashTable::PrintStats() const {
// Helper function to store a value into the results buffer if the expr
// evaluated to NULL. We don't want (NULL, 1) to hash to the same as (0,1) so
// we'll pick a more random value.
-static void CodegenAssignNullValue(LlvmCodeGen* codegen,
- LlvmCodeGen::LlvmBuilder* builder, Value* dst, const ColumnType& type) {
+static void CodegenAssignNullValue(
+ LlvmCodeGen* codegen, LlvmBuilder* builder, Value* dst, const ColumnType& type) {
uint64_t fnv_seed = HashUtil::FNV_SEED;
if (type.type == TYPE_STRING || type.type == TYPE_VARCHAR) {
@@ -715,11 +715,11 @@ Status HashTableCtx::CodegenEvalRow(LlvmCodeGen* codegen, bool build, Function**
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", this_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
prototype.AddArgument(LlvmCodeGen::NamedVariable("expr_values", codegen->ptr_type()));
- prototype.AddArgument(LlvmCodeGen::NamedVariable("expr_values_null",
- codegen->ptr_type()));
+ prototype.AddArgument(
+ LlvmCodeGen::NamedVariable("expr_values_null", codegen->ptr_type()));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[4];
*fn = prototype.GeneratePrototype(&builder, args);
Value* this_ptr = args[0];
@@ -740,10 +740,10 @@ Status HashTableCtx::CodegenEvalRow(LlvmCodeGen* codegen, bool build, Function**
// vector of exprs
// Convert result buffer to llvm ptr type
int offset = expr_values_cache_.expr_values_offsets(i);
- Value* loc = builder.CreateGEP(
+ Value* loc = builder.CreateInBoundsGEP(
NULL, expr_values, codegen->GetIntConstant(TYPE_INT, offset), "loc_addr");
- Value* llvm_loc = builder.CreatePointerCast(loc,
- codegen->GetPtrType(ctxs[i]->root()->type()), "loc");
+ Value* llvm_loc = builder.CreatePointerCast(
+ loc, codegen->GetPtrType(ctxs[i]->root()->type()), "loc");
BasicBlock* null_block = BasicBlock::Create(context, "null", *fn);
BasicBlock* not_null_block = BasicBlock::Create(context, "not_null", *fn);
@@ -768,7 +768,7 @@ Status HashTableCtx::CodegenEvalRow(LlvmCodeGen* codegen, bool build, Function**
// Set null-byte result
Value* null_byte = builder.CreateZExt(is_null, codegen->GetType(TYPE_TINYINT));
- Value* llvm_null_byte_loc = builder.CreateGEP(
+ Value* llvm_null_byte_loc = builder.CreateInBoundsGEP(
NULL, expr_values_null, codegen->GetIntConstant(TYPE_INT, i), "null_byte_loc");
builder.CreateStore(null_byte, llvm_null_byte_loc);
builder.CreateCondBr(is_null, null_block, not_null_block);
@@ -863,7 +863,7 @@ Status HashTableCtx::CodegenHashRow(LlvmCodeGen* codegen, bool use_murmur, Funct
LlvmCodeGen::NamedVariable("expr_values_null", codegen->ptr_type()));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[3];
*fn = prototype.GeneratePrototype(&builder, args);
Value* this_arg = args[0];
@@ -910,7 +910,7 @@ Status HashTableCtx::CodegenHashRow(LlvmCodeGen* codegen, bool use_murmur, Funct
Value* str_null_result = NULL;
int offset = expr_values_cache_.expr_values_offsets(i);
- Value* llvm_loc = builder.CreateGEP(
+ Value* llvm_loc = builder.CreateInBoundsGEP(
NULL, expr_values, codegen->GetIntConstant(TYPE_INT, offset), "loc_addr");
// If the hash table stores nulls, we need to check if the stringval
@@ -920,11 +920,11 @@ Status HashTableCtx::CodegenHashRow(LlvmCodeGen* codegen, bool use_murmur, Funct
not_null_block = BasicBlock::Create(context, "not_null", *fn);
continue_block = BasicBlock::Create(context, "continue", *fn);
- Value* llvm_null_byte_loc = builder.CreateGEP(NULL, expr_values_null,
+ Value* llvm_null_byte_loc = builder.CreateInBoundsGEP(NULL, expr_values_null,
codegen->GetIntConstant(TYPE_INT, i), "null_byte_loc");
Value* null_byte = builder.CreateLoad(llvm_null_byte_loc, "null_byte");
- Value* is_null = builder.CreateICmpNE(null_byte,
- codegen->GetIntConstant(TYPE_TINYINT, 0), "is_null");
+ Value* is_null = builder.CreateICmpNE(
+ null_byte, codegen->GetIntConstant(TYPE_TINYINT, 0), "is_null");
builder.CreateCondBr(is_null, null_block, not_null_block);
// For null, we just want to call the hash function on the portion of
@@ -1071,7 +1071,7 @@ Status HashTableCtx::CodegenEquals(LlvmCodeGen* codegen, bool force_null_equalit
LlvmCodeGen::NamedVariable("expr_values_null", codegen->ptr_type()));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[4];
*fn = prototype.GeneratePrototype(&builder, args);
Value* this_ptr = args[0];
@@ -1116,19 +1116,19 @@ Status HashTableCtx::CodegenEquals(LlvmCodeGen* codegen, bool force_null_equalit
// We consider null values equal if we are comparing build rows or if the join
// predicate is <=>
if (force_null_equality || finds_nulls_[i]) {
- Value* llvm_null_byte_loc = builder.CreateGEP(
+ Value* llvm_null_byte_loc = builder.CreateInBoundsGEP(
NULL, expr_values_null, codegen->GetIntConstant(TYPE_INT, i), "null_byte_loc");
Value* null_byte = builder.CreateLoad(llvm_null_byte_loc);
- row_is_null = builder.CreateICmpNE(null_byte,
- codegen->GetIntConstant(TYPE_TINYINT, 0));
+ row_is_null =
+ builder.CreateICmpNE(null_byte, codegen->GetIntConstant(TYPE_TINYINT, 0));
}
// Get llvm value for row_val from 'expr_values'
int offset = expr_values_cache_.expr_values_offsets(i);
- Value* loc = builder.CreateGEP(
+ Value* loc = builder.CreateInBoundsGEP(
NULL, expr_values, codegen->GetIntConstant(TYPE_INT, offset), "loc");
- Value* row_val = builder.CreatePointerCast(loc,
- codegen->GetPtrType(build_expr_ctxs_[i]->root()->type()), "row_val");
+ Value* row_val = builder.CreatePointerCast(
+ loc, codegen->GetPtrType(build_expr_ctxs_[i]->root()->type()), "row_val");
// Branch for GetValue() returning NULL
builder.CreateCondBr(is_null, null_block, not_null_block);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/hdfs-avro-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-avro-scanner.cc b/be/src/exec/hdfs-avro-scanner.cc
index a073cef..c217b65 100644
--- a/be/src/exec/hdfs-avro-scanner.cc
+++ b/be/src/exec/hdfs-avro-scanner.cc
@@ -776,10 +776,10 @@ void HdfsAvroScanner::SetStatusValueOverflow(TErrorCode::type error_code, int64_
// bail_out: ; preds = %read_field11, %end_field3, %read_field2, %end_field,
// ret i1 false ; %read_field, %entry
// }
-Status HdfsAvroScanner::CodegenMaterializeTuple(HdfsScanNodeBase* node,
- LlvmCodeGen* codegen, Function** materialize_tuple_fn) {
+Status HdfsAvroScanner::CodegenMaterializeTuple(
+ HdfsScanNodeBase* node, LlvmCodeGen* codegen, Function** materialize_tuple_fn) {
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Type* this_type = codegen->GetType(HdfsAvroScanner::LLVM_CLASS_NAME);
DCHECK(this_type != NULL);
@@ -853,8 +853,7 @@ Status HdfsAvroScanner::CodegenReadRecord(
}
DCHECK_EQ(record.schema->type, AVRO_RECORD);
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder* builder =
- reinterpret_cast<LlvmCodeGen::LlvmBuilder*>(void_builder);
+ LlvmBuilder* builder = reinterpret_cast<LlvmBuilder*>(void_builder);
// Codegen logic for parsing each field and, if necessary, populating a slot with the
// result.
@@ -911,9 +910,8 @@ Status HdfsAvroScanner::CodegenReadRecord(
// Write null field IR
builder->SetInsertPoint(null_block);
if (slot_idx != HdfsScanNode::SKIP_COLUMN) {
- Function* set_null_fn = slot_desc->GetUpdateNullFn(codegen, true);
- DCHECK(set_null_fn != NULL);
- builder->CreateCall(set_null_fn, ArrayRef<Value*>({tuple_val}));
+ slot_desc->CodegenSetNullIndicator(
+ codegen, builder, tuple_val, codegen->true_value());
}
// LLVM requires all basic blocks to end with a terminating instruction
builder->CreateBr(end_field_block);
@@ -944,11 +942,10 @@ Status HdfsAvroScanner::CodegenReadRecord(
}
Status HdfsAvroScanner::CodegenReadScalar(const AvroSchemaElement& element,
- SlotDescriptor* slot_desc, LlvmCodeGen* codegen, void* void_builder,
- Value* this_val, Value* pool_val, Value* tuple_val, Value* data_val,
- Value* data_end_val, Value** ret_val) {
- LlvmCodeGen::LlvmBuilder* builder =
- reinterpret_cast<LlvmCodeGen::LlvmBuilder*>(void_builder);
+ SlotDescriptor* slot_desc, LlvmCodeGen* codegen, void* void_builder, Value* this_val,
+ Value* pool_val, Value* tuple_val, Value* data_val, Value* data_end_val,
+ Value** ret_val) {
+ LlvmBuilder* builder = reinterpret_cast<LlvmBuilder*>(void_builder);
Function* read_field_fn;
switch (element.schema->type) {
case AVRO_BOOLEAN:
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/hdfs-scanner.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/hdfs-scanner.cc b/be/src/exec/hdfs-scanner.cc
index 3885522..390085f 100644
--- a/be/src/exec/hdfs-scanner.cc
+++ b/be/src/exec/hdfs-scanner.cc
@@ -380,7 +380,7 @@ Status HdfsScanner::CodegenWriteCompleteTuple(HdfsScanNodeBase* node,
prototype.AddArgument(LlvmCodeGen::NamedVariable("error_in_row", uint8_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[8];
Function* fn = prototype.GeneratePrototype(&builder, &args[0]);
@@ -411,8 +411,8 @@ Status HdfsScanner::CodegenWriteCompleteTuple(HdfsScanNodeBase* node,
// Put tuple in tuple_row
Value* tuple_row_typed =
builder.CreateBitCast(tuple_row_arg, PointerType::get(tuple_ptr_type, 0));
- Value* tuple_row_idxs[] = { codegen->GetIntConstant(TYPE_INT, node->tuple_idx()) };
- Value* tuple_in_row_addr = builder.CreateGEP(tuple_row_typed, tuple_row_idxs);
+ Value* tuple_row_idxs[] = {codegen->GetIntConstant(TYPE_INT, node->tuple_idx())};
+ Value* tuple_in_row_addr = builder.CreateInBoundsGEP(tuple_row_typed, tuple_row_idxs);
builder.CreateStore(tuple_arg, tuple_in_row_addr);
builder.CreateBr(parse_block);
@@ -447,11 +447,12 @@ Status HdfsScanner::CodegenWriteCompleteTuple(HdfsScanNodeBase* node,
codegen->GetIntConstant(TYPE_INT, 1),
};
Value* error_idxs[] = {
- codegen->GetIntConstant(TYPE_INT, slot_idx),
+ codegen->GetIntConstant(TYPE_INT, slot_idx),
};
- Value* data_ptr = builder.CreateGEP(fields_arg, data_idxs, "data_ptr");
- Value* len_ptr = builder.CreateGEP(fields_arg, len_idxs, "len_ptr");
- Value* error_ptr = builder.CreateGEP(errors_arg, error_idxs, "slot_error_ptr");
+ Value* data_ptr = builder.CreateInBoundsGEP(fields_arg, data_idxs, "data_ptr");
+ Value* len_ptr = builder.CreateInBoundsGEP(fields_arg, len_idxs, "len_ptr");
+ Value* error_ptr =
+ builder.CreateInBoundsGEP(errors_arg, error_idxs, "slot_error_ptr");
Value* data = builder.CreateLoad(data_ptr, "data");
Value* len = builder.CreateLoad(len_ptr, "len");
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/old-hash-table.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/old-hash-table.cc b/be/src/exec/old-hash-table.cc
index f51bc74..44bf7e4 100644
--- a/be/src/exec/old-hash-table.cc
+++ b/be/src/exec/old-hash-table.cc
@@ -182,8 +182,8 @@ int OldHashTable::AddBloomFilters() {
// Helper function to store a value into the results buffer if the expr
// evaluated to NULL. We don't want (NULL, 1) to hash to the same as (0,1) so
// we'll pick a more random value.
-static void CodegenAssignNullValue(LlvmCodeGen* codegen,
- LlvmCodeGen::LlvmBuilder* builder, Value* dst, const ColumnType& type) {
+static void CodegenAssignNullValue(
+ LlvmCodeGen* codegen, LlvmBuilder* builder, Value* dst, const ColumnType& type) {
uint64_t fnv_seed = HashUtil::FNV_SEED;
if (type.type == TYPE_STRING || type.type == TYPE_VARCHAR) {
@@ -288,7 +288,7 @@ Function* OldHashTable::CodegenEvalTupleRow(LlvmCodeGen* codegen, bool build) {
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[2];
Function* fn = prototype.GeneratePrototype(&builder, args);
@@ -429,7 +429,7 @@ Function* OldHashTable::CodegenHashCurrentRow(LlvmCodeGen* codegen) {
prototype.AddArgument(LlvmCodeGen::NamedVariable("this_ptr", this_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* this_arg;
Function* fn = prototype.GeneratePrototype(&builder, &this_arg);
@@ -612,7 +612,7 @@ Function* OldHashTable::CodegenEquals(LlvmCodeGen* codegen) {
prototype.AddArgument(LlvmCodeGen::NamedVariable("row", tuple_row_ptr_type));
LLVMContext& context = codegen->context();
- LlvmCodeGen::LlvmBuilder builder(context);
+ LlvmBuilder builder(context);
Value* args[2];
Function* fn = prototype.GeneratePrototype(&builder, args);
Value* row = args[1];
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/d7246d64/be/src/exec/partitioned-aggregation-node-ir.cc
----------------------------------------------------------------------
diff --git a/be/src/exec/partitioned-aggregation-node-ir.cc b/be/src/exec/partitioned-aggregation-node-ir.cc
index 83362e7..b696131 100644
--- a/be/src/exec/partitioned-aggregation-node-ir.cc
+++ b/be/src/exec/partitioned-aggregation-node-ir.cc
@@ -26,7 +26,7 @@
using namespace impala;
-ExprContext* PartitionedAggregationNode::GetAggExprContext(int i) const {
+ExprContext* const* PartitionedAggregationNode::GetAggExprContexts(int i) const {
return agg_expr_ctxs_[i];
}
[16/50] [abbrv] incubator-impala git commit: IMPALA-3872: allow
providing PyPi mirror for python packages
Posted by ta...@apache.org.
IMPALA-3872: allow providing PyPi mirror for python packages
We still rely on the python.org json API, which doesn't seem to be
mirrored (instead there's a html-based index format implemented by
the mirrors).
The mirror can be provided by setting the PYPI_MIRROR environment
variable. The default is "https://pypi.python.org".
Change-Id: Ibc11f010332c0225121c86c9930e35c7ac01409c
Reviewed-on: http://gerrit.cloudera.org:8080/4770
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/51b13106
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/51b13106
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/51b13106
Branch: refs/heads/hadoop-next
Commit: 51b1310681d07308fb508a038a4fdf5a1e73b5e8
Parents: 381e719
Author: Tim Armstrong <ta...@cloudera.com>
Authored: Wed Oct 19 11:09:35 2016 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 05:34:50 2016 +0000
----------------------------------------------------------------------
infra/python/deps/pip_download.py | 10 ++++++++--
1 file changed, 8 insertions(+), 2 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/51b13106/infra/python/deps/pip_download.py
----------------------------------------------------------------------
diff --git a/infra/python/deps/pip_download.py b/infra/python/deps/pip_download.py
index 658d0cc..a3c6a09 100755
--- a/infra/python/deps/pip_download.py
+++ b/infra/python/deps/pip_download.py
@@ -22,6 +22,7 @@
# This script requires Python 2.6+.
import json
+import os
import os.path
import sys
from hashlib import md5
@@ -30,6 +31,8 @@ from urllib import urlopen, URLopener
NUM_TRIES = 3
+PYPI_MIRROR = os.environ.get("PYPI_MIRROR", "https://pypi.python.org")
+
def check_md5sum(filename, expected_md5):
actual_md5 = md5(open(filename).read()).hexdigest()
return actual_md5 == expected_md5
@@ -55,6 +58,8 @@ def download_package(pkg_name, pkg_version):
'''Download the required package. Sometimes the download can be flaky, so we use the
retry decorator.'''
pkg_type = 'sdist' # Don't download wheel archives for now
+ # This JSON endpoint is not provided by PyPI mirrors so we always need to get this
+ # from pypi.python.org.
pkg_info = json.loads(urlopen('https://pypi.python.org/pypi/%s/json' % pkg_name).read())
downloader = URLopener()
@@ -65,8 +70,9 @@ def download_package(pkg_name, pkg_version):
if os.path.isfile(filename) and check_md5sum(filename, expected_md5):
print "File with matching md5sum already exists, skipping %s" % filename
return True
- print "Downloading %s from %s " % (filename, pkg['url'])
- downloader.retrieve(pkg['url'], filename)
+ pkg_url = "{0}/packages/{1}".format(PYPI_MIRROR, pkg['path'])
+ print "Downloading %s from %s" % (filename, pkg_url)
+ downloader.retrieve(pkg_url, filename)
actual_md5 = md5(open(filename).read()).hexdigest()
if check_md5sum(filename, expected_md5):
return True
[07/50] [abbrv] incubator-impala git commit: IMPALA-4048: Misc.
improvements to /sessions
Posted by ta...@apache.org.
IMPALA-4048: Misc. improvements to /sessions
* Make table searchable and sortable
* Fix 'last accessed time' being printed in UTC
* Made table contents more compact so that it mostly fits on screen
* Clarify summary text re: active and inactive sessions
* Include fix in mustache-cpp required to print 64-bit integers
correctly (see
https://github.com/henryr/cpp-mustache/commit/29768bf0e84f5a1e95e006fc64996d375499dbda)
Testing: Visual inspection and manual sorting, searching etc.
Change-Id: I14edcb6d60cf031a62c5a20b2d2b4d23248633a3
Reviewed-on: http://gerrit.cloudera.org:8080/4880
Reviewed-by: Thomas Tauber-Marshall <tm...@cloudera.com>
Tested-by: Internal Jenkins
Reviewed-by: Tim Armstrong <ta...@cloudera.com>
Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/c62d8244
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/c62d8244
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/c62d8244
Branch: refs/heads/hadoop-next
Commit: c62d8244a4c3c674367dfa90831fc714d869ecb0
Parents: 58d8861
Author: Henry Robinson <he...@cloudera.com>
Authored: Fri Oct 28 15:01:26 2016 -0700
Committer: Henry Robinson <he...@cloudera.com>
Committed: Mon Nov 7 20:50:04 2016 +0000
----------------------------------------------------------------------
be/src/service/impala-hs2-server.cc | 2 +-
be/src/service/impala-http-handler.cc | 18 +++++-
be/src/service/impala-server.cc | 2 +-
be/src/service/impala-server.h | 6 +-
be/src/thirdparty/mustache/mustache.cc | 2 +
www/sessions.tmpl | 94 +++++++++++++++++------------
6 files changed, 78 insertions(+), 46 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/be/src/service/impala-hs2-server.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-hs2-server.cc b/be/src/service/impala-hs2-server.cc
index 05a58a4..eb96359 100644
--- a/be/src/service/impala-hs2-server.cc
+++ b/be/src/service/impala-hs2-server.cc
@@ -281,7 +281,7 @@ void ImpalaServer::OpenSession(TOpenSessionResp& return_val,
// TODO: Fix duplication of code between here and ConnectionStart().
shared_ptr<SessionState> state = make_shared<SessionState>();
state->closed = false;
- state->start_time = TimestampValue::LocalTime();
+ state->start_time_ms = UnixMillis();
state->session_type = TSessionType::HIVESERVER2;
state->network_address = ThriftServer::GetThreadConnectionContext()->network_address;
state->last_accessed_ms = UnixMillis();
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/be/src/service/impala-http-handler.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-http-handler.cc b/be/src/service/impala-http-handler.cc
index b335a29..834fd42 100644
--- a/be/src/service/impala-http-handler.cc
+++ b/be/src/service/impala-http-handler.cc
@@ -427,6 +427,7 @@ void ImpalaHttpHandler::SessionsHandler(const Webserver::ArgumentMap& args,
Document* document) {
lock_guard<mutex> l(server_->session_state_map_lock_);
Value sessions(kArrayType);
+ int num_active = 0;
for (const ImpalaServer::SessionStateMap::value_type& session:
server_->session_state_map_) {
shared_ptr<ImpalaServer::SessionState> state = session.second;
@@ -457,18 +458,26 @@ void ImpalaHttpHandler::SessionsHandler(const Webserver::ArgumentMap& args,
Value default_db(state->database.c_str(), document->GetAllocator());
session_json.AddMember("default_database", default_db, document->GetAllocator());
- Value start_time(state->start_time.DebugString().c_str(), document->GetAllocator());
+ TimestampValue local_start_time(session.second->start_time_ms / 1000);
+ local_start_time.UtcToLocal();
+ Value start_time(local_start_time.DebugString().c_str(), document->GetAllocator());
session_json.AddMember("start_time", start_time, document->GetAllocator());
+ session_json.AddMember(
+ "start_time_sort", session.second->start_time_ms, document->GetAllocator());
+ TimestampValue local_last_accessed(session.second->last_accessed_ms / 1000);
+ local_last_accessed.UtcToLocal();
Value last_accessed(
- TimestampValue(session.second->last_accessed_ms / 1000).DebugString().c_str(),
- document->GetAllocator());
+ local_last_accessed.DebugString().c_str(), document->GetAllocator());
session_json.AddMember("last_accessed", last_accessed, document->GetAllocator());
+ session_json.AddMember(
+ "last_accessed_sort", session.second->last_accessed_ms, document->GetAllocator());
session_json.AddMember("session_timeout", state->session_timeout,
document->GetAllocator());
session_json.AddMember("expired", state->expired, document->GetAllocator());
session_json.AddMember("closed", state->closed, document->GetAllocator());
+ if (!state->expired && !state->closed) ++num_active;
session_json.AddMember("ref_count", state->ref_count, document->GetAllocator());
sessions.PushBack(session_json, document->GetAllocator());
}
@@ -477,6 +486,9 @@ void ImpalaHttpHandler::SessionsHandler(const Webserver::ArgumentMap& args,
document->AddMember("num_sessions",
static_cast<uint64_t>(server_->session_state_map_.size()),
document->GetAllocator());
+ document->AddMember("num_active", num_active, document->GetAllocator());
+ document->AddMember("num_inactive", server_->session_state_map_.size() - num_active,
+ document->GetAllocator());
}
void ImpalaHttpHandler::CatalogHandler(const Webserver::ArgumentMap& args,
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/be/src/service/impala-server.cc
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.cc b/be/src/service/impala-server.cc
index c7180fd..024cd24 100644
--- a/be/src/service/impala-server.cc
+++ b/be/src/service/impala-server.cc
@@ -1621,7 +1621,7 @@ void ImpalaServer::ConnectionStart(
shared_ptr<SessionState> session_state;
session_state.reset(new SessionState);
session_state->closed = false;
- session_state->start_time = TimestampValue::LocalTime();
+ session_state->start_time_ms = UnixMillis();
session_state->last_accessed_ms = UnixMillis();
session_state->database = "default";
session_state->session_timeout = FLAGS_idle_session_timeout;
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/be/src/service/impala-server.h
----------------------------------------------------------------------
diff --git a/be/src/service/impala-server.h b/be/src/service/impala-server.h
index b884ea4..836e619 100644
--- a/be/src/service/impala-server.h
+++ b/be/src/service/impala-server.h
@@ -687,8 +687,8 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
TSessionType::type session_type;
- /// Time the session was created.
- TimestampValue start_time;
+ /// Time the session was created, in ms since epoch (UTC).
+ int64_t start_time_ms;
/// Connected user for this session, i.e. the user which originated this session.
std::string connected_user;
@@ -733,7 +733,7 @@ class ImpalaServer : public ImpalaServiceIf, public ImpalaHiveServer2ServiceIf,
/// Total number of queries run as part of this session.
int64_t total_queries;
- /// Time the session was last accessed.
+ /// Time the session was last accessed, in ms since epoch (UTC).
int64_t last_accessed_ms;
/// The latest Kudu timestamp observed after DML operations executed within this
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/be/src/thirdparty/mustache/mustache.cc
----------------------------------------------------------------------
diff --git a/be/src/thirdparty/mustache/mustache.cc b/be/src/thirdparty/mustache/mustache.cc
index 59aeafc..7d5a840 100644
--- a/be/src/thirdparty/mustache/mustache.cc
+++ b/be/src/thirdparty/mustache/mustache.cc
@@ -275,6 +275,8 @@ int EvaluateSubstitution(const string& document, const int idx,
// TODO: Triple {{{ means don't escape
(*out) << context->GetString();
}
+ } else if (context->IsInt64()) {
+ (*out) << context->GetInt64();
} else if (context->IsInt()) {
(*out) << context->GetInt();
} else if (context->IsDouble()) {
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c62d8244/www/sessions.tmpl
----------------------------------------------------------------------
diff --git a/www/sessions.tmpl b/www/sessions.tmpl
index e0a5216..8c4f206 100644
--- a/www/sessions.tmpl
+++ b/www/sessions.tmpl
@@ -19,45 +19,63 @@ under the License.
{{> www/common-header.tmpl }}
<h2>Sessions</h2>
-There are {{num_sessions}} active sessions.
-<table class='table table-bordered table-hover'>
- <tr>
- <th>Session Type</th>
- <th>Open Queries</th>
- <th>Total Queries</th>
- <th>User</th>
- <th>Delegated User</th>
- <th>Session ID</th>
- <th>Network Address</th>
- <th>Default Database</th>
- <th>Start Time</th>
- <th>Last Accessed</th>
- <th>Idle Timeout (s)</th>
- <th>Expired</th>
- <th>Closed</th>
- <th>Ref count</th>
- <th>Action</th>
- </tr>
-{{#sessions}}
- <tr>
- <td>{{type}}</td>
- <td>{{inflight_queries}}</td>
- <td>{{total_queries}}</td>
- <td>{{user}}</td>
- <td>{{delegated_user}}</td>
- <td>{{session_id}}</td>
- <td>{{network_address}}</td>
- <td>{{default_database}}</td>
- <td>{{start_time}}</td>
- <td>{{last_accessed}}</td>
- <td>{{session_timeout}}</td>
- <td>{{expired}}</td>
- <td>{{closed}}</td>
- <td>{{ref_count}}</td>
- <td><a href='/close_session?session_id={{session_id}}'>Close Session</a></td>
- </tr>
-{{/sessions}}
+<div class="alert alert-info" role="alert">
+<h4>There are {{num_sessions}} sessions, of which {{num_active}} are active</h4> Sessions
+may be <strong>closed</strong> either when they are idle for some time (see Idle Timeout
+below), or if they are deliberately closed, otherwise they are
+called <strong>active</strong>.</div>
+
+<table id="sessions-tbl" class='table table-bordered table-hover table-condensed'>
+ <thead>
+ <tr>
+ <th><small>Session Type</small></th>
+ <th><small>Open Queries</small></th>
+ <th><small>Total Queries</small></th>
+ <th><small>User</small></th>
+ <th><small>Delegated User</small></th>
+ <th><small>Session ID</small></th>
+ <th><small>Network Address</small></th>
+ <th><small>Default Database</small></th>
+ <th><small>Start Time</small></th>
+ <th><small>Last Accessed</small></th>
+ <th><small>Idle Timeout (s)</small></th>
+ <th><small>Expired</small></th>
+ <th><small>Closed</small></th>
+ <th><small>Ref count</small></th>
+ <th><small>Action</small></th>
+ </tr>
+ </thead>
+ <tbody>
+ {{#sessions}}
+ <tr>
+ <td><small>{{type}}</small></td>
+ <td><small>{{inflight_queries}}</small></td>
+ <td><small>{{total_queries}}</small></td>
+ <td><small>{{user}}</small></td>
+ <td><small>{{delegated_user}}</small></td>
+ <td><small>{{session_id}}</small></td>
+ <td><small>{{network_address}}</small></td>
+ <td><small>{{default_database}}</small></td>
+ <td data-order="{{start_time_sort}}"><small>{{start_time}}</small></td>
+ <td data-order="{{last_accessed_sort}}"><small>{{last_accessed}}</small></td>
+ <td><small>{{session_timeout}}</small></td>
+ <td><small>{{expired}}</small></td>
+ <td><small>{{closed}}</small></td>
+ <td><small>{{ref_count}}</small></td>
+ <td><small><a href='/close_session?session_id={{session_id}}'>Close</a></small></td>
+ </tr>
+ {{/sessions}}
+ </tbody>
</table>
+<script>
+ $(document).ready(function() {
+ $('#sessions-tbl').DataTable({
+ "order": [[ 1, "desc" ]],
+ "pageLength": 100
+ });
+ });
+</script>
+
{{> www/common-footer.tmpl }}
[18/50] [abbrv] incubator-impala git commit: IMPALA-4365: Enabling
end-to-end tests on a remote cluster
Posted by ta...@apache.org.
IMPALA-4365: Enabling end-to-end tests on a remote cluster
This patch lays the groundwork for loading data and running end-to-end
tests on a remote CDH cluster. The requirements for the cluster to run
the tests are:
- Managed by Cloudera Manager (CM)
- GPL Extras need to be installed
- KMS and KeyTrustee installed and available as a service
- SERDEPROPERTIES in the Hive DB modified to accept wide tables
- Hive warehouse dir points to /test-warehouse
The actual data loading is done via a new script, remote_data_load.py,
which takes the CM host as an argument. It can be run from a client
machine that is not a node of the cluster, but it needs to have the
Impala repo checked out and Impala built. This insures that all of the
necessary data load scripts are available, as well as setting up the
environment properly (client binaries like beeline and the hbase shell
are available, python libraries like cm_api are installed, necessary
environment variables are defined, etc.)
It should be noted that running remote_data_load.py will overwrite
any local XML config files with the configurations downloaded from
the remote cluster.
Usage: remote_data_load.py [options] <cm_host address>
Options:
-h, --help show this help message and exit
--snapshot-file=SNAPSHOT_FILE
Path to the test-warehouse archive
--cm-user=CM_USER Cloudera Manager admin user
--cm-pass=CM_PASS Cloudera Manager admin user password
--gateway=GATEWAY Gateway host to upload the data from. If not
set, uses the CM host as gateway.
--ssh-user=SSH_USER System user on the remote machine with
passwordless SSH configured.
--no-load Do not try to load the snapshot
--exploration-strategy=EXPLORATION_STRATEGY
--test Run end-to-end tests against cluster
Testing:
This patch is being submitted with the understanding that there are
still clean up issues that need to be addressed in the remote data
load script, for which JIRA's have been filed.
However, since many of the existing build scripts also had to be
modified, it is more important to make sure that no regressions were
inadvertently introduced into the existing data load process. Loading
data to a local mini-cluster was checked repeatedly while this patch
was being developed, as well as running it against the Jenkins job
that provides the test-warehouse snapshot used by the many other
Impala CI builds that run daily.
Change-Id: I1f443a1728a1d28168090c6f54e82dec2cb073e9
Reviewed-on: http://gerrit.cloudera.org:8080/4769
Reviewed-by: Taras Bobrovytsky <tb...@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/ce4c5f67
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/ce4c5f67
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/ce4c5f67
Branch: refs/heads/hadoop-next
Commit: ce4c5f67433ebe050261710920972621d625c81c
Parents: ef689ed
Author: Martin Grund <mg...@cloudera.com>
Authored: Wed Aug 19 22:18:47 2015 -0700
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Tue Nov 8 10:16:55 2016 +0000
----------------------------------------------------------------------
bin/load-data.py | 12 +
bin/remote_data_load.py | 560 +++++++++++++++++++
testdata/bin/compute-table-stats.sh | 8 +-
testdata/bin/create-load-data.sh | 176 ++++--
testdata/bin/create-table-many-blocks.sh | 14 +-
testdata/bin/generate-schema-statements.py | 3 +-
testdata/bin/load-test-warehouse-snapshot.sh | 37 +-
testdata/bin/load_nested.py | 13 +-
testdata/bin/run-step.sh | 1 +
testdata/bin/setup-hdfs-env.sh | 32 +-
.../datasets/functional/schema_constraints.csv | 5 +
11 files changed, 797 insertions(+), 64 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/bin/load-data.py
----------------------------------------------------------------------
diff --git a/bin/load-data.py b/bin/load-data.py
index df41786..1359e01 100755
--- a/bin/load-data.py
+++ b/bin/load-data.py
@@ -22,6 +22,7 @@
# Most ddl commands are executed by Impala.
import collections
import getpass
+import logging
import os
import re
import sqlparse
@@ -30,12 +31,17 @@ import sys
import tempfile
import time
import traceback
+
from itertools import product
from optparse import OptionParser
from Queue import Queue
from tests.beeswax.impala_beeswax import *
from threading import Thread
+logging.basicConfig()
+LOG = logging.getLogger('load-data.py')
+LOG.setLevel(logging.DEBUG)
+
parser = OptionParser()
parser.add_option("-e", "--exploration_strategy", dest="exploration_strategy",
default="core",
@@ -191,6 +197,7 @@ def generate_schema_statements(workload):
generate_cmd += " --hive_warehouse_dir=%s" % options.hive_warehouse_dir
if options.hdfs_namenode is not None:
generate_cmd += " --hdfs_namenode=%s" % options.hdfs_namenode
+ generate_cmd += " --backend=%s" % options.impalad
print 'Executing Generate Schema Command: ' + generate_cmd
schema_cmd = os.path.join(TESTDATA_BIN_DIR, generate_cmd)
error_msg = 'Error generating schema statements for workload: ' + workload
@@ -265,6 +272,11 @@ def invalidate_impala_metadata():
impala_client.close_connection()
if __name__ == "__main__":
+ # Having the actual command line at the top of each data-load-* log can help
+ # when debugging dataload issues.
+ #
+ LOG.debug(' '.join(sys.argv))
+
all_workloads = available_workloads(WORKLOAD_DIR)
workloads = []
if options.workloads is None:
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/bin/remote_data_load.py
----------------------------------------------------------------------
diff --git a/bin/remote_data_load.py b/bin/remote_data_load.py
new file mode 100755
index 0000000..85a9f95
--- /dev/null
+++ b/bin/remote_data_load.py
@@ -0,0 +1,560 @@
+#!/usr/bin/env python
+# Copyright 2015 Cloudera Inc.
+#
+# Licensed 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.
+#
+#
+# This is a setup script that will downloaded a test warehouse snapshot and
+# deploy it on a remote, CM-managed cluster. Once the data is loaded, it is
+# possible to run a subset of the Impala core / exhaustive tests on the
+# remote cluster.
+#
+# * This script should be executed from a machine that has the Impala
+# development environment set up.
+#
+# * The cluster needs to be configured appropriately:
+# - The following services need to be installed:
+# HDFS, YARN, HIVE, IMPALA, MAPREDUCE, KUDU, HBASE, ZOOKEEPER
+# - GPL Extras parcel needs to be installed
+# - Metastore DB SERDE properties PARAM_VALUE needs to be altered to
+# allow for wide tables (See HIVE-1364.)
+# - The hive-warehouse path needs to be /test-warehouse
+#
+# Usage: remote_data_load.py [options] cm_host
+#
+# Options:
+# -h, --help show this help message and exit
+# --cm_user=CM_USER Cloudera Manager admin user
+# --cm_pass=CM_PASS Cloudera Manager admin user password
+# --no-load Do not try to load the snapshot
+# --test Run end-to-end tests against cluster.
+# --gateway=GATEWAY Gateway host to upload the data from. If not set, uses
+# the CM host as gateway.
+# --ssh_user=SSH_USER System user on the remote machine with passwordless SSH
+# configured.
+#
+import fnmatch
+import glob
+import logging
+import os
+import sh
+import shutil
+import sys
+import time
+
+from cm_api.api_client import ApiResource
+from functools import wraps
+from optparse import OptionParser
+from sh import ssh
+from tempfile import mkdtemp
+from urllib import quote as urlquote
+
+
+REQUIRED_SERVICES = ['HBASE',
+ 'HDFS',
+ 'HIVE',
+ 'IMPALA',
+ 'KUDU',
+ 'MAPREDUCE',
+ 'YARN',
+ 'ZOOKEEPER']
+
+# TODO: It's not currently possible to get the version from the cluster.
+# It would be nice to generate this dynamically.
+# (v14 happens to be the version that ships with CDH 5.9.x)
+CM_API_VERSION = 'v14'
+
+# Impala's data loading and test framework assumes this Hive Warehouse Directory.
+# Making this configurable would be an invasive change, and therefore, we prefer to
+# re-configure the Hive service via the CM API before loading data and running tests.
+HIVE_WAREHOUSE_DIR = "/test-warehouse"
+
+logger = logging.getLogger("remote_data_load")
+logger.setLevel(logging.DEBUG)
+
+# Goes to the file
+fh = logging.FileHandler("remote_data_load.log")
+fh.setLevel(logging.DEBUG)
+
+# Goes to stdout
+ch = logging.StreamHandler()
+ch.setLevel(logging.INFO)
+
+# create formatter and add it to the handlers
+formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
+fh.setFormatter(formatter)
+ch.setFormatter(formatter)
+
+# add the handlers to the logger
+logger.addHandler(fh)
+logger.addHandler(ch)
+
+
+def timing(func):
+ """
+ A decorator for timing how much time a function takes.
+
+ We can modify this later to do something more intelligent than just logging.
+ """
+ @wraps(func)
+ def wrap(*args, **kwargs):
+ t1 = time.time()
+ result = func(*args, **kwargs)
+ t2 = time.time()
+
+ output = 'TIME: {name}() took: {t:.4f} seconds'
+ logger.info(output.format(name=func.__name__, t=(t2-t1)))
+ return result
+ return wrap
+
+
+def tee(line):
+ """Output wrapper function used by sh to send the stdout or stderr to the
+ module's logger."""
+ logger.debug(line.strip())
+
+
+class RemoteDataLoad(object):
+ """This is an implementation of the process to load a test-warehouse snapshot on
+ a remote CM managed cluster. This script assumes that the warehouse snapshot was
+ already downloaded and was either passed in as a parameter, or can be found by
+ either inspecting the SNAPSHOT_DIR environment variable, or based on the WORKSPACE
+ environment variable on a Jenkins build slave.
+
+ The reason for the additional setup code is that in the local development
+ environment it is assumed that $USER is HDFS superuser, which is not the case for
+ remote deloyments.
+ """
+
+ def __init__(self, cm_host, options):
+ logger.info("Starting remote data load...")
+ self.options = options
+ self.cm_host = cm_host
+
+ # Gateway host can be used if the CM host is not configured as a Hadoop gateway
+ self.gateway = options.gateway if options.gateway else cm_host
+ self.impala_home = os.environ["IMPALA_HOME"]
+ self.api = ApiResource(self.cm_host, username=options.cm_user,
+ password=options.cm_pass)
+
+ # The API returns a list of clusters managed by the CM host. We're assuming
+ # that this CM host was set up for the purpose of Impala testing on one
+ # cluster, so the list should only have one value.
+ self.cluster = self.api.get_all_clusters()[0]
+ self.services = self.get_services()
+
+ self.config = self.get_service_client_configurations()
+ logger.info("Retrieved service configuration")
+ logger.info(str(self.config))
+ self.prepare()
+ logger.info("IMPALA_HOME: {0}".format(self.impala_home))
+
+ def get_hostname_for_ref(self, host_ref):
+ """Translate the HostRef instance into the hostname."""
+ return self.api.get_host(host_ref.hostId).hostname
+
+ @staticmethod
+ def get_or_default(config):
+ return config.value if config.value else config.default
+
+ def get_services(self):
+ """Confirm that all services are running, and return service dict."""
+ services = dict((s.type, s) for s in self.cluster.get_all_services())
+
+ if set(REQUIRED_SERVICES) != set(services.keys()):
+ missing_services = set(REQUIRED_SERVICES) - set(services.keys())
+ logger.error("Services not installed: {0}".format(list(missing_services)))
+ raise RuntimeError("Cluster not ready.")
+
+ if not all(services[s].serviceState == 'STARTED' for s in services):
+ stopped = [s for s in services if services[s].serviceState != "STARTED"]
+ logger.error("Not all services started: {0}".format(stopped))
+ raise RuntimeError("Cluster not ready.")
+
+ return services
+
+ @timing
+ def download_client_config(self, cluster, service):
+ """Download the client configuration zip for a particular cluster and service.
+
+ Since cm_api does not provide a way to download the archive we build the URL
+ manually and download the file. Once it downloaded the file the archive is
+ extracted and its content is copied to the Hadoop configuration directories
+ defined by Impala.
+ """
+ logger.info("Downloading client configuration for {0}".format(service.name))
+ url = "http://{0}:7180/api/{1}/clusters/{2}/services/{3}/clientConfig".format(
+ self.cm_host, CM_API_VERSION, urlquote(cluster.name), urlquote(service.name))
+ path = mkdtemp()
+ sh.curl(url, o=os.path.join(path, "clientConfig.zip"), _out=tee, _err=tee)
+ current = os.getcwd()
+ os.chdir(path)
+ sh.unzip("clientConfig.zip")
+ for root, _, file_names in os.walk("."):
+ for filename in fnmatch.filter(file_names, "*.xml"):
+ src = os.path.join(root, filename)
+ dst = os.path.join(self.impala_home, "fe", "src", "test", "resources")
+ logger.debug("Copying {0} to {1}".format(src, dst))
+ shutil.copy(src, dst)
+ os.chdir(current)
+
+ # TODO: this may be available in tests/comparison/cluster.py
+ def set_hive_warehouse_dir(self, cluster, service):
+ logger.info("Setting the Hive Warehouse Dir")
+ for service in self.api.get_all_clusters()[0].get_all_services():
+ logger.info(service)
+ if service.type == "HIVE":
+ hive_config = { "hive_warehouse_directory" : HIVE_WAREHOUSE_DIR }
+ service.update_config(hive_config)
+
+ # TODO: This functionality should be more generally available to other infrastructure
+ # code, rather than being quarantined in this script. See IMPALA-4367.
+ @timing
+ def get_service_client_configurations(self):
+ """Download the client configurations necessary to upload data to the remote
+ cluster. Unfortunately, the CM API does not allow downloading it so we have to
+ iterate over the services and download the config for all of them.
+
+ In addition, returns an options dictionary with settings required for data loading
+ like the HS2 server, Impala hosts, Name node etc.
+
+ Returns:
+ A client-configuration dictionary, e.g.:
+
+ {
+ 'hive_warehouse_directory': '/test-warehouse',
+ 'hs2': 'impala-test-cluster-1.gce.cloudera.com:10000',
+ 'impalad': ['impala-test-cluster-4.gce.cloudera.com:21000',
+ 'impala-test-cluster-2.gce.cloudera.com:21000',
+ 'impala-test-cluster-3.gce.cloudera.com:21000'],
+ 'metastore': 'impala-test-cluster-1.gce.cloudera.com:9083',
+ 'namenode': 'impala-test-cluster-1.gce.cloudera.com',
+ 'namenode_http': 'impala-test-cluster-1.gce.cloudera.com:20101',
+ 'kudu_master': 'impala-test-cluster-1.gce.cloudera.com'
+ }
+ """
+ # Iterate overs services and find the information we need
+ result = {}
+ for service_type, service in self.services.iteritems():
+ if service_type == "IMPALA":
+ roles = service.get_roles_by_type("IMPALAD")
+ impalads = []
+ for r in roles:
+ rc_config = r.get_config("full")
+ hostname = self.get_hostname_for_ref(r.hostRef)
+ hs2_port = self.get_or_default(rc_config["beeswax_port"])
+ impalads.append("{0}:{1}".format(hostname, hs2_port))
+ result["impalad"] = impalads
+ elif service_type == "HBASE":
+ self.download_client_config(self.cluster, service)
+ elif service_type == "HDFS":
+ self.download_client_config(self.cluster, service)
+ role = service.get_roles_by_type("NAMENODE")
+ config = role[0].get_config("full")
+ namenode = self.get_hostname_for_ref(role[0].hostRef)
+ result["namenode"] = namenode
+ result["namenode_http"] = "{0}:{1}".format(
+ namenode,
+ self.get_or_default(config["dfs_http_port"])
+ )
+ elif service_type == "HIVE":
+ self.set_hive_warehouse_dir(self.cluster, service)
+ self.download_client_config(self.cluster, service)
+ hs2 = service.get_roles_by_type("HIVESERVER2")[0]
+ rc_config = hs2.get_config("full")
+ result["hive_warehouse_directory"] = self.get_or_default(
+ service.get_config("full")[0]["hive_warehouse_directory"])
+ hostname = self.get_hostname_for_ref(hs2.hostRef)
+ result["hs2"] = "{0}:{1}".format(hostname, self.get_or_default(
+ rc_config["hs2_thrift_address_port"]))
+
+ # Get Metastore information
+ ms = service.get_roles_by_type("HIVEMETASTORE")[0]
+ rc_config = ms.get_config("full")
+ result["metastore"] = "{0}:{1}".format(
+ self.get_hostname_for_ref(ms.hostRef),
+ self.get_or_default(rc_config["hive_metastore_port"])
+ )
+ elif service_type == "KUDU":
+ # Service KUDU does not require a client configuration
+ result["kudu_master"] = self.cm_host
+
+ return result
+
+ # TODO: This functionality should be more generally available to other infrastructure
+ # code, rather than being quarantined in this script. See IMPALA-4367.
+ @staticmethod
+ def find_snapshot_file(snapshot_dir):
+ """Given snapshot_directory, walks the directory tree until it finds a file
+ matching the test-warehouse archive pattern."""
+ for root, _, file_names in os.walk(snapshot_dir):
+ for filename in fnmatch.filter(file_names, "test-warehouse-*-SNAPSHOT.tar.gz"):
+ logger.info("Found Snapshot file {0}".format(filename))
+ return os.path.join(root, filename)
+
+ @timing
+ def prepare(self):
+ """Populate the environment of the process with the necessary values.
+
+ In addition, it creates helper objects to run shell and SSH processes.
+ """
+ # Populate environment with required variables
+ os.environ["HS2_HOST_PORT"] = self.config["hs2"]
+ os.environ["HDFS_NN"] = self.config["namenode"]
+ os.environ["IMPALAD"] = self.config["impalad"][0]
+ os.environ["REMOTE_LOAD"] = "1"
+ os.environ["HADOOP_USER_NAME"] = "hdfs"
+ os.environ["TEST_WAREHOUSE_DIR"] = self.config["hive_warehouse_directory"]
+ os.environ["KUDU_MASTER"] = self.config["kudu_master"]
+
+ if self.options.snapshot_file is None:
+ if "SNAPSHOT_DIR" in os.environ:
+ snapshot_dir = os.environ["SNAPSHOT_DIR"]
+ else:
+ snapshot_dir = "{0}/testdata/test-warehouse-SNAPSHOT".format(
+ os.getenv("WORKSPACE"))
+ if not os.path.isdir(snapshot_dir):
+ err_msg = 'Snapshot directory "{0}" is not a valid directory'
+ logger.error(err_msg.format(snapshot_dir))
+ raise OSError("Could not find test-warehouse snapshot file.")
+
+ logger.info("Snapshot directory: {0}".format(snapshot_dir))
+ self.snapshot_file = self.find_snapshot_file(snapshot_dir)
+ else:
+ self.snapshot_file = self.options.snapshot_file
+
+ # Prepare shortcuts for connecting to remote services
+ self.gtw_ssh = ssh.bake("{0}@{1}".format(self.options.ssh_user, self.gateway),
+ "-oStrictHostKeyChecking=no",
+ "-oUserKnownHostsFile=/dev/null",
+ t=True, _out=tee, _err=tee)
+
+ self.beeline = sh.beeline.bake(silent=False, outputformat="csv2", n="impala",
+ u="jdbc:hive2://{0}/default".format(
+ self.config["hs2"]))
+
+ self.load_test_warehouse = sh.Command(
+ "{0}/testdata/bin/load-test-warehouse-snapshot.sh".format(
+ self.impala_home)).bake(
+ _out=tee, _err=tee)
+
+ self.create_load_data = sh.Command(
+ "{0}/testdata/bin/create-load-data.sh".format(self.impala_home))
+
+ self.main_impalad = self.config["impalad"][0]
+ self.impala_shell = sh.Command("impala-shell.sh").bake(i=self.main_impalad,
+ _out=tee, _err=tee)
+
+ self.python = sh.Command("impala-python").bake(u=True)
+ self.compute_stats = sh.Command(
+ "{0}/testdata/bin/compute-table-stats.sh".format(self.impala_home)).bake(
+ _out=tee, _err=tee)
+
+ @timing
+ def load(self):
+ """This method performs the actual data load. First it removes any known artifacts
+ from the remote location. Next it drops potentially existing database from the
+ Hive Metastore. Now, it invokes the load-test-warehouse-snapshot.sh and
+ create-load-data.sh scripts with the appropriate parameters. The most important
+ paramters are implicitly passed to the scripts as environment variables pointing
+ to the remote HDFS, Hive and Impala.
+ """
+ exploration_strategy = self.options.exploration_strategy
+
+ logger.info("Removing other databases")
+ dblist = self.beeline(e="show databases;", _err=tee).stdout
+ database_list = dblist.split()[1:] # The first element is the header string
+ for db in database_list:
+ if db.strip() != "default":
+ logger.debug("Dropping database %s", db)
+ self.impala_shell(q="drop database if exists {0} cascade;".format(db))
+
+ logger.info("Invalidating metadata in Impala")
+ self.impala_shell(q="invalidate metadata;")
+
+ logger.info("Removing previous remote {0}".format(
+ self.config["hive_warehouse_directory"]))
+ r = sh.hdfs.dfs("-rm", "-r", "-f", "{0}".format(
+ self.config["hive_warehouse_directory"]))
+
+ logger.info("Expunging HDFS trash")
+ r = sh.hdfs.dfs("-expunge")
+
+ logger.info("Uploading test warehouse snapshot")
+ self.load_test_warehouse(self.snapshot_file)
+
+ # TODO: We need to confirm that if we change any permissions, that we don't
+ # affect any running tests. See IMPALA-4375.
+ logger.info("Changing warehouse ownership")
+ r = sh.hdfs.dfs("-chown", "-R", "impala:hdfs", "{0}".format(
+ self.config["hive_warehouse_directory"]))
+ sh.hdfs.dfs("-chmod", "-R", "g+rwx", "{0}".format(
+ self.config["hive_warehouse_directory"]))
+ sh.hdfs.dfs("-chmod", "1777", "{0}".format(
+ self.config["hive_warehouse_directory"]))
+
+ logger.info("Calling create_load_data.sh")
+ # The $USER variable is used in the create-load-data.sh script for beeline
+ # impersonation.
+ new_env = os.environ.copy()
+ new_env["LOGNAME"] = "impala"
+ new_env["USER"] = "impala"
+ new_env["USERNAME"] = "impala"
+
+ # Regardless of whether we are in fact skipping the snapshot load or not,
+ # we nonetheless always pass -skip_snapshot_load to create-load-data.sh.
+ # This is because we have already loaded the snapshot earlier in this
+ # script, so we don't want create-load-data.sh to invoke
+ # load-test-warehouse-snapshot.sh again.
+ #
+ # It would actually be nice to be able to skip the snapshot load, but
+ # because of the existing messiness of create-load-data.sh, we can't.
+ # This invocation...
+ #
+ # $ create-load-data.sh -skip_snapshot_load -exploration_strategy core
+ #
+ # ...results in this error:
+ #
+ # Creating /test-warehouse HDFS directory \
+ # (logging to create-test-warehouse-dir.log)... FAILED
+ # 'hadoop fs -mkdir /test-warehouse' failed. Tail of log:
+ # Log for command 'hadoop fs -mkdir /test-warehouse'
+ # mkdir: `/test-warehouse': File exists
+ #
+ # Similarly, even though we might pass in "core" as the exploration strategy,
+ # because we aren't loading a metadata snapshot (i.e., -skip_metadata_load is
+ # false), an exhaustive dataload will always be done. This again is the result
+ # of logic in create-load-data.sh, which itself ignores the value passed in
+ # for -exploration_strategy.
+ #
+ # See IMPALA-4399: "create-load-data.sh has bitrotted to some extent, and needs
+ # to be cleaned up"
+ create_load_data_args = ["-skip_snapshot_load", "-cm_host", self.cm_host,
+ "-snapshot_file", self.snapshot_file,
+ "-exploration_strategy", exploration_strategy]
+
+ self.create_load_data(*create_load_data_args, _env=new_env, _out=tee, _err=tee)
+
+ sh.hdfs.dfs("-chown", "-R", "impala:hdfs", "{0}".format(
+ self.config["hive_warehouse_directory"]))
+
+ logger.info("Re-load HBase data")
+ # Manually load the HBase data last.
+ self.python("{0}/bin/load-data.py".format(self.impala_home),
+ "--hive_warehouse_dir={0}".format(
+ self.config["hive_warehouse_directory"]),
+ "--table_formats=hbase/none",
+ "--hive_hs2_hostport={0}".format(self.config["hs2"]),
+ "--hdfs_namenode={0}".format(self.config["namenode"]),
+ "--exploration_strategy={0}".format(exploration_strategy),
+ workloads="functional-query",
+ force=True,
+ impalad=self.main_impalad,
+ _env=new_env,
+ _out=tee,
+ _err=tee)
+
+ self.compute_stats()
+ logger.info("Load data finished")
+
+ # TODO: Should this be refactored out of this script? It has nothing to do with
+ # data loading per se. If tests rely on the environment on the client being set
+ # a certain way -- as in the prepare() method -- we may need to find another way
+ # to deal with that. See IMPALA-4376.
+ @timing
+ def test(self):
+ """Execute Impala's end-to-end tests against a remote cluster. All configuration
+ paramters are picked from the cluster configuration that was fetched via the
+ CM API."""
+
+ # TODO: Running tests via runtest.py is currently not working against a remote
+ # cluster (although running directly via py.test seems to work.) This method
+ # may be refactored out of this file under IMPALA-4376, so for the time being,
+ # raise a NotImplementedError.
+ raise NotImplementedError
+
+ # Overwrite the username to match the service user on the remote system and deal
+ # with the assumption that in the local development environment the current user
+ # is HDFS superuser as well.
+ new_env = os.environ.copy()
+ new_env["LOGNAME"] = "impala"
+ new_env["USER"] = "impala"
+ new_env["USERNAME"] = "impala"
+
+ strategy = self.options.exploration_strategy
+ logger.info("Running tests with exploration strategy {0}".format(strategy))
+ run_tests = sh.Command("{0}/tests/run-tests.py".format(self.impala_home))
+ run_tests("--skip_local_tests",
+ "--exploration_strategy={0}".format(strategy),
+ "--workload_exploration_strategy=functional-query:{0}".format(strategy),
+ "--namenode_http_address={0}".format(self.config["namenode_http"]),
+ "--hive_server2={0}".format(self.config["hs2"]),
+ "--metastore_server={0}".format(self.config["metastore"]),
+ "query_test",
+ maxfail=10,
+ impalad=",".join(self.config["impalad"]),
+ _env=new_env,
+ _out=tee,
+ _err=tee)
+
+
+def parse_args():
+ parser = OptionParser()
+ parser.add_option("--snapshot-file", default=None,
+ help="Path to the test-warehouse archive")
+ parser.add_option("--cm-user", default="admin", help="Cloudera Manager admin user")
+ parser.add_option("--cm-pass", default="admin",
+ help="Cloudera Manager admin user password")
+ parser.add_option("--gateway", default=None,
+ help=("Gateway host to upload the data from. If not set, uses the "
+ "CM host as gateway."))
+ parser.add_option("--ssh-user", default="jenkins",
+ help=("System user on the remote machine with passwordless "
+ "SSH configured."))
+ parser.add_option("--no-load", action="store_false", default=True, dest="load",
+ help="Do not try to load the snapshot")
+ parser.add_option("--exploration-strategy", default="core")
+ parser.add_option("--test", action="store_true", default=False,
+ help="Run end-to-end tests against cluster")
+ parser.set_usage("remote_data_load.py [options] cm_host")
+
+ options, args = parser.parse_args()
+
+ try:
+ return options, args[0] # args[0] is the cm_host
+ except IndexError:
+ logger.error("You must supply the cm_host.")
+ parser.print_usage()
+ raise
+
+def main(cm_host, options):
+ """
+ Load data to a remote cluster (and/or run tests) as specified.
+
+ Args:
+ cm_host: FQDN or IP of the CM host machine
+ options: an optparse 'options' instance containing RemoteDataLoad
+ values (though any object with the correct .attributes, e.g.
+ a collections.namedtuple instance, would also work)
+ """
+ rd = RemoteDataLoad(cm_host, options)
+
+ if options.load:
+ rd.load()
+ if options.test:
+ rd.test()
+
+
+if __name__ == "__main__":
+ options, cm_host = parse_args()
+ main(cm_host=cm_host, options=options)
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/compute-table-stats.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/compute-table-stats.sh b/testdata/bin/compute-table-stats.sh
index 6397d29..f06efab 100755
--- a/testdata/bin/compute-table-stats.sh
+++ b/testdata/bin/compute-table-stats.sh
@@ -23,7 +23,12 @@ set -euo pipefail
trap 'echo Error in $0 at line $LINENO: $(cd "'$PWD'" && awk "NR == $LINENO" $0)' ERR
. ${IMPALA_HOME}/bin/impala-config.sh > /dev/null 2>&1
-COMPUTE_STATS_SCRIPT="${IMPALA_HOME}/tests/util/compute_table_stats.py"
+
+# TODO: We need a better way of managing how these get set. See:
+# https://issues.cloudera.org/browse/IMPALA-4346
+IMPALAD=${IMPALAD:-localhost:21000}
+
+COMPUTE_STATS_SCRIPT="${IMPALA_HOME}/tests/util/compute_table_stats.py --impalad=${IMPALAD}"
# Run compute stats over as many of the tables used in the Planner tests as possible.
${COMPUTE_STATS_SCRIPT} --db_names=functional\
@@ -44,4 +49,3 @@ if "$KUDU_IS_SUPPORTED"; then
${COMPUTE_STATS_SCRIPT} --db_names=functional_kudu
${COMPUTE_STATS_SCRIPT} --db_names=tpch_kudu
fi
-
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/create-load-data.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/create-load-data.sh b/testdata/bin/create-load-data.sh
index 7631c1c..7a351fc 100755
--- a/testdata/bin/create-load-data.sh
+++ b/testdata/bin/create-load-data.sh
@@ -34,17 +34,38 @@ trap 'echo Error in $0 at line $LINENO: $(cd "'$PWD'" && awk "NR == $LINENO" $0)
. ${IMPALA_HOME}/bin/impala-config.sh > /dev/null 2>&1
. ${IMPALA_HOME}/testdata/bin/run-step.sh
+# Environment variables used to direct the data loading process to an external cluster.
+# TODO: We need a better way of managing how these get set. See:
+# https://issues.cloudera.org/browse/IMPALA-4346
+: ${HS2_HOST_PORT=localhost:11050}
+: ${HDFS_NN=localhost:20500}
+: ${IMPALAD=localhost:21000}
+: ${REMOTE_LOAD=}
+: ${CM_HOST=}
+
SKIP_METADATA_LOAD=0
SKIP_SNAPSHOT_LOAD=0
SNAPSHOT_FILE=""
LOAD_DATA_ARGS=""
-JDBC_URL="jdbc:hive2://localhost:11050/default;"
+EXPLORATION_STRATEGY="exhaustive"
+export JDBC_URL="jdbc:hive2://${HS2_HOST_PORT}/default;"
+
# For logging when using run-step.
LOG_DIR=${IMPALA_DATA_LOADING_LOGS_DIR}
+echo "Executing: create-load-data.sh $@"
+
while [ -n "$*" ]
do
case $1 in
+ -exploration_strategy)
+ EXPLORATION_STRATEGY=${2-}
+ if [[ -z "$EXPLORATION_STRATEGY" ]]; then
+ echo "Must provide an exploration strategy from e.g. core, exhaustive"
+ exit 1;
+ fi
+ shift;
+ ;;
-skip_metadata_load)
SKIP_METADATA_LOAD=1
;;
@@ -59,11 +80,16 @@ do
fi
shift;
;;
+ -cm_host)
+ CM_HOST=${2-}
+ shift;
+ ;;
-help|-h|*)
echo "create-load-data.sh : Creates data and loads from scratch"
echo "[-skip_metadata_load] : Skips loading of metadata"
echo "[-skip_snapshot_load] : Assumes that the snapshot is already loaded"
echo "[-snapshot_file] : Loads the test warehouse snapshot into hdfs"
+ echo "[-cm_host] : Address of the Cloudera Manager host if loading to a remote cluster"
exit 1;
;;
esac
@@ -71,8 +97,10 @@ do
done
if [[ $SKIP_METADATA_LOAD -eq 0 && "$SNAPSHOT_FILE" = "" ]]; then
- run-step "Loading Hive Builtins" load-hive-builtins.log \
+ if [[ -z "$REMOTE_LOAD" ]]; then
+ run-step "Loading Hive Builtins" load-hive-builtins.log \
${IMPALA_HOME}/testdata/bin/load-hive-builtins.sh
+ fi
run-step "Generating HBase data" create-hbase.log \
${IMPALA_HOME}/testdata/bin/create-hbase.sh
run-step "Creating /test-warehouse HDFS directory" create-test-warehouse-dir.log \
@@ -98,6 +126,14 @@ else
echo Skipping loading data to hdfs.
fi
+echo "Derived params for create-load-data.sh:"
+echo "EXPLORATION_STRATEGY=${EXPLORATION_STRATEGY:-}"
+echo "SKIP_METADATA_LOAD=${SKIP_METADATA_LOAD:-}"
+echo "SKIP_SNAPSHOT_LOAD=${SKIP_SNAPSHOT_LOAD:-}"
+echo "SNAPSHOT_FILE=${SNAPSHOT_FILE:-}"
+echo "CM_HOST=${CM_HOST:-}"
+echo "REMOTE_LOAD=${REMOTE_LOAD:-}"
+
function load-custom-schemas {
SCHEMA_SRC_DIR=${IMPALA_HOME}/testdata/data/schemas
SCHEMA_DEST_DIR=/test-warehouse/schemas
@@ -131,7 +167,7 @@ function load-data {
MSG="Loading workload '$WORKLOAD'"
ARGS=("--workloads $WORKLOAD")
- MSG+=" Using exploration strategy '$EXPLORATION_STRATEGY'"
+ MSG+=" using exploration strategy '$EXPLORATION_STRATEGY'"
ARGS+=("-e $EXPLORATION_STRATEGY")
if [ $TABLE_FORMATS ]; then
MSG+=" in table formats '$TABLE_FORMATS'"
@@ -144,15 +180,35 @@ function load-data {
if [ "${WORKLOAD}" = "functional-query" ]; then
WORKLOAD="functional"
fi
+
+ # TODO: Why is there a REMOTE_LOAD condition?
+ # See https://issues.cloudera.org/browse/IMPALA-4347
+ #
# Force load the dataset if we detect a schema change.
- if ! ${IMPALA_HOME}/testdata/bin/check-schema-diff.sh $WORKLOAD; then
- ARGS+=("--force")
- echo "Force loading $WORKLOAD because a schema change was detected"
- elif [ "${FORCE_LOAD}" = "force" ]; then
- ARGS+=("--force")
- echo "Force loading."
+ if [[ -z "$REMOTE_LOAD" ]]; then
+ if ! ${IMPALA_HOME}/testdata/bin/check-schema-diff.sh $WORKLOAD; then
+ ARGS+=("--force")
+ echo "Force loading $WORKLOAD because a schema change was detected"
+ elif [ "${FORCE_LOAD}" = "force" ]; then
+ ARGS+=("--force")
+ echo "Force loading."
+ fi
fi
- LOG_FILE=${IMPALA_DATA_LOADING_LOGS_DIR}/data-load-${WORKLOAD}-${EXPLORATION_STRATEGY}.log
+
+ ARGS+=("--impalad ${IMPALAD}")
+ ARGS+=("--hive_hs2_hostport ${HS2_HOST_PORT}")
+ ARGS+=("--hdfs_namenode ${HDFS_NN}")
+
+ if [[ -n ${TABLE_FORMATS} ]]; then
+ # TBL_FMT_STR replaces slashes with underscores,
+ # e.g., kudu/none/none -> kudu_none_none
+ TBL_FMT_STR=${TABLE_FORMATS//[\/]/_}
+ LOG_BASENAME=data-load-${WORKLOAD}-${EXPLORATION_STRATEGY}-${TBL_FMT_STR}.log
+ else
+ LOG_BASENAME=data-load-${WORKLOAD}-${EXPLORATION_STRATEGY}.log
+ fi
+
+ LOG_FILE=${IMPALA_DATA_LOADING_LOGS_DIR}/${LOG_BASENAME}
echo "$MSG. Logging to ${LOG_FILE}"
# Use unbuffered logging by executing with -u
if ! impala-python -u ${IMPALA_HOME}/bin/load-data.py ${ARGS[@]} &> ${LOG_FILE}; then
@@ -165,10 +221,13 @@ function load-data {
function cache-test-tables {
echo CACHING tpch.nation AND functional.alltypestiny
# uncaching the tables first makes this operation idempotent.
- ${IMPALA_HOME}/bin/impala-shell.sh -q "alter table functional.alltypestiny set uncached"
- ${IMPALA_HOME}/bin/impala-shell.sh -q "alter table tpch.nation set uncached"
- ${IMPALA_HOME}/bin/impala-shell.sh -q "alter table tpch.nation set cached in 'testPool'"
- ${IMPALA_HOME}/bin/impala-shell.sh -q\
+ ${IMPALA_HOME}/bin/impala-shell.sh -i ${IMPALAD}\
+ -q "alter table functional.alltypestiny set uncached"
+ ${IMPALA_HOME}/bin/impala-shell.sh -i ${IMPALAD}\
+ -q "alter table tpch.nation set uncached"
+ ${IMPALA_HOME}/bin/impala-shell.sh -i ${IMPALAD}\
+ -q "alter table tpch.nation set cached in 'testPool'"
+ ${IMPALA_HOME}/bin/impala-shell.sh -i ${IMPALAD} -q\
"alter table functional.alltypestiny set cached in 'testPool'"
}
@@ -179,6 +238,9 @@ function load-aux-workloads {
if [ -d ${IMPALA_AUX_WORKLOAD_DIR} ] && [ -d ${IMPALA_AUX_DATASET_DIR} ]; then
echo Loading auxiliary workloads. Logging to $LOG_FILE.
if ! impala-python -u ${IMPALA_HOME}/bin/load-data.py --workloads all\
+ --impalad=${IMPALAD}\
+ --hive_hs2_hostport=${HS2_HOST_PORT}\
+ --hdfs_namenode=${HDFS_NN}\
--workload_dir=${IMPALA_AUX_WORKLOAD_DIR}\
--dataset_dir=${IMPALA_AUX_DATASET_DIR}\
--exploration_strategy=core ${LOAD_DATA_ARGS} >> $LOG_FILE 2>&1; then
@@ -192,6 +254,7 @@ function load-aux-workloads {
}
function copy-auth-policy {
+ echo COPYING AUTHORIZATION POLICY FILE
hadoop fs -rm -f ${FILESYSTEM_PREFIX}/test-warehouse/authz-policy.ini
hadoop fs -put ${IMPALA_HOME}/fe/src/test/resources/authz-policy.ini \
${FILESYSTEM_PREFIX}/test-warehouse/
@@ -207,18 +270,37 @@ function copy-and-load-dependent-tables {
hadoop fs -rm -r -f /tmp/alltypes_seq
hadoop fs -mkdir -p /tmp/alltypes_seq/year=2009
hadoop fs -mkdir -p /tmp/alltypes_rc/year=2009
- hadoop fs -cp /test-warehouse/alltypes_seq/year=2009/month=2/ /tmp/alltypes_seq/year=2009
- hadoop fs -cp /test-warehouse/alltypes_rc/year=2009/month=3/ /tmp/alltypes_rc/year=2009
+ hadoop fs -cp /test-warehouse/alltypes_seq/year=2009/month=2/ /tmp/alltypes_seq/year=2009
+ hadoop fs -cp /test-warehouse/alltypes_rc/year=2009/month=3/ /tmp/alltypes_rc/year=2009
# Create a hidden file in AllTypesSmall
hadoop fs -rm -f /test-warehouse/alltypessmall/year=2009/month=1/_hidden
hadoop fs -rm -f /test-warehouse/alltypessmall/year=2009/month=1/.hidden
- hadoop fs -cp /test-warehouse/zipcode_incomes/DEC_00_SF3_P077_with_ann_noheader.csv \
+ hadoop fs -cp /test-warehouse/zipcode_incomes/DEC_00_SF3_P077_with_ann_noheader.csv \
/test-warehouse/alltypessmall/year=2009/month=1/_hidden
- hadoop fs -cp /test-warehouse/zipcode_incomes/DEC_00_SF3_P077_with_ann_noheader.csv \
+ hadoop fs -cp /test-warehouse/zipcode_incomes/DEC_00_SF3_P077_with_ann_noheader.csv \
/test-warehouse/alltypessmall/year=2009/month=1/.hidden
- # For tables that rely on loading data from local fs test-warehouse
+ # In case the data is updated by a non-super user, make sure the user can write
+ # by chmoding 777 /tmp/alltypes_rc and /tmp/alltypes_seq. This is needed in order
+ # to prevent this error during data load to a remote cluster:
+ #
+ # ERROR : Failed with exception Unable to move source hdfs://cluster-1.foo.cloudera.com:
+ # 8020/tmp/alltypes_seq/year=2009/month=2/000023_0 to destination hdfs://cluster-1.foo.
+ # cloudera.com:8020/test-warehouse/alltypesmixedformat/year=2009/month=2/000023_0
+ # [...]
+ # Caused by: org.apache.hadoop.security.AccessControlException:
+ # Permission denied: user=impala, access=WRITE
+ # inode="/tmp/alltypes_seq/year=2009/month=2":hdfs:supergroup:drwxr-xr-x
+ #
+ # The error occurs while loading dependent tables.
+ #
+ # See: logs/data_loading/copy-and-load-dependent-tables.log)
+ # See also: https://issues.cloudera.org/browse/IMPALA-4345
+ hadoop fs -chmod -R 777 /tmp/alltypes_rc
+ hadoop fs -chmod -R 777 /tmp/alltypes_seq
+
+ # For tables that rely on loading data from local fs test-wareload-house
# TODO: Find a good way to integrate this with the normal data loading scripts
beeline -n $USER -u "${JDBC_URL}" -f\
${IMPALA_HOME}/testdata/bin/load-dependent-tables.sql
@@ -249,6 +331,7 @@ EOF
function load-custom-data {
# Load the index files for corrupted lzo data.
+ hadoop fs -mkdir -p /test-warehouse/bad_text_lzo_text_lzo
hadoop fs -rm -f /test-warehouse/bad_text_lzo_text_lzo/bad_text.lzo.index
hadoop fs -put ${IMPALA_HOME}/testdata/bad_text_lzo/bad_text.lzo.index \
/test-warehouse/bad_text_lzo_text_lzo/
@@ -258,8 +341,12 @@ function load-custom-data {
# Cleanup the old bad_text_lzo files, if they exist.
hadoop fs -rm -r -f /test-warehouse/bad_text_lzo/
- # Index all lzo files in HDFS under /test-warehouse
- ${IMPALA_HOME}/testdata/bin/lzo_indexer.sh /test-warehouse
+ # TODO: Why is there a REMOTE_LOAD condition?
+ # See https://issues.cloudera.org/browse/IMPALA-4347
+ if [[ -z $REMOTE_LOAD ]]; then
+ # Index all lzo files in HDFS under /test-warehouse
+ ${IMPALA_HOME}/testdata/bin/lzo_indexer.sh /test-warehouse
+ fi
hadoop fs -mv /bad_text_lzo_text_lzo/ /test-warehouse/
@@ -292,7 +379,7 @@ function load-custom-data {
done
# Remove all index files in this partition.
- hadoop fs -rm /test-warehouse/alltypes_text_lzo/year=2009/month=1/*.lzo.index
+ hadoop fs -rm -f /test-warehouse/alltypes_text_lzo/year=2009/month=1/*.lzo.index
# Add a sequence file that only contains a header (see IMPALA-362)
hadoop fs -put -f ${IMPALA_HOME}/testdata/tinytable_seq_snap/tinytable_seq_snap_header_only \
@@ -303,8 +390,16 @@ function load-custom-data {
hadoop fs -put -f ${IMPALA_HOME}/testdata/compressed_formats/compressed_payload.snap \
/test-warehouse/compressed_payload.snap
+ # Create Avro tables
beeline -n $USER -u "${JDBC_URL}" -f\
${IMPALA_HOME}/testdata/avro_schema_resolution/create_table.sql
+
+ # Delete potentially existing avro data
+ hadoop fs -rm -f /test-warehouse/avro_schema_resolution_test/*.avro
+
+ # Upload Avro data to the 'schema_resolution_test' table
+ hadoop fs -put ${IMPALA_HOME}/testdata/avro_schema_resolution/records*.avro \
+ /test-warehouse/avro_schema_resolution_test
}
function build-and-copy-hive-udfs {
@@ -319,12 +414,16 @@ function build-and-copy-hive-udfs {
# Additional data loading actions that must be executed after the main data is loaded.
function custom-post-load-steps {
- # Configure alltypes_seq as a read-only table. This is required for fe tests.
- # Set both read and execute permissions because accessing the contents of a directory on
- # the local filesystem requires the x permission (while on HDFS it requires the r
- # permission).
- hadoop fs -chmod -R 555 ${FILESYSTEM_PREFIX}/test-warehouse/alltypes_seq/year=2009/month=1
- hadoop fs -chmod -R 555 ${FILESYSTEM_PREFIX}/test-warehouse/alltypes_seq/year=2009/month=3
+ # TODO: Why is there a REMOTE_LOAD condition?
+ # See https://issues.cloudera.org/browse/IMPALA-4347
+ if [[ -z "$REMOTE_LOAD" ]]; then
+ # Configure alltypes_seq as a read-only table. This is required for fe tests.
+ # Set both read and execute permissions because accessing the contents of a directory on
+ # the local filesystem requires the x permission (while on HDFS it requires the r
+ # permission).
+ hadoop fs -chmod -R 555 ${FILESYSTEM_PREFIX}/test-warehouse/alltypes_seq/year=2009/month=1
+ hadoop fs -chmod -R 555 ${FILESYSTEM_PREFIX}/test-warehouse/alltypes_seq/year=2009/month=3
+ fi
#IMPALA-1881: data file produced by hive with multiple blocks.
hadoop fs -mkdir -p ${FILESYSTEM_PREFIX}/test-warehouse/lineitem_multiblock_parquet
@@ -349,7 +448,7 @@ function copy-and-load-ext-data-source {
# Copy the test data source library into HDFS
${IMPALA_HOME}/testdata/bin/copy-data-sources.sh
# Create data sources table.
- ${IMPALA_HOME}/bin/impala-shell.sh -f\
+ ${IMPALA_HOME}/bin/impala-shell.sh -i ${IMPALAD} -f\
${IMPALA_HOME}/testdata/bin/create-data-source-table.sql
}
@@ -365,9 +464,12 @@ if [[ "${TARGET_FILESYSTEM}" == "local" ]]; then
else
START_CLUSTER_ARGS="-s 3 ${START_CLUSTER_ARGS}"
fi
-run-step "Starting Impala cluster" start-impala-cluster.log \
- ${IMPALA_HOME}/bin/start-impala-cluster.py \
- --log_dir=${IMPALA_DATA_LOADING_LOGS_DIR} ${START_CLUSTER_ARGS}
+if [[ -z "$REMOTE_LOAD" ]]; then
+ run-step "Starting Impala cluster" start-impala-cluster.log \
+ ${IMPALA_HOME}/bin/start-impala-cluster.py --log_dir=${IMPALA_DATA_LOADING_LOGS_DIR} \
+ ${START_CLUSTER_ARGS}
+fi
+
# The hdfs environment script sets up kms (encryption) and cache pools (hdfs caching).
# On a non-hdfs filesystem, we don't test encryption or hdfs caching, so this setup is not
# needed.
@@ -383,8 +485,11 @@ if [ $SKIP_METADATA_LOAD -eq 0 ]; then
run-step "Loading TPC-H data" load-tpch.log load-data "tpch" "core"
# Load tpch nested data.
# TODO: Hacky and introduces more complexity into the system, but it is expedient.
+ if [[ -n "$CM_HOST" ]]; then
+ LOAD_NESTED_ARGS="--cm-host $CM_HOST"
+ fi
run-step "Loading nested data" load-nested.log \
- ${IMPALA_HOME}/testdata/bin/load_nested.py
+ ${IMPALA_HOME}/testdata/bin/load_nested.py ${LOAD_NESTED_ARGS:-}
run-step "Loading TPC-DS data" load-tpcds.log load-data "tpcds" "core"
run-step "Loading auxiliary workloads" load-aux-workloads.log load-aux-workloads
run-step "Loading dependent tables" copy-and-load-dependent-tables.log \
@@ -419,7 +524,10 @@ if [ "${TARGET_FILESYSTEM}" = "hdfs" ]; then
run-step "Loading external data sources" load-ext-data-source.log \
copy-and-load-ext-data-source
- run-step "Splitting HBase" create-hbase.log ${IMPALA_HOME}/testdata/bin/split-hbase.sh
+ # HBase splitting is only relevant for FE tests
+ if [[ -z "$REMOTE_LOAD" ]]; then
+ run-step "Splitting HBase" create-hbase.log ${IMPALA_HOME}/testdata/bin/split-hbase.sh
+ fi
run-step "Creating internal HBase table" create-internal-hbase-table.log \
create-internal-hbase-table
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/create-table-many-blocks.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/create-table-many-blocks.sh b/testdata/bin/create-table-many-blocks.sh
index 5b0199a..abdf94f 100755
--- a/testdata/bin/create-table-many-blocks.sh
+++ b/testdata/bin/create-table-many-blocks.sh
@@ -29,6 +29,12 @@ trap 'echo Error in $0 at line $LINENO: $(cd "'$PWD'" && awk "NR == $LINENO" $0)
. ${IMPALA_HOME}/bin/impala-config.sh > /dev/null 2>&1
+# Environment variables needed for remote cluster
+: ${HS2_HOST_PORT:=localhost:11050}
+JDBC_URL="jdbc:hive2://${HS2_HOST_PORT}/default;"
+
+HIVE_CMD="beeline -n $USER -u $JDBC_URL"
+
LOCAL_OUTPUT_DIR=$(mktemp -dt "impala_test_tmp.XXXXXX")
echo $LOCAL_OUTPUT_DIR
@@ -66,9 +72,9 @@ HDFS_PATH=/test-warehouse/many_blocks_num_blocks_per_partition_${BLOCKS_PER_PART
DB_NAME=scale_db
TBL_NAME=num_partitions_${NUM_PARTITIONS}_blocks_per_partition_${BLOCKS_PER_PARTITION}
-hive -e "create database if not exists scale_db"
-hive -e "drop table if exists ${DB_NAME}.${TBL_NAME}"
-hive -e "create external table ${DB_NAME}.${TBL_NAME} (i int) partitioned by (j int)"
+$HIVE_CMD -e "create database if not exists scale_db"
+$HIVE_CMD -e "drop table if exists ${DB_NAME}.${TBL_NAME}"
+$HIVE_CMD -e "create external table ${DB_NAME}.${TBL_NAME} (i int) partitioned by (j int)"
# Generate many (small) files. Each file will be assigned a unique block.
echo "Generating ${BLOCKS_PER_PARTITION} files"
@@ -98,6 +104,6 @@ done
echo ";" >> ${LOCAL_OUTPUT_DIR}/hive_create_partitions.q
echo "Executing DDL via Hive"
-hive -f ${LOCAL_OUTPUT_DIR}/hive_create_partitions.q
+$HIVE_CMD -f ${LOCAL_OUTPUT_DIR}/hive_create_partitions.q
echo "Done! Final result in table: ${DB_NAME}.${TBL_NAME}"
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/generate-schema-statements.py
----------------------------------------------------------------------
diff --git a/testdata/bin/generate-schema-statements.py b/testdata/bin/generate-schema-statements.py
index 4c8ef02..1fe6a01 100755
--- a/testdata/bin/generate-schema-statements.py
+++ b/testdata/bin/generate-schema-statements.py
@@ -408,10 +408,11 @@ def build_load_statement(load_template, db_name, db_suffix, table_name):
db_name=db_name,
db_suffix=db_suffix)
else:
+ base_load_dir = os.getenv("REMOTE_LOAD", os.getenv("IMPALA_HOME"))
load_template = load_template.format(table_name=table_name,
db_name=db_name,
db_suffix=db_suffix,
- impala_home = os.environ['IMPALA_HOME'])
+ impala_home = base_load_dir)
return load_template
def build_hbase_create_stmt(db_name, table_name, column_families):
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/load-test-warehouse-snapshot.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/load-test-warehouse-snapshot.sh b/testdata/bin/load-test-warehouse-snapshot.sh
index 2b6e90d..604c8f1 100755
--- a/testdata/bin/load-test-warehouse-snapshot.sh
+++ b/testdata/bin/load-test-warehouse-snapshot.sh
@@ -28,13 +28,14 @@ set -euo pipefail
trap 'echo Error in $0 at line $LINENO: $(cd "'$PWD'" && awk "NR == $LINENO" $0)' ERR
. ${IMPALA_HOME}/bin/impala-config.sh > /dev/null 2>&1
+: ${REMOTE_LOAD:=}
if [[ $# -ne 1 ]]; then
echo "Usage: load-test-warehouse-snapshot.sh [test-warehouse-SNAPSHOT.tar.gz]"
exit 1
fi
-TEST_WAREHOUSE_DIR="/test-warehouse"
+: ${TEST_WAREHOUSE_DIR=/test-warehouse}
SNAPSHOT_FILE=$1
if [ ! -f ${SNAPSHOT_FILE} ]; then
@@ -42,9 +43,13 @@ if [ ! -f ${SNAPSHOT_FILE} ]; then
exit 1
fi
-echo "Your existing ${TARGET_FILESYSTEM} warehouse directory " \
- "(${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}) will be removed."
-read -p "Continue (y/n)? "
+if [[ -z "$REMOTE_LOAD" ]]; then
+ echo "Your existing ${TARGET_FILESYSTEM} warehouse directory " \
+ "(${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR} will be removed."
+ read -p "Continue (y/n)? "
+else
+ REPLY=y
+fi
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
# Create a new warehouse directory. If one already exist, remove it first.
if [ "${TARGET_FILESYSTEM}" = "s3" ]; then
@@ -56,7 +61,7 @@ if [[ "$REPLY" =~ ^[Yy]$ ]]; then
else
# Either isilon or hdfs, no change in procedure.
if hadoop fs -test -d ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}; then
- echo "Removing existing test-warehouse directory"
+ echo "Removing existing ${TEST_WAREHOUSE_DIR} directory"
# For filesystems that don't allow 'rm' without 'x', chmod to 777 for the
# subsequent 'rm -r'.
if [ "${TARGET_FILESYSTEM}" = "isilon" ] || \
@@ -65,8 +70,13 @@ if [[ "$REPLY" =~ ^[Yy]$ ]]; then
fi
hadoop fs -rm -r -skipTrash ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
fi
- echo "Creating test-warehouse directory"
- hadoop fs -mkdir ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
+ echo "Creating ${TEST_WAREHOUSE_DIR} directory"
+ hadoop fs -mkdir -p ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
+
+ # TODO: commented out because of regressions in local end-to-end testing
+ # See: https://issues.cloudera.org/browse/IMPALA-4345
+ #
+ # hdfs dfs -chmod 1777 ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
fi
else
echo -e "\nAborting."
@@ -81,14 +91,18 @@ mkdir ${SNAPSHOT_STAGING_DIR}
echo "Extracting tarball"
tar -C ${SNAPSHOT_STAGING_DIR} -xzf ${SNAPSHOT_FILE}
-if [ ! -f ${SNAPSHOT_STAGING_DIR}/test-warehouse/githash.txt ]; then
+if [ ! -f ${SNAPSHOT_STAGING_DIR}${TEST_WAREHOUSE_DIR}/githash.txt ]; then
echo "The test-warehouse snapshot does not contain a githash.txt file, aborting load"
exit 1
fi
-echo "Loading hive builtins"
-${IMPALA_HOME}/testdata/bin/load-hive-builtins.sh
+# Hive builtins are already present on a pre-setup CM managed cluster.
+if [[ -z "$REMOTE_LOAD" ]]; then
+ echo "Loading hive builtins"
+ ${IMPALA_HOME}/testdata/bin/load-hive-builtins.sh
+fi
+
echo "Copying data to ${TARGET_FILESYSTEM}"
if [ "${TARGET_FILESYSTEM}" = "s3" ]; then
# hive does not yet work well with s3, so we won't need hive builtins.
@@ -99,8 +113,7 @@ if [ "${TARGET_FILESYSTEM}" = "s3" ]; then
exit 1
fi
else
- hadoop fs -put ${SNAPSHOT_STAGING_DIR}${TEST_WAREHOUSE_DIR}/* \
- ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
+ hadoop fs -put ${SNAPSHOT_STAGING_DIR}${TEST_WAREHOUSE_DIR}/* ${FILESYSTEM_PREFIX}${TEST_WAREHOUSE_DIR}
fi
${IMPALA_HOME}/bin/create_testdata.sh
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/load_nested.py
----------------------------------------------------------------------
diff --git a/testdata/bin/load_nested.py b/testdata/bin/load_nested.py
index f68f8c4..b44bd04 100755
--- a/testdata/bin/load_nested.py
+++ b/testdata/bin/load_nested.py
@@ -20,10 +20,13 @@
'''This script creates a nested version of TPC-H. Non-nested TPC-H must already be
loaded.
'''
-
import logging
import os
+from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
+import tests.comparison.cli_options as cli_options
+
+
LOG = logging.getLogger(os.path.splitext(os.path.basename(__file__))[0])
# These vars are set after arg parsing.
@@ -281,23 +284,25 @@ def load():
DROP TABLE tmp_supplier_string;""".split(";"):
if not stmt.strip():
continue
+ LOG.info("Executing: {0}".format(stmt))
hive.execute(stmt)
with cluster.impala.cursor(db_name=target_db) as impala:
impala.invalidate_metadata()
impala.compute_stats()
+ LOG.info("Done loading nested TPCH data")
if __name__ == "__main__":
- from argparse import ArgumentDefaultsHelpFormatter, ArgumentParser
- import tests.comparison.cli_options as cli_options
parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter)
cli_options.add_logging_options(parser)
- cli_options.add_cluster_options(parser)
+ cli_options.add_cluster_options(parser) # --cm-host and similar args added here
+
parser.add_argument("-s", "--source-db", default="tpch_parquet")
parser.add_argument("-t", "--target-db", default="tpch_nested_parquet")
parser.add_argument("-c", "-p", "--chunks", type=int, default=1)
+
args = parser.parse_args()
cli_options.configure_logging(args.log_level, debug_log_file=args.debug_log_file)
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/run-step.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/run-step.sh b/testdata/bin/run-step.sh
index faef360..e3e516e 100755
--- a/testdata/bin/run-step.sh
+++ b/testdata/bin/run-step.sh
@@ -24,6 +24,7 @@
# outputs if there is an error.
# Usage: run-step <step description> <log file name> <cmd> <arg1> <arg2> ...
# LOG_DIR must be set to a writable directory for logs.
+
function run-step {
local MSG=$1
shift
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/bin/setup-hdfs-env.sh
----------------------------------------------------------------------
diff --git a/testdata/bin/setup-hdfs-env.sh b/testdata/bin/setup-hdfs-env.sh
index 921ec67..259cac1 100755
--- a/testdata/bin/setup-hdfs-env.sh
+++ b/testdata/bin/setup-hdfs-env.sh
@@ -16,10 +16,12 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-
+#
set -euo pipefail
trap 'echo Error in $0 at line $LINENO: $(cd "'$PWD'" && awk "NR == $LINENO" $0)' ERR
+: ${REMOTE_LOAD:=}
+
# Create a cache pool and encryption keys for tests
PREVIOUS_PRINCIPAL=""
@@ -27,13 +29,23 @@ CACHEADMIN_ARGS=""
# If we're kerberized, we need to become hdfs for this:
if ${CLUSTER_DIR}/admin is_kerberized; then
- PREVIOUS_PRINCIPAL=`klist | grep ^Default | awk '{print $3}'`
- PREVIOUS_USER=`echo ${PREVIOUS_PRINCIPAL} | awk -F/ '{print $1}'`
- CACHEADMIN_ARGS="-group supergroup -owner ${PREVIOUS_USER}"
- kinit -k -t ${KRB5_KTNAME} ${MINIKDC_PRINC_HDFS}
+ if [[ -n "${REMOTE_LOAD:-}" ]]; then
+ echo "REMOTE_LOAD: $REMOTE_LOAD"
+ echo "Remote cluster testing is not supported with Kerberos"
+ exit 1
+ else
+ PREVIOUS_PRINCIPAL=`klist | grep ^Default | awk '{print $3}'`
+ PREVIOUS_USER=`echo ${PREVIOUS_PRINCIPAL} | awk -F/ '{print $1}'`
+ CACHEADMIN_ARGS="-group supergroup -owner ${PREVIOUS_USER}"
+ kinit -k -t ${KRB5_KTNAME} ${MINIKDC_PRINC_HDFS}
+ fi
fi
-if [[ $TARGET_FILESYSTEM == hdfs ]]; then # Otherwise assume KMS isn't setup.
+# TODO: Investigate how to setup encryption keys for running HDFS encryption tests
+# against a remote cluster, rather than the local mini-cluster (i.e., when REMOTE_LOAD
+# is true. See: https://issues.cloudera.org/browse/IMPALA-4344)
+
+if [[ $TARGET_FILESYSTEM == hdfs && -z "$REMOTE_LOAD" ]]; then # Otherwise assume KMS isn't setup.
# Create encryption keys for HDFS encryption tests. Keys are stored by the KMS.
EXISTING_KEYS=$(hadoop key list)
for KEY in testkey{1,2}; do
@@ -44,7 +56,13 @@ if [[ $TARGET_FILESYSTEM == hdfs ]]; then # Otherwise assume KMS isn't setup.
done
fi
-# Create test cache pool
+if [[ -n "${REMOTE_LOAD:-}" ]]; then
+ # Create test cache pool if HADOOP_USER_NAME has a non-zero length
+ if [[ -n "${HADOOP_USER_NAME:-}" ]]; then
+ CACHEADMIN_ARGS="${CACHEADMIN_ARGS} -owner ${USER}"
+ fi
+fi
+
if hdfs cacheadmin -listPools testPool | grep testPool &>/dev/null; then
hdfs cacheadmin -removePool testPool
fi
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/ce4c5f67/testdata/datasets/functional/schema_constraints.csv
----------------------------------------------------------------------
diff --git a/testdata/datasets/functional/schema_constraints.csv b/testdata/datasets/functional/schema_constraints.csv
index d6d1111..790dba4 100644
--- a/testdata/datasets/functional/schema_constraints.csv
+++ b/testdata/datasets/functional/schema_constraints.csv
@@ -118,6 +118,11 @@ table_name:overflow, constraint:restrict_to, table_format:text/none/none
# seem to like this.
table_name:widerow, constraint:exclude, table_format:hbase/none/none
+# Wide tables fail due to the SERDEPROPERTIES limits. See HIVE-1364.
+table_name:widetable_250_cols, constraints:exclude, table_format:hbase/none/none
+table_name:widetable_500_cols, constraints:exclude, table_format:hbase/none/none
+table_name:widetable_1000_cols, constraints:exclude, table_format:hbase/none/none
+
# nullformat_custom is used in null-insert tests, which user insert overwrite,
# which is not supported in hbase. The schema is also specified in HIVE_CREATE
# with no corresponding LOAD statement.
[30/50] [abbrv] incubator-impala git commit: IMPALA-4461: Make sure
data gets loaded for wide hbase tables.
Posted by ta...@apache.org.
IMPALA-4461: Make sure data gets loaded for wide hbase tables.
Ths patch reverts a change that broke the exhaustive suite of Impala
tests. The change was introduced here:
https://github.com/apache/incubator-impala/commit/ce4c5f67433ebe050261710920972621d625c81c
The orginal problem was that data load was failing when run against a
remote cluster, due to a 4000 byte max for SERDEPROPERTIES.PARAM_VALUE,
a limitation that is well described in HIVE-1364. Locally, when we load
data, we work around the issue here:
https://github.com/apache/incubator-impala/blob/master/bin/create-test-configuration.sh#L99
When testing on CDH remote cluster however, this "fix" never gets applied.
(It also assumes the database will always by postgres.)
I made this change without realizing its full effect, or appreciating
exactly how exhaustive our exhaustive test suite really is. Another
solution will need to be found for the case of remote cluster testing,
but this should unblock the local build for now.
As far as testing, I ran the full suite of tests in query_test/
test_scanners.py, and they all pass after removing these lines.
Change-Id: If2148d6546789c6c53c8e045717081b24ce76689
Reviewed-on: http://gerrit.cloudera.org:8080/5033
Reviewed-by: Dan Hecht <dh...@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/b14f3197
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/b14f3197
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/b14f3197
Branch: refs/heads/hadoop-next
Commit: b14f319708943b14680c77b2afbc502a056d06a1
Parents: 0aeb680
Author: David Knupp <dk...@cloudera.com>
Authored: Wed Nov 9 17:55:46 2016 -0800
Committer: Internal Jenkins <cl...@gerrit.cloudera.org>
Committed: Fri Nov 11 00:37:59 2016 +0000
----------------------------------------------------------------------
testdata/datasets/functional/schema_constraints.csv | 5 -----
1 file changed, 5 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/b14f3197/testdata/datasets/functional/schema_constraints.csv
----------------------------------------------------------------------
diff --git a/testdata/datasets/functional/schema_constraints.csv b/testdata/datasets/functional/schema_constraints.csv
index 790dba4..d6d1111 100644
--- a/testdata/datasets/functional/schema_constraints.csv
+++ b/testdata/datasets/functional/schema_constraints.csv
@@ -118,11 +118,6 @@ table_name:overflow, constraint:restrict_to, table_format:text/none/none
# seem to like this.
table_name:widerow, constraint:exclude, table_format:hbase/none/none
-# Wide tables fail due to the SERDEPROPERTIES limits. See HIVE-1364.
-table_name:widetable_250_cols, constraints:exclude, table_format:hbase/none/none
-table_name:widetable_500_cols, constraints:exclude, table_format:hbase/none/none
-table_name:widetable_1000_cols, constraints:exclude, table_format:hbase/none/none
-
# nullformat_custom is used in null-insert tests, which user insert overwrite,
# which is not supported in hbase. The schema is also specified in HIVE_CREATE
# with no corresponding LOAD statement.
[37/50] [abbrv] incubator-impala git commit: IMPALA-1654: General
partition exprs in DDL operations.
Posted by ta...@apache.org.
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/testdata/workloads/functional-query/queries/QueryTest/alter-table.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/alter-table.test b/testdata/workloads/functional-query/queries/QueryTest/alter-table.test
index 3b1d86b..3230b9e 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/alter-table.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/alter-table.test
@@ -247,6 +247,9 @@ bigint,bigint,string,string,string,string,string,string
# change the table fileformat to match the data
alter table jointbl_test set fileformat sequencefile
---- RESULTS
+'Updated table.'
+---- TYPES
+string
====
---- QUERY
# now the proper data should be returned
@@ -333,10 +336,16 @@ alter table t_part add partition (j=NULL, s=NULL)
# be read twice.
alter table t_part drop partition (j=100, s='same_location')
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
alter table t_part drop partition (j=101, s='different_part_dir')
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
insert overwrite table t_part partition(j=NULL, s=NULL)
@@ -392,6 +401,9 @@ int,int,string
---- QUERY
alter table t_part drop partition (j=NULL, s=NULL)
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select i, j, s from t_part
@@ -413,6 +425,9 @@ int,int,string
---- QUERY
alter table t_part drop partition (j=NULL, s=trim(' 2013 '))
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select i, j, s from t_part
@@ -429,6 +444,9 @@ int,int,string
---- QUERY
alter table t_part drop partition (j=1, s='2013')
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select i, j, s from t_part
@@ -442,6 +460,9 @@ int,int,string
---- QUERY
alter table t_part drop partition (j=1, s='2012/withslash')
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select i, j, s from t_part
@@ -480,6 +501,9 @@ int,int,string
# Drop default partition using empty string as key
alter table t_part drop partition (j=2, s='')
---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
# Validate previous partition drop
@@ -528,6 +552,9 @@ set location '$FILESYSTEM_PREFIX/test-warehouse/alltypes_seq_snap/year=2009/mont
alter table alltypes_test partition(month=4, year=2009)
set fileformat sequencefile
---- RESULTS
+'Updated 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select int_col, count(*) from alltypes_test
@@ -557,6 +584,9 @@ set location '$FILESYSTEM_PREFIX/test-warehouse/alltypes_rc/year=2009/month=5'
alter table alltypes_test partition(month=cast(2+3 as int), year=2009)
set fileformat rcfile
---- RESULTS
+'Updated 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
select int_col, count(*) from alltypes_test
@@ -591,12 +621,18 @@ STRING, STRING, BIGINT, BIGINT, STRING, STRING, STRING, STRING, STRING, STRING
# Test altering the 'numRows' table property of a table.
alter table alltypes_test set tblproperties ('numRows'='200')
---- RESULTS
+'Updated table.'
+---- TYPES
+string
====
---- QUERY
# Test altering the 'numRows' table property of a partition.
alter table alltypes_test partition(year=2009, month=4)
set tblproperties ('numRows'='30', 'STATS_GENERATED_VIA_STATS_TASK'='true')
---- RESULTS
+'Updated 1 partition(s).'
+---- TYPES
+string
====
---- QUERY
# Show the table stats after altering the table and partition stats.
@@ -770,6 +806,9 @@ set serdeproperties(
'valuevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluev
aluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalueval
uevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalue
valuevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalueva
luevaluevalue'
)
---- RESULTS
+'Updated table.'
+---- TYPES
+string
====
---- QUERY
# alter with property lengths just within limits
@@ -780,6 +819,9 @@ set tblproperties(
'valuevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluev
aluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalueval
uevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalue
valuevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevaluevalueva
luevaluevalue'
)
---- RESULTS
+'Updated table.'
+---- TYPES
+string
====
---- QUERY
-- Change table location after a partition has been created in the original table location
@@ -926,6 +968,9 @@ STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING, STRING,
create table i1740_alter_1 (i1 integer);
alter table i1740_alter_1 set tblproperties ('skip.header.line.count'='2');
---- RESULTS
+'Updated table.'
+---- TYPES
+string
====
---- QUERY
# IMPALA-1740: Test setting the skip.header.line.count tblproperty
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test b/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
index a5ddb90..817dd4d 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/compute-stats.test
@@ -262,6 +262,7 @@ STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
# Drop the partitions with NULL values and check for stats.
alter table alltypes drop partition (year=NULL, month=NULL)
---- RESULTS
+'Dropped 1 partition(s).'
====
---- QUERY
show column stats alltypes
@@ -287,6 +288,7 @@ STRING, STRING, BIGINT, BIGINT, INT, DOUBLE
---- QUERY
alter table alltypes drop partition (year=2011, month=NULL)
---- RESULTS
+'Dropped 1 partition(s).'
====
---- QUERY
show column stats alltypes
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/testdata/workloads/functional-query/queries/QueryTest/hdfs-caching.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/hdfs-caching.test b/testdata/workloads/functional-query/queries/QueryTest/hdfs-caching.test
index 9477958..8896c3a 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/hdfs-caching.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/hdfs-caching.test
@@ -358,7 +358,7 @@ location 'file://$IMPALA_HOME/testdata/data/cached_local_part'
# Turning on caching for this new partition should fail
alter table cached_tbl_local partition(j=0) set cached in 'testPool'
---- CATCH
-Partition (j=0) cannot be cached. Please check if the table or partitions are on a filesystem which supports caching.
+Partition(s) (j=0) cannot be cached. Please check if the table or partitions are on a filesystem which supports caching.
====
---- QUERY
# Turning on caching should also fail for this table
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/testdata/workloads/functional-query/queries/QueryTest/kudu_alter.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/kudu_alter.test b/testdata/workloads/functional-query/queries/QueryTest/kudu_alter.test
index e6814e1..4572a5f 100644
--- a/testdata/workloads/functional-query/queries/QueryTest/kudu_alter.test
+++ b/testdata/workloads/functional-query/queries/QueryTest/kudu_alter.test
@@ -10,6 +10,9 @@ alter table simple set tblproperties (
'kudu.master_addresses' = 'localhost'
)
---- RESULTS
+'Updated table.'
+---- TYPES
+STRING
====
---- QUERY
-- Show that new address is picked up
@@ -22,6 +25,9 @@ STRING,STRING,STRING
---- QUERY
alter table simple set tblproperties ('kudu.master_addresses' = '127.0.0.1')
---- RESULTS
+'Updated table.'
+---- TYPES
+STRING
====
---- QUERY
-- Try to use an invalid master address
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/testdata/workloads/functional-query/queries/QueryTest/partition-ddl-predicates.test
----------------------------------------------------------------------
diff --git a/testdata/workloads/functional-query/queries/QueryTest/partition-ddl-predicates.test b/testdata/workloads/functional-query/queries/QueryTest/partition-ddl-predicates.test
new file mode 100644
index 0000000..cc7e865
--- /dev/null
+++ b/testdata/workloads/functional-query/queries/QueryTest/partition-ddl-predicates.test
@@ -0,0 +1,156 @@
+====
+---- QUERY
+# First create a partitioned table
+create table p1 (i int) partitioned by(j int, k string);
+# Add some partitions
+alter table p1 add partition (j=1,k="a");
+alter table p1 add partition (j=1,k="b");
+alter table p1 add partition (j=1,k="c");
+alter table p1 add partition (j=2,k="d");
+alter table p1 add partition (j=2,k="e");
+alter table p1 add partition (j=2,k="f");
+alter table p1 add partition (j=2,k=NULL);
+alter table p1 add partition (j=NULL,k="g");
+alter table p1 add partition (j=NULL,k=NULL);
+# Populate the table
+insert into p1 partition (j, k) values (100, 1, "a"), (200, 1, "b"), (300, 1, "c");
+====
+---- QUERY
+show partitions p1
+---- RESULTS
+'NULL','NULL',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=__HIVE_DEFAULT_PARTITION__/k=__HIVE_DEFAULT_PARTITION__
+'NULL','g',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=__HIVE_DEFAULT_PARTITION__/k=g
+'1','a',-1,1,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=1/k=a
+'1','b',-1,1,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=1/k=b
+'1','c',-1,1,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=1/k=c
+'2','NULL',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=__HIVE_DEFAULT_PARTITION__
+'2','d',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=d
+'2','e',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=e
+'2','f',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=f
+'Total','',-1,3,regex:.+,regex:.+,'','','',''
+---- TYPES
+STRING, STRING, BIGINT, BIGINT, STRING, STRING, STRING, STRING, STRING, STRING
+====
+---- QUERY
+show files in p1 partition (j<2, k="a")
+---- RESULTS
+regex:.+,regex:.+,'j=1/k=a'
+---- TYPES
+STRING, STRING, STRING
+====
+---- QUERY
+alter table p1 partition (j<2, k in ("b", "c")) set cached in 'testPool'
+---- RESULTS
+'Cached 2 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (j<2, j>0, k<>"d") set uncached
+---- RESULTS
+'Uncached 2 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (j=3 or j=2, k like "%") set uncached
+---- RESULTS
+'Uncached 0 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (j=2) set fileformat parquet
+---- RESULTS
+'Updated 4 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (k rlike ".*") set serdeproperties ('k'='v')
+---- RESULTS
+'Updated 7 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (k="") set serdeproperties ('k'='v')
+---- RESULTS
+'Updated 2 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (k=null) set serdeproperties ('k'='v')
+---- RESULTS
+'Updated 2 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 partition (j is not null) set tblproperties ('k'='v')
+---- RESULTS
+'Updated 7 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+compute incremental stats p1 partition(j<2)
+---- RESULTS
+'Updated 3 partition(s) and 1 column(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop partition (j<2)
+---- RESULTS
+'Dropped 3 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop partition (j<2)
+---- RESULTS
+'Dropped 0 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop if exists partition (j<2)
+---- RESULTS
+'Dropped 0 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop if exists partition (j=2, k="bla")
+---- RESULTS
+'Dropped 0 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop partition (j=2, k=NULL)
+---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+alter table p1 drop partition (j IS NULL AND k IS NULL);
+---- RESULTS
+'Dropped 1 partition(s).'
+---- TYPES
+STRING
+====
+---- QUERY
+show partitions p1
+---- RESULTS
+'NULL','g',-1,0,regex:.+,regex:.+,regex:.+,regex:.+,regex:.+,regex:.*/test-warehouse/.+/p1/j=__HIVE_DEFAULT_PARTITION__/k=g
+'2','d',-1,0,regex:.+,regex:.+,regex:.+,'PARQUET',regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=d
+'2','e',-1,0,regex:.+,regex:.+,regex:.+,'PARQUET',regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=e
+'2','f',-1,0,regex:.+,regex:.+,regex:.+,'PARQUET',regex:.+,regex:.*/test-warehouse/.+/p1/j=2/k=f
+'Total','',0,0,regex:.+,regex:.+,'','','',''
+---- TYPES
+STRING, STRING, BIGINT, BIGINT, STRING, STRING, STRING, STRING, STRING, STRING
+====
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/628685ae/tests/metadata/test_ddl.py
----------------------------------------------------------------------
diff --git a/tests/metadata/test_ddl.py b/tests/metadata/test_ddl.py
index 8079855..15fe4c7 100644
--- a/tests/metadata/test_ddl.py
+++ b/tests/metadata/test_ddl.py
@@ -391,6 +391,10 @@ class TestDdlStatements(TestDdlBase):
assert properties['p2'] == 'val3'
assert properties[''] == ''
+ @UniqueDatabase.parametrize(sync_ddl=True)
+ def test_partition_ddl_predicates(self, vector, unique_database):
+ self.run_test_case('QueryTest/partition-ddl-predicates', vector,
+ use_db=unique_database, multiple_impalad=self._use_multiple_impalad(vector))
# IMPALA-2002: Tests repeated adding/dropping of .jar and .so in the lib cache.
class TestLibCache(TestDdlBase):
[31/50] [abbrv] incubator-impala git commit: IMPALA-4455:
MemPoolTest.TryAllocateAligned failure: sizeof v. alignof
Posted by ta...@apache.org.
IMPALA-4455: MemPoolTest.TryAllocateAligned failure: sizeof v. alignof
This was testing all memory alignments up to and including
sizeof(max_align_t), but the standard says nothing about that. It does
say things about alignof(max_align_t), including that malloc() returns
memory at least that aligned.
In both gcc and clang on our currently supported platforms,
max_align_t has sizeof == 32 and alignof == 16, so this test expected
an alignment that malloc was not guaranteed to provide.
Change-Id: Ic2dbabcb9af2874d8ed354738243dfca9c492b08
Reviewed-on: http://gerrit.cloudera.org:8080/5022
Reviewed-by: Henry Robinson <he...@cloudera.com>
Reviewed-by: Dan Hecht <dh...@cloudera.com>
Tested-by: Jim Apple <jb...@cloudera.com>
Project: http://git-wip-us.apache.org/repos/asf/incubator-impala/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-impala/commit/c68734ad
Tree: http://git-wip-us.apache.org/repos/asf/incubator-impala/tree/c68734ad
Diff: http://git-wip-us.apache.org/repos/asf/incubator-impala/diff/c68734ad
Branch: refs/heads/hadoop-next
Commit: c68734ad6509869e8660cd1bad05e53461137474
Parents: b14f319
Author: Jim Apple <jb...@cloudera.com>
Authored: Wed Nov 9 14:22:20 2016 -0800
Committer: Jim Apple <jb...@cloudera.com>
Committed: Fri Nov 11 03:44:07 2016 +0000
----------------------------------------------------------------------
be/src/exprs/anyval-util.cc | 9 ++++-----
be/src/exprs/anyval-util.h | 22 ++++++++++++++++++++++
be/src/runtime/mem-pool-test.cc | 2 +-
be/src/runtime/mem-pool.cc | 2 +-
be/src/runtime/mem-pool.h | 12 ++++++------
5 files changed, 34 insertions(+), 13 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c68734ad/be/src/exprs/anyval-util.cc
----------------------------------------------------------------------
diff --git a/be/src/exprs/anyval-util.cc b/be/src/exprs/anyval-util.cc
index e4d9337..132d6e4 100644
--- a/be/src/exprs/anyval-util.cc
+++ b/be/src/exprs/anyval-util.cc
@@ -31,11 +31,10 @@ namespace impala {
Status AllocateAnyVal(RuntimeState* state, MemPool* pool, const ColumnType& type,
const std::string& mem_limit_exceeded_msg, AnyVal** result) {
- int anyval_size = AnyValUtil::AnyValSize(type);
- // Ensure the allocation is sufficiently aligned (e.g. DecimalVal has a 16-byte
- // alignment requirement).
- int alignment = BitUtil::RoundUpToPowerOfTwo(anyval_size);
- *result = reinterpret_cast<AnyVal*>(pool->TryAllocateAligned(anyval_size, alignment));
+ const int anyval_size = AnyValUtil::AnyValSize(type);
+ const int anyval_alignment = AnyValUtil::AnyValAlignment(type);
+ *result =
+ reinterpret_cast<AnyVal*>(pool->TryAllocateAligned(anyval_size, anyval_alignment));
if (*result == NULL) {
return pool->mem_tracker()->MemLimitExceeded(
state, mem_limit_exceeded_msg, anyval_size);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c68734ad/be/src/exprs/anyval-util.h
----------------------------------------------------------------------
diff --git a/be/src/exprs/anyval-util.h b/be/src/exprs/anyval-util.h
index b84187a..8c75247 100644
--- a/be/src/exprs/anyval-util.h
+++ b/be/src/exprs/anyval-util.h
@@ -179,6 +179,28 @@ class AnyValUtil {
}
}
+ /// Returns the byte alignment of *Val for type t.
+ static int AnyValAlignment(const ColumnType& t) {
+ switch (t.type) {
+ case TYPE_BOOLEAN: return alignof(BooleanVal);
+ case TYPE_TINYINT: return alignof(TinyIntVal);
+ case TYPE_SMALLINT: return alignof(SmallIntVal);
+ case TYPE_INT: return alignof(IntVal);
+ case TYPE_BIGINT: return alignof(BigIntVal);
+ case TYPE_FLOAT: return alignof(FloatVal);
+ case TYPE_DOUBLE: return alignof(DoubleVal);
+ case TYPE_STRING:
+ case TYPE_VARCHAR:
+ case TYPE_CHAR:
+ return alignof(StringVal);
+ case TYPE_TIMESTAMP: return alignof(TimestampVal);
+ case TYPE_DECIMAL: return alignof(DecimalVal);
+ default:
+ DCHECK(false) << t;
+ return 0;
+ }
+ }
+
static std::string ToString(const StringVal& v) {
return std::string(reinterpret_cast<char*>(v.ptr), v.len);
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c68734ad/be/src/runtime/mem-pool-test.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool-test.cc b/be/src/runtime/mem-pool-test.cc
index 70fb141..e6cb3b9 100644
--- a/be/src/runtime/mem-pool-test.cc
+++ b/be/src/runtime/mem-pool-test.cc
@@ -506,7 +506,7 @@ TEST(MemPoolTest, TryAllocateAligned) {
uint8_t* ptr = pool.TryAllocateAligned(size, alignment);
ASSERT_TRUE(ptr != NULL);
ASSERT_EQ(0, reinterpret_cast<uintptr_t>(ptr) % alignment);
- alignment = alignment == sizeof(std::max_align_t) ? 1 : alignment * 2;
+ alignment = alignment == alignof(std::max_align_t) ? 1 : alignment * 2;
size = (size + 1) % MAX_ALLOCATION_SIZE;
}
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c68734ad/be/src/runtime/mem-pool.cc
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.cc b/be/src/runtime/mem-pool.cc
index c95953a..5f3feca 100644
--- a/be/src/runtime/mem-pool.cc
+++ b/be/src/runtime/mem-pool.cc
@@ -133,7 +133,7 @@ bool MemPool::FindChunk(int64_t min_size, bool check_limits) noexcept {
if (FLAGS_disable_mem_pools) {
// Disable pooling by sizing the chunk to fit only this allocation.
// Make sure the alignment guarantees are respected.
- chunk_size = std::max<int64_t>(min_size, sizeof(std::max_align_t));
+ chunk_size = std::max<int64_t>(min_size, alignof(std::max_align_t));
} else {
DCHECK_GE(next_chunk_size_, INITIAL_CHUNK_SIZE);
chunk_size = max<int64_t>(min_size, next_chunk_size_);
http://git-wip-us.apache.org/repos/asf/incubator-impala/blob/c68734ad/be/src/runtime/mem-pool.h
----------------------------------------------------------------------
diff --git a/be/src/runtime/mem-pool.h b/be/src/runtime/mem-pool.h
index 8980d22..b0fa694 100644
--- a/be/src/runtime/mem-pool.h
+++ b/be/src/runtime/mem-pool.h
@@ -111,10 +111,10 @@ class MemPool {
}
/// Same as TryAllocate() except a non-default alignment can be specified. It
- /// should be a power-of-two in [1, sizeof(std::max_align_t)].
+ /// should be a power-of-two in [1, alignof(std::max_align_t)].
uint8_t* TryAllocateAligned(int64_t size, int alignment) noexcept {
DCHECK_GE(alignment, 1);
- DCHECK_LE(alignment, sizeof(std::max_align_t));
+ DCHECK_LE(alignment, alignof(std::max_align_t));
DCHECK_EQ(BitUtil::RoundUpToPowerOfTwo(alignment), alignment);
return Allocate<true>(size, alignment);
}
@@ -255,11 +255,11 @@ class MemPool {
}
if (!fits_in_chunk) {
- // If we couldn't allocate a new chunk, return NULL.
- // malloc() guarantees alignment of min(std::max_align_t, min_chunk_size),
- // so we do not need to do anything additional to guarantee alignment.
+ // If we couldn't allocate a new chunk, return NULL. malloc() guarantees alignment
+ // of alignof(std::max_align_t), so we do not need to do anything additional to
+ // guarantee alignment.
static_assert(
- INITIAL_CHUNK_SIZE >= sizeof(std::max_align_t), "Min chunk size too low");
+ INITIAL_CHUNK_SIZE >= alignof(std::max_align_t), "Min chunk size too low");
if (UNLIKELY(!FindChunk(size, CHECK_LIMIT_FIRST))) return NULL;
}