You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@hive.apache.org by kg...@apache.org on 2019/05/13 12:51:02 UTC
[hive] branch master updated (5c425dc -> cdf8d8b)
This is an automated email from the ASF dual-hosted git repository.
kgyrtkirk pushed a change to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git.
from 5c425dc HIVE-21717 : Rename is failing for directory in move task. (Mahesh Kumar Behera reviewed by Sankar Hariappan
new 86a1560 HIVE-21662: Refactor some functionality from QTestUtil to separate classes (Laszlo Bodor via Zoltan Haindrich, Zoltan Haindrich)
new cdf8d8b HIVE-21703: Break up DDLTask - extract Partition related operations (Miklos Gergely via Zoltan Haindrich)
The 2 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails. The revisions
listed as "add" were already present in the repository and have only
been added to this reference.
Summary of changes:
.../cli/SemanticAnalysis/HCatSemanticAnalyzer.java | 37 +-
.../hive/hcatalog/streaming/HiveEndPoint.java | 4 +-
.../apache/hadoop/hive/ql/TestLocationQueries.java | 6 +-
.../org/apache/hadoop/hive/ql/TestMTQueries.java | 4 +-
.../hive/ql/parse/TestReplicationScenarios.java | 11 +-
.../jdbc/TestJdbcWithMiniHS2ErasureCoding.java | 2 +-
.../hadoop/hive/accumulo/AccumuloQTestUtil.java | 1 +
.../hadoop/hive/accumulo/AccumuloTestSetup.java | 7 +-
.../hadoop/hive/cli/control/AbstractCliConfig.java | 11 +-
.../control/AbstractCoreBlobstoreCliDriver.java | 2 +-
.../apache/hadoop/hive/cli/control/CliConfigs.java | 86 +-
.../hive/cli/control/CoreAccumuloCliDriver.java | 2 +-
.../hadoop/hive/cli/control/CoreCliDriver.java | 13 +-
.../hive/cli/control/CoreCompareCliDriver.java | 20 +-
.../apache/hadoop/hive/cli/control/CoreDummy.java | 5 +-
.../hive/cli/control/CoreHBaseCliDriver.java | 2 +-
.../cli/control/CoreHBaseNegativeCliDriver.java | 2 +-
.../hive/cli/control/CoreNegativeCliDriver.java | 20 +-
.../hadoop/hive/cli/control/CorePerfCliDriver.java | 57 +-
.../apache/hadoop/hive/hbase/HBaseQTestUtil.java | 3 +-
.../apache/hadoop/hive/hbase/HBaseTestSetup.java | 6 +-
.../apache/hadoop/hive/ql/QFileVersionHandler.java | 91 ++
.../org/apache/hadoop/hive/ql/QOutProcessor.java | 8 +-
.../org/apache/hadoop/hive/ql/QTestArguments.java | 35 +-
.../apache/hadoop/hive/ql/QTestMiniClusters.java | 615 ++++++++++
.../hadoop/hive/ql/QTestResultProcessor.java | 234 ++++
.../apache/hadoop/hive/ql/QTestRunnerUtils.java | 172 +++
.../org/apache/hadoop/hive/ql/QTestSyntaxUtil.java | 14 +-
.../hadoop/hive/ql/QTestSystemProperties.java | 72 ++
.../java/org/apache/hadoop/hive/ql/QTestUtil.java | 1193 ++------------------
.../hive/ql/dataset/QTestDatasetHandler.java | 142 +++
.../hadoop/hive/ql/parse/CoreParseNegative.java | 33 +-
.../main/java/org/apache/hive/beeline/QFile.java | 4 +-
.../apache/hive/beeline/QFileBeeLineClient.java | 3 +-
.../apache/hadoop/hive/ql/TestQOutProcessor.java | 4 +-
.../hadoop/hive/ql/ddl/table/AlterTableUtils.java | 64 ++
.../partition/AlterTableAddPartitionDesc.java} | 45 +-
.../partition/AlterTableAddPartitionOperation.java | 49 +
.../partition/AlterTableAlterPartitionDesc.java | 80 ++
.../AlterTableAlterPartitionOperation.java | 137 +++
.../partition/AlterTableDropPartitionDesc.java} | 38 +-
.../AlterTableDropPartitionOperation.java | 115 ++
.../AlterTableExchangePartitionsDesc.java} | 48 +-
.../AlterTableExchangePartitionsOperation.java | 65 ++
.../partition/AlterTableRenamePartitionDesc.java | 103 ++
.../AlterTableRenamePartitionOperation.java | 99 ++
.../table/partition}/ShowPartitionsDesc.java | 78 +-
.../table/partition/ShowPartitionsOperation.java | 66 ++
.../table/partition/package-info.java} | 10 +-
.../org/apache/hadoop/hive/ql/exec/DDLTask.java | 357 ------
.../exec/repl/bootstrap/events/PartitionEvent.java | 4 +-
.../ql/exec/repl/bootstrap/events/TableEvent.java | 4 +-
.../events/filesystem/FSPartitionEvent.java | 6 +-
.../bootstrap/events/filesystem/FSTableEvent.java | 16 +-
.../exec/repl/bootstrap/load/ReplicationState.java | 8 +-
.../repl/bootstrap/load/table/LoadPartitions.java | 44 +-
.../org/apache/hadoop/hive/ql/metadata/Hive.java | 23 +-
.../hadoop/hive/ql/parse/DDLSemanticAnalyzer.java | 62 +-
.../hive/ql/parse/ImportSemanticAnalyzer.java | 47 +-
.../repl/load/message/DropPartitionHandler.java | 12 +-
.../repl/load/message/RenamePartitionHandler.java | 10 +-
.../hive/ql/plan/AlterTableAlterPartDesc.java | 72 --
.../org/apache/hadoop/hive/ql/plan/DDLWork.java | 102 --
.../hadoop/hive/ql/plan/RenamePartitionDesc.java | 141 ---
.../clientpositive/alter_partition_change_col.q | 1 +
.../clientpositive/alter_rename_partition.q | 1 +
.../clientpositive/drop_partitions_filter.q | 5 +
.../queries/clientpositive/exchgpartition2lel.q | 1 +
.../test/queries/clientpositive/show_partitions.q | 4 +-
.../add_partition_with_whitelist.q.out | 2 +-
ql/src/test/results/clientnegative/addpart1.q.out | 2 +-
.../alter_partition_with_whitelist.q.out | 2 +-
.../alter_rename_partition_failure.q.out | 2 +-
.../alter_rename_partition_failure2.q.out | 2 +-
.../clientnegative/exchange_partition.q.out | 2 +-
ql/src/test/results/clientnegative/external2.q.out | 2 +-
.../results/clientpositive/add_part_multiple.q.out | 4 +-
.../alter_partition_change_col.q.out | 16 +
.../clientpositive/alter_rename_partition.q.out | 22 +
.../clientpositive/drop_deleted_partitions.q.out | 5 +-
.../clientpositive/drop_multi_partitions.q.out | 5 +-
.../clientpositive/drop_partitions_filter.q.out | 72 ++
.../clientpositive/llap/exchgpartition2lel.q.out | 19 +
.../results/clientpositive/show_partitions.q.out | 47 +
ql/src/test/results/clientpositive/showparts.q.out | 5 +-
.../clientpositive/spark/add_part_multiple.q.out | 4 +-
.../hive/streaming/HiveStreamingConnection.java | 4 +-
87 files changed, 2783 insertions(+), 2272 deletions(-)
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/QFileVersionHandler.java
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestMiniClusters.java
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestResultProcessor.java
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestRunnerUtils.java
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSystemProperties.java
create mode 100644 itests/util/src/main/java/org/apache/hadoop/hive/ql/dataset/QTestDatasetHandler.java
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/AlterTableUtils.java
rename ql/src/java/org/apache/hadoop/hive/ql/{plan/AddPartitionDesc.java => ddl/table/partition/AlterTableAddPartitionDesc.java} (87%)
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionOperation.java
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionDesc.java
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionOperation.java
rename ql/src/java/org/apache/hadoop/hive/ql/{plan/DropPartitionDesc.java => ddl/table/partition/AlterTableDropPartitionDesc.java} (67%)
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionOperation.java
rename ql/src/java/org/apache/hadoop/hive/ql/{plan/AlterTableExchangePartition.java => ddl/table/partition/AlterTableExchangePartitionsDesc.java} (53%)
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsOperation.java
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionDesc.java
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionOperation.java
rename ql/src/java/org/apache/hadoop/hive/ql/{plan => ddl/table/partition}/ShowPartitionsDesc.java (52%)
create mode 100644 ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsOperation.java
copy ql/src/java/org/apache/hadoop/hive/ql/{exec/repl/bootstrap/events/PartitionEvent.java => ddl/table/partition/package-info.java} (76%)
delete mode 100644 ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableAlterPartDesc.java
delete mode 100644 ql/src/java/org/apache/hadoop/hive/ql/plan/RenamePartitionDesc.java
[hive] 01/02: HIVE-21662: Refactor some functionality from
QTestUtil to separate classes (Laszlo Bodor via Zoltan Haindrich,
Zoltan Haindrich)
Posted by kg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
kgyrtkirk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git
commit 86a15600ae610e1c6017019883ef9344585572ef
Author: Laszlo Bodor <bo...@gmail.com>
AuthorDate: Mon May 13 14:45:47 2019 +0200
HIVE-21662: Refactor some functionality from QTestUtil to separate classes (Laszlo Bodor via Zoltan Haindrich, Zoltan Haindrich)
Signed-off-by: Zoltan Haindrich <ki...@rxd.hu>
---
.../apache/hadoop/hive/ql/TestLocationQueries.java | 6 +-
.../org/apache/hadoop/hive/ql/TestMTQueries.java | 4 +-
.../jdbc/TestJdbcWithMiniHS2ErasureCoding.java | 2 +-
.../hadoop/hive/accumulo/AccumuloQTestUtil.java | 1 +
.../hadoop/hive/accumulo/AccumuloTestSetup.java | 7 +-
.../hadoop/hive/cli/control/AbstractCliConfig.java | 11 +-
.../control/AbstractCoreBlobstoreCliDriver.java | 2 +-
.../apache/hadoop/hive/cli/control/CliConfigs.java | 86 +-
.../hive/cli/control/CoreAccumuloCliDriver.java | 2 +-
.../hadoop/hive/cli/control/CoreCliDriver.java | 13 +-
.../hive/cli/control/CoreCompareCliDriver.java | 20 +-
.../apache/hadoop/hive/cli/control/CoreDummy.java | 5 +-
.../hive/cli/control/CoreHBaseCliDriver.java | 2 +-
.../cli/control/CoreHBaseNegativeCliDriver.java | 2 +-
.../hive/cli/control/CoreNegativeCliDriver.java | 20 +-
.../hadoop/hive/cli/control/CorePerfCliDriver.java | 57 +-
.../apache/hadoop/hive/hbase/HBaseQTestUtil.java | 3 +-
.../apache/hadoop/hive/hbase/HBaseTestSetup.java | 6 +-
.../apache/hadoop/hive/ql/QFileVersionHandler.java | 91 ++
.../org/apache/hadoop/hive/ql/QOutProcessor.java | 8 +-
.../org/apache/hadoop/hive/ql/QTestArguments.java | 35 +-
.../apache/hadoop/hive/ql/QTestMiniClusters.java | 615 ++++++++++
.../hadoop/hive/ql/QTestResultProcessor.java | 234 ++++
.../apache/hadoop/hive/ql/QTestRunnerUtils.java | 172 +++
.../org/apache/hadoop/hive/ql/QTestSyntaxUtil.java | 14 +-
.../hadoop/hive/ql/QTestSystemProperties.java | 72 ++
.../java/org/apache/hadoop/hive/ql/QTestUtil.java | 1193 ++------------------
.../hive/ql/dataset/QTestDatasetHandler.java | 142 +++
.../hadoop/hive/ql/parse/CoreParseNegative.java | 33 +-
.../main/java/org/apache/hive/beeline/QFile.java | 4 +-
.../apache/hive/beeline/QFileBeeLineClient.java | 3 +-
.../apache/hadoop/hive/ql/TestQOutProcessor.java | 4 +-
32 files changed, 1576 insertions(+), 1293 deletions(-)
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestLocationQueries.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestLocationQueries.java
index 405d21c..38bdcb1 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestLocationQueries.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestLocationQueries.java
@@ -24,7 +24,7 @@ import java.io.FileReader;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
/**
* Suite for testing location. e.g. if "alter table alter partition
@@ -117,13 +117,13 @@ public class TestLocationQueries extends BaseTestQueries {
QTestUtil[] qt = new QTestUtil[qfiles.length];
for (int i = 0; i < qfiles.length; i++) {
- qt[i] = new CheckResults(resDir, logDir, MiniClusterType.none, "parta");
+ qt[i] = new CheckResults(resDir, logDir, MiniClusterType.NONE, "parta");
qt[i].newSession();
qt[i].addFile(qfiles[i], false);
qt[i].clearTestSideEffects();
}
- boolean success = QTestUtil.queryListRunnerSingleThreaded(qfiles, qt);
+ boolean success = QTestRunnerUtils.queryListRunnerSingleThreaded(qfiles, qt);
if (!success) {
fail("One or more queries failed");
}
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestMTQueries.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestMTQueries.java
index 62c037e..e336712 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestMTQueries.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/TestMTQueries.java
@@ -36,7 +36,7 @@ public class TestMTQueries extends BaseTestQueries {
String[] testNames = new String[] {"join2.q", "groupby1.q", "input1.q", "input19.q"};
File[] qfiles = setupQFiles(testNames);
- QTestUtil[] qts = QTestUtil.queryListRunnerSetup(qfiles, resDir, logDir, "q_test_init_src_with_stats.sql",
+ QTestUtil[] qts = QTestRunnerUtils.queryListRunnerSetup(qfiles, resDir, logDir, "q_test_init_src_with_stats.sql",
"q_test_cleanup_src_with_stats.sql");
for (QTestUtil util : qts) {
// derby fails creating multiple stats aggregator concurrently
@@ -48,7 +48,7 @@ public class TestMTQueries extends BaseTestQueries {
util.getConf().set("hive.stats.column.autogather", "false");
util.newSession();
}
- boolean success = QTestUtil.queryListRunnerMultiThreaded(qfiles, qts);
+ boolean success = QTestRunnerUtils.queryListRunnerMultiThreaded(qfiles, qts);
if (!success) {
fail("One or more queries failed");
}
diff --git a/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestJdbcWithMiniHS2ErasureCoding.java b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestJdbcWithMiniHS2ErasureCoding.java
index b2ddff7..ca77db0 100644
--- a/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestJdbcWithMiniHS2ErasureCoding.java
+++ b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestJdbcWithMiniHS2ErasureCoding.java
@@ -50,7 +50,7 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
-import static org.apache.hadoop.hive.ql.QTestUtil.DEFAULT_TEST_EC_POLICY;
+import static org.apache.hadoop.hive.ql.QTestMiniClusters.DEFAULT_TEST_EC_POLICY;
import static org.apache.hive.jdbc.TestJdbcWithMiniHS2.getDetailedTableDescription;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloQTestUtil.java b/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloQTestUtil.java
index 01c3c0b..acf64b0 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloQTestUtil.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloQTestUtil.java
@@ -18,6 +18,7 @@
package org.apache.hadoop.hive.accumulo;
import org.apache.hadoop.hive.ql.QTestArguments;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.QTestUtil;
/**
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloTestSetup.java b/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloTestSetup.java
index c599814..4e24e15 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloTestSetup.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/accumulo/AccumuloTestSetup.java
@@ -20,9 +20,6 @@ import java.io.File;
import java.sql.Date;
import java.sql.Timestamp;
-import junit.extensions.TestSetup;
-import junit.framework.Test;
-
import org.apache.accumulo.core.client.AccumuloException;
import org.apache.accumulo.core.client.AccumuloSecurityException;
import org.apache.accumulo.core.client.BatchWriter;
@@ -37,12 +34,12 @@ import org.apache.accumulo.minicluster.MiniAccumuloConfig;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.hive.common.type.HiveDecimal;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.QTestMiniClusters;
/**
* Start and stop an AccumuloMiniCluster for testing purposes
*/
-public class AccumuloTestSetup extends QTestUtil.QTestSetup {
+public class AccumuloTestSetup extends QTestMiniClusters.QTestSetup {
public static final String PASSWORD = "password";
public static final String TABLE_NAME = "accumuloHiveTable";
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCliConfig.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCliConfig.java
index 142f903..e964490 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCliConfig.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCliConfig.java
@@ -33,9 +33,9 @@ import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
-import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.FsType;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestSystemProperties;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hive.testutils.HiveTestEnvSetup;
import com.google.common.base.Splitter;
@@ -76,7 +76,7 @@ public abstract class AbstractCliConfig {
public AbstractCliConfig(Class<? extends CliAdapter> adapter) {
cliAdapter = adapter;
- clusterType = MiniClusterType.none;
+ clusterType = MiniClusterType.NONE;
queryFile = getSysPropValue("qfile");
queryFileRegex = getSysPropValue("qfile_regex");
runDisabled = getSysPropValue("run_disabled");
@@ -244,7 +244,8 @@ public abstract class AbstractCliConfig {
for (String qFileName : excludedQueryFileNames) {
// in case of running as ptest, exclusions should be respected,
// because test drivers receive every qfiles regardless of exclusions
- if ("hiveptest".equals(System.getProperty("user.name")) || !isQFileSpecified()) {
+ if ("hiveptest".equals(System.getProperty("user.name")) || !isQFileSpecified()
+ || QTestSystemProperties.shouldForceExclusions()) {
testFiles.remove(new File(queryDir, qFileName));
}
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCoreBlobstoreCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCoreBlobstoreCliDriver.java
index 6a15c00..2431859 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCoreBlobstoreCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/AbstractCoreBlobstoreCliDriver.java
@@ -31,7 +31,7 @@ import org.apache.hadoop.hive.conf.VariableSubstitution;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hive.testutils.HiveTestEnvSetup;
import org.junit.After;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CliConfigs.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CliConfigs.java
index 1108e49..5c17e1a 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CliConfigs.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CliConfigs.java
@@ -21,8 +21,8 @@ import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
-import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.parse.CoreParseNegative;
public class CliConfigs {
@@ -74,7 +74,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -94,7 +94,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/perf-reg/");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -116,7 +116,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.mr);
+ setClusterType(MiniClusterType.MR);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -141,9 +141,9 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_tez.sql");
setHiveConfDir("data/conf/tez");
- setClusterType(MiniClusterType.tez);
+ setClusterType(MiniClusterType.TEZ);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.hdfs);
+ setFsType(QTestMiniClusters.FsType.HDFS);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -166,7 +166,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.llap);
+ setClusterType(MiniClusterType.LLAP);
setMetastoreType(MetastoreType.sql);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
@@ -192,9 +192,9 @@ public class CliConfigs {
setInitScript("q_test_druid_init.sql");
setCleanupScript("q_test_cleanup_druid.sql");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.druid);
+ setClusterType(MiniClusterType.DRUID);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.hdfs);
+ setFsType(QTestMiniClusters.FsType.HDFS);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -213,9 +213,9 @@ public class CliConfigs {
setInitScript("q_test_druid_init.sql");
setCleanupScript("q_test_cleanup_druid.sql");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.druidKafka);
+ setClusterType(MiniClusterType.DRUID_KAFKA);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.hdfs);
+ setFsType(QTestMiniClusters.FsType.HDFS);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -231,9 +231,9 @@ public class CliConfigs {
setResultsDir("ql/src/test/results/clientpositive/kafka");
setLogDir("itests/qtest/target/tmp/log");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.kafka);
+ setClusterType(MiniClusterType.KAFKA);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.hdfs);
+ setFsType(QTestMiniClusters.FsType.HDFS);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -267,9 +267,9 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.llap_local);
+ setClusterType(MiniClusterType.LLAP_LOCAL);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.local);
+ setFsType(QTestMiniClusters.FsType.LOCAL);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -291,9 +291,9 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
- setClusterType(MiniClusterType.mr);
- setFsType(QTestUtil.FsType.encrypted_hdfs);
- if (getClusterType() == MiniClusterType.tez) {
+ setClusterType(MiniClusterType.MR);
+ setFsType(QTestMiniClusters.FsType.ENCRYPTED_HDFS);
+ if (getClusterType() == MiniClusterType.TEZ) {
setHiveConfDir("data/conf/tez");
} else {
setHiveConfDir("data/conf");
@@ -359,7 +359,7 @@ public class CliConfigs {
setCleanupScript("q_perf_test_cleanup.sql");
setHiveConfDir("data/conf/perf-reg/tez");
- setClusterType(MiniClusterType.tez);
+ setClusterType(MiniClusterType.TEZ);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -381,7 +381,7 @@ public class CliConfigs {
setCleanupScript("q_perf_test_cleanup.sql");
setHiveConfDir("data/conf/perf-reg/spark");
- setClusterType(MiniClusterType.spark);
+ setClusterType(MiniClusterType.SPARK);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -401,7 +401,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_compare.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -425,7 +425,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -447,7 +447,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.mr);
+ setClusterType(MiniClusterType.MR);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -467,7 +467,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -487,7 +487,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_compare.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -507,7 +507,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -527,7 +527,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -549,7 +549,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -570,7 +570,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup_src.sql");
setHiveConfDir("");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -593,7 +593,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/spark/standalone");
- setClusterType(MiniClusterType.spark);
+ setClusterType(MiniClusterType.SPARK);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -615,7 +615,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/spark/local");
- setClusterType(MiniClusterType.spark);
+ setClusterType(MiniClusterType.SPARK);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -638,7 +638,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/spark/yarn-cluster");
- setClusterType(MiniClusterType.miniSparkOnYarn);
+ setClusterType(MiniClusterType.MINI_SPARK_ON_YARN);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -661,7 +661,7 @@ public class CliConfigs {
setCleanupScript("q_test_cleanup.sql");
setHiveConfDir("data/conf/spark/standalone");
- setClusterType(MiniClusterType.spark);
+ setClusterType(MiniClusterType.SPARK);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -681,7 +681,7 @@ public class CliConfigs {
setCleanupScript("blobstore_test_cleanup.q");
setHiveConfDir("itests/hive-blobstore/src/test/resources");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -701,7 +701,7 @@ public class CliConfigs {
setCleanupScript("blobstore_test_cleanup.q");
setHiveConfDir("itests/hive-blobstore/src/test/resources");
- setClusterType(MiniClusterType.none);
+ setClusterType(MiniClusterType.NONE);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
@@ -726,8 +726,8 @@ public class CliConfigs {
setInitScript("q_test_init_src.sql");
setCleanupScript("q_test_cleanup_src.sql");
- setClusterType(MiniClusterType.mr);
- setFsType(QTestUtil.FsType.erasure_coded_hdfs);
+ setClusterType(MiniClusterType.MR);
+ setFsType(QTestMiniClusters.FsType.ERASURE_CODED_HDFS);
setHiveConfDir(getClusterType());
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
@@ -739,13 +739,13 @@ public class CliConfigs {
*/
private void setHiveConfDir(MiniClusterType clusterType) {
switch (clusterType) {
- case tez:
+ case TEZ:
setHiveConfDir("data/conf/tez");
break;
- case spark:
+ case SPARK:
setHiveConfDir("data/conf/spark/standalone");
break;
- case miniSparkOnYarn:
+ case MINI_SPARK_ON_YARN:
setHiveConfDir("data/conf/spark/yarn-cluster");
break;
default:
@@ -769,9 +769,9 @@ public class CliConfigs {
setInitScript("q_test_druid_init.sql");
setCleanupScript("q_test_cleanup_druid.sql");
setHiveConfDir("data/conf/llap");
- setClusterType(MiniClusterType.druidLocal);
+ setClusterType(MiniClusterType.DRUID_LOCAL);
setMetastoreType(MetastoreType.sql);
- setFsType(QTestUtil.FsType.local);
+ setFsType(QTestMiniClusters.FsType.LOCAL);
} catch (Exception e) {
throw new RuntimeException("can't construct cliconfig", e);
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreAccumuloCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreAccumuloCliDriver.java
index 9b5d5e3..432d6ea 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreAccumuloCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreAccumuloCliDriver.java
@@ -25,7 +25,7 @@ import java.io.File;
import org.apache.hadoop.hive.accumulo.AccumuloQTestUtil;
import org.apache.hadoop.hive.accumulo.AccumuloTestSetup;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.junit.After;
import org.junit.AfterClass;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCliDriver.java
index 2411843..1d453ec 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCliDriver.java
@@ -28,7 +28,7 @@ import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.util.ElapsedTimeLoggingWrapper;
import org.junit.After;
@@ -167,11 +167,6 @@ public class CoreCliDriver extends CliAdapter {
}
}
- private static String debugHint =
- "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
- + "or check ./ql/target/surefire-reports "
- + "or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
-
@Override
public void runTest(String testName, String fname, String fpath) {
Stopwatch sw = Stopwatch.createStarted();
@@ -188,7 +183,7 @@ public class CoreCliDriver extends CliAdapter {
int ecode = response.getResponseCode();
if (ecode != 0) {
failed = true;
- qt.failedQuery(response.getException(), response.getResponseCode(), fname, debugHint);
+ qt.failedQuery(response.getException(), response.getResponseCode(), fname, QTestUtil.DEBUG_HINT);
}
setupAdditionalPartialMasks();
@@ -196,14 +191,14 @@ public class CoreCliDriver extends CliAdapter {
resetAdditionalPartialMasks();
if (result.getReturnCode() != 0) {
failed = true;
- String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? debugHint
+ String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? QTestUtil.DEBUG_HINT
: "\r\n" + result.getCapturedOutput();
qt.failedDiff(result.getReturnCode(), fname, message);
}
}
catch (Exception e) {
failed = true;
- qt.failedWithException(e, fname, debugHint);
+ qt.failedWithException(e, fname, QTestUtil.DEBUG_HINT);
} finally {
String message = "Done query " + fname + ". succeeded=" + !failed + ", skipped=" + skipped +
". ElapsedTime(ms)=" + sw.stop().elapsed(TimeUnit.MILLISECONDS);
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCompareCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCompareCliDriver.java
index 2dfee13..a2aa8bf 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCompareCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreCompareCliDriver.java
@@ -23,10 +23,11 @@ import java.io.File;
import java.util.ArrayList;
import java.util.List;
+import org.apache.hadoop.hive.ql.QFileVersionHandler;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.junit.After;
import org.junit.AfterClass;
@@ -37,6 +38,7 @@ import com.google.common.base.Strings;
public class CoreCompareCliDriver extends CliAdapter{
private static QTestUtil qt;
+ private QFileVersionHandler qvh = new QFileVersionHandler();
public CoreCompareCliDriver(AbstractCliConfig testCliConfig) {
super(testCliConfig);
@@ -116,9 +118,6 @@ public class CoreCompareCliDriver extends CliAdapter{
}
}
- private static String debugHint = "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
- + "or check ./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
-
@Override
public void runTest(String tname, String fname, String fpath) {
final String queryDirectory = cliConfig.getQueryDirectory();
@@ -127,7 +126,7 @@ public class CoreCompareCliDriver extends CliAdapter{
try {
System.err.println("Begin query: " + fname);
// TODO: versions could also be picked at build time.
- List<String> versionFiles = QTestUtil.getVersionFiles(queryDirectory, tname);
+ List<String> versionFiles = qvh.getVersionFiles(queryDirectory, tname);
if (versionFiles.size() < 2) {
fail("Cannot run " + tname + " with only " + versionFiles.size() + " versions");
}
@@ -147,19 +146,18 @@ public class CoreCompareCliDriver extends CliAdapter{
// TODO: will this work?
CommandProcessorResponse response = qt.executeClient(versionFile, fname);
if (response.getResponseCode() != 0) {
- qt.failedQuery(response.getException(), response.getResponseCode(), fname, debugHint);
+ qt.failedQuery(response.getException(), response.getResponseCode(), fname, QTestUtil.DEBUG_HINT);
}
}
QTestProcessExecResult result = qt.checkCompareCliDriverResults(fname, outputs);
if (result.getReturnCode() != 0) {
- String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ?
- debugHint : "\r\n" + result.getCapturedOutput();
+ String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? QTestUtil.DEBUG_HINT
+ : "\r\n" + result.getCapturedOutput();
qt.failedDiff(result.getReturnCode(), fname, message);
}
- }
- catch (Exception e) {
- qt.failedWithException(e, fname, debugHint);
+ } catch (Exception e) {
+ qt.failedWithException(e, fname, QTestUtil.DEBUG_HINT);
}
long elapsedTime = System.currentTimeMillis() - startTime;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreDummy.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreDummy.java
index a0d1433..301b91e 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreDummy.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreDummy.java
@@ -21,9 +21,10 @@ import static org.junit.Assert.fail;
import java.util.List;
-import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.QFileVersionHandler;
public class CoreDummy extends CliAdapter {
+ QFileVersionHandler qvh = new QFileVersionHandler();
public CoreDummy(AbstractCliConfig cliConfig) {
super(cliConfig);
@@ -47,7 +48,7 @@ public class CoreDummy extends CliAdapter {
@Override
public void runTest(String name, String name2, String absolutePath) {
- List<String> versionFiles = QTestUtil.getVersionFiles(cliConfig.getQueryDirectory(), name);
+ List<String> versionFiles = qvh.getVersionFiles(cliConfig.getQueryDirectory(), name);
if (versionFiles.size() < 2) {
fail("Cannot run " + name2 + " with only " + versionFiles.size() + " versions");
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseCliDriver.java
index ec187d9..5c6597d 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseCliDriver.java
@@ -25,7 +25,7 @@ import java.io.File;
import org.apache.hadoop.hive.hbase.HBaseQTestUtil;
import org.apache.hadoop.hive.hbase.HBaseTestSetup;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.junit.After;
import org.junit.AfterClass;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseNegativeCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseNegativeCliDriver.java
index b65e805..7725618 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseNegativeCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreHBaseNegativeCliDriver.java
@@ -26,7 +26,7 @@ import java.io.File;
import org.apache.hadoop.hive.hbase.HBaseQTestUtil;
import org.apache.hadoop.hive.hbase.HBaseTestSetup;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreNegativeCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreNegativeCliDriver.java
index 8f66b1f..16fdd6b 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreNegativeCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CoreNegativeCliDriver.java
@@ -25,7 +25,7 @@ import java.io.File;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
@@ -113,9 +113,6 @@ public class CoreNegativeCliDriver extends CliAdapter{
}
}
- private static String debugHint = "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
- + "or check ./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
-
@Override
public void runTest(String tname, String fname, String fpath) throws Exception {
long startTime = System.currentTimeMillis();
@@ -127,25 +124,24 @@ public class CoreNegativeCliDriver extends CliAdapter{
int ecode = qt.executeClient(fname).getResponseCode();
if (ecode == 0) {
- qt.failed(fname, debugHint);
+ qt.failed(fname, QTestUtil.DEBUG_HINT);
}
QTestProcessExecResult result = qt.checkCliDriverResults(fname);
if (result.getReturnCode() != 0) {
- String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ?
- debugHint : "\r\n" + result.getCapturedOutput();
+ String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? QTestUtil.DEBUG_HINT
+ : "\r\n" + result.getCapturedOutput();
qt.failedDiff(result.getReturnCode(), fname, message);
}
} catch (Error error) {
QTestProcessExecResult qTestProcessExecResult = qt.checkNegativeResults(fname, error);
if (qTestProcessExecResult.getReturnCode() != 0) {
- String message = Strings.isNullOrEmpty(qTestProcessExecResult.getCapturedOutput()) ? debugHint :
- "\r\n" + qTestProcessExecResult.getCapturedOutput();
+ String message = Strings.isNullOrEmpty(qTestProcessExecResult.getCapturedOutput())
+ ? QTestUtil.DEBUG_HINT : "\r\n" + qTestProcessExecResult.getCapturedOutput();
qt.failedDiff(qTestProcessExecResult.getReturnCode(), fname, message);
}
- }
- catch (Exception e) {
- qt.failedWithException(e, fname, debugHint);
+ } catch (Exception e) {
+ qt.failedWithException(e, fname, QTestUtil.DEBUG_HINT);
}
long elapsedTime = System.currentTimeMillis() - startTime;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CorePerfCliDriver.java b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CorePerfCliDriver.java
index 81ce5cb..1613e96 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CorePerfCliDriver.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/cli/control/CorePerfCliDriver.java
@@ -18,8 +18,6 @@
package org.apache.hadoop.hive.cli.control;
-
-
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
@@ -28,26 +26,24 @@ import java.io.File;
import org.apache.hadoop.hive.ql.MetaStoreDumpUtility;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
+import org.apache.hadoop.hive.ql.QTestSystemProperties;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.junit.After;
import org.junit.AfterClass;
import com.google.common.base.Strings;
+
/**
- This is the TestPerformance Cli Driver for integrating performance regression tests
- as part of the Hive Unit tests.
- Currently this includes support for :
- 1. Running explain plans for TPCDS workload (non-partitioned dataset) on 30TB scaleset.
- TODO :
- 1. Support for partitioned data set
- 2. Use HBase Metastore instead of Derby
-
-This suite differs from TestCliDriver w.r.t the fact that we modify the underlying metastore
-database to reflect the dataset before running the queries.
-*/
-public class CorePerfCliDriver extends CliAdapter{
+ * This is the TestPerformance Cli Driver for integrating performance regression tests as part of
+ * the Hive Unit tests. Currently this includes support for : 1. Running explain plans for TPCDS
+ * workload (non-partitioned dataset) on 30TB scaleset. TODO : 1. Support for partitioned data set
+ * 2. Use HBase Metastore instead of Derby
+ * This suite differs from TestCliDriver w.r.t the fact that we modify the underlying metastore
+ * database to reflect the dataset before running the queries.
+ */
+public class CorePerfCliDriver extends CliAdapter {
private static QTestUtil qt;
@@ -66,16 +62,10 @@ public class CorePerfCliDriver extends CliAdapter{
String cleanupScript = cliConfig.getCleanupScript();
try {
- qt = new QTestUtil(
- QTestArguments.QTestArgumentsBuilder.instance()
- .withOutDir(cliConfig.getResultsDir())
- .withLogDir(cliConfig.getLogDir())
- .withClusterType(miniMR)
- .withConfDir(hiveConfDir)
- .withInitScript(initScript)
- .withCleanupScript(cleanupScript)
- .withLlapIo(false)
- .build());
+ qt = new QTestUtil(QTestArguments.QTestArgumentsBuilder.instance()
+ .withOutDir(cliConfig.getResultsDir()).withLogDir(cliConfig.getLogDir())
+ .withClusterType(miniMR).withConfDir(hiveConfDir).withInitScript(initScript)
+ .withCleanupScript(cleanupScript).withLlapIo(false).build());
// do a one time initialization
qt.newSession();
@@ -84,13 +74,14 @@ public class CorePerfCliDriver extends CliAdapter{
// Manually modify the underlying metastore db to reflect statistics corresponding to
// the 30TB TPCDS scale set. This way the optimizer will generate plans for a 30 TB set.
MetaStoreDumpUtility.setupMetaStoreTableColumnStatsFor30TBTPCDSWorkload(qt.getConf(),
- System.getProperty(QTestUtil.TEST_TMP_DIR_PROPERTY));
+ QTestSystemProperties.getTempDir());
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
e.printStackTrace();
System.err.flush();
- throw new RuntimeException("Unexpected exception in static initialization: " + e.getMessage(), e);
+ throw new RuntimeException("Unexpected exception in static initialization: " + e.getMessage(),
+ e);
}
}
@@ -127,10 +118,6 @@ public class CorePerfCliDriver extends CliAdapter{
}
}
- private static String debugHint =
- "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
- + "or check ./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
-
@Override
public void runTest(String name, String fname, String fpath) {
long startTime = System.currentTimeMillis();
@@ -143,17 +130,17 @@ public class CorePerfCliDriver extends CliAdapter{
CommandProcessorResponse response = qt.executeClient(fname);
int ecode = response.getResponseCode();
if (ecode != 0) {
- qt.failedQuery(response.getException(), response.getResponseCode(), fname, debugHint);
+ qt.failedQuery(response.getException(), response.getResponseCode(), fname, QTestUtil.DEBUG_HINT);
}
QTestProcessExecResult result = qt.checkCliDriverResults(fname);
if (result.getReturnCode() != 0) {
- String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ?
- debugHint : "\r\n" + result.getCapturedOutput();
+ String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? QTestUtil.DEBUG_HINT
+ : "\r\n" + result.getCapturedOutput();
qt.failedDiff(result.getReturnCode(), fname, message);
}
} catch (Exception e) {
- qt.failedWithException(e, fname, debugHint);
+ qt.failedWithException(e, fname, QTestUtil.DEBUG_HINT);
}
long elapsedTime = System.currentTimeMillis() - startTime;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseQTestUtil.java b/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseQTestUtil.java
index e8e5176..a327167 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseQTestUtil.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseQTestUtil.java
@@ -21,6 +21,7 @@ import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hive.ql.QTestArguments;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.apache.hadoop.hive.ql.QTestUtil;
/**
@@ -62,7 +63,7 @@ public class HBaseQTestUtil extends QTestUtil {
super.createSources(tname);
conf.setBoolean("hive.test.init.phase", true);
- initDataset(HBASE_SRC_NAME);
+ datasetHandler.initDataset(HBASE_SRC_NAME, getCliDriver());
// create a snapshot
Admin admin = null;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseTestSetup.java b/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseTestSetup.java
index ec38aea..7501580 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseTestSetup.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/hbase/HBaseTestSetup.java
@@ -29,15 +29,15 @@ import org.apache.hadoop.hbase.HBaseTestingUtility;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HConstants;
import org.apache.hadoop.hbase.HTableDescriptor;
+import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
-import org.apache.hadoop.hbase.MiniHBaseCluster;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.hive.conf.HiveConf;
-import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.QTestSetup;
import org.apache.hadoop.mapred.JobConf;
import org.apache.zookeeper.Watcher;
@@ -45,7 +45,7 @@ import org.apache.zookeeper.Watcher;
* HBaseTestSetup defines HBase-specific test fixtures which are
* reused across testcases.
*/
-public class HBaseTestSetup extends QTestUtil.QTestSetup {
+public class HBaseTestSetup extends QTestSetup {
private MiniHBaseCluster hbaseCluster;
private HBaseTestingUtility util;
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QFileVersionHandler.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QFileVersionHandler.java
new file mode 100644
index 0000000..4db6cb3
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QFileVersionHandler.java
@@ -0,0 +1,91 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+import java.util.regex.Pattern;
+
+import org.apache.tools.ant.BuildException;
+
+import com.google.common.collect.ImmutableList;
+
+public class QFileVersionHandler {
+ private static final Pattern QV_SUFFIX = Pattern.compile("_[0-9]+.qv$", Pattern.CASE_INSENSITIVE);
+
+ private String[] cachedQvFileList = null;
+ private ImmutableList<String> cachedDefaultQvFileList = null;
+
+ public List<String> getVersionFiles(String queryDir, String tname) {
+ ensureQvFileList(queryDir);
+ List<String> result = getVersionFilesInternal(tname);
+ if (result == null) {
+ result = cachedDefaultQvFileList;
+ }
+ return result;
+ }
+
+ private void ensureQvFileList(String queryDir) {
+ if (cachedQvFileList != null) {
+ return;
+ }
+ // Not thread-safe.
+ System.out.println("Getting versions from " + queryDir);
+ cachedQvFileList = (new File(queryDir)).list(new FilenameFilter() {
+ @Override
+ public boolean accept(File dir, String name) {
+ return name.toLowerCase().endsWith(".qv");
+ }
+ });
+ if (cachedQvFileList == null) {
+ return; // no files at all
+ }
+ Arrays.sort(cachedQvFileList, String.CASE_INSENSITIVE_ORDER);
+ List<String> defaults = getVersionFilesInternal("default");
+ cachedDefaultQvFileList =
+ (defaults != null) ? ImmutableList.copyOf(defaults) : ImmutableList.<String> of();
+ }
+
+ private List<String> getVersionFilesInternal(String tname) {
+ if (cachedQvFileList == null) {
+ return new ArrayList<String>();
+ }
+ int pos = Arrays.binarySearch(cachedQvFileList, tname, String.CASE_INSENSITIVE_ORDER);
+ if (pos >= 0) {
+ throw new BuildException("Unexpected file list element: " + cachedQvFileList[pos]);
+ }
+ List<String> result = null;
+ for (pos = (-pos - 1); pos < cachedQvFileList.length; ++pos) {
+ String candidate = cachedQvFileList[pos];
+ if (candidate.length() <= tname.length()
+ || !tname.equalsIgnoreCase(candidate.substring(0, tname.length()))
+ || !QV_SUFFIX.matcher(candidate.substring(tname.length())).matches()) {
+ break;
+ }
+ if (result == null) {
+ result = new ArrayList<String>();
+ }
+ result.add(candidate);
+ }
+ return result;
+ }
+}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QOutProcessor.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QOutProcessor.java
index ec61b34..2185fd4 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QOutProcessor.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QOutProcessor.java
@@ -34,7 +34,7 @@ import java.util.regex.Pattern;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
-import org.apache.hadoop.hive.ql.QTestUtil.FsType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
/**
* QOutProcessor: produces the final q.out from original q.out by postprocessing (e.g. masks)
@@ -72,7 +72,7 @@ public class QOutProcessor {
private static final Pattern PATTERN_MASK_DATA_SIZE = Pattern.compile("-- MASK_DATA_SIZE");
private static final Pattern PATTERN_MASK_LINEAGE = Pattern.compile("-- MASK_LINEAGE");
- private FsType fsType = FsType.local;
+ private FsType fsType = FsType.LOCAL;
public static class LineProcessingResult {
private String line;
@@ -140,7 +140,7 @@ public class QOutProcessor {
}
public QOutProcessor() {
- this.fsType = FsType.hdfs;
+ this.fsType = FsType.HDFS;
}
private Pattern[] toPattern(String[] patternStrs) {
@@ -194,7 +194,7 @@ public class QOutProcessor {
Matcher matcher = null;
- if (fsType == FsType.encrypted_hdfs) {
+ if (fsType == FsType.ENCRYPTED_HDFS) {
for (Pattern pattern : partialReservedPlanMask) {
matcher = pattern.matcher(result.line);
if (matcher.find()) {
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestArguments.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestArguments.java
index 33412b2..7c0e552 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestArguments.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestArguments.java
@@ -18,6 +18,9 @@
package org.apache.hadoop.hive.ql;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.QTestSetup;
+
/**
* QTestArguments composite used as arguments holder for QTestUtil initialization.
*/
@@ -26,21 +29,21 @@ public final class QTestArguments {
private String outDir;
private String logDir;
private String confDir;
- private QTestUtil.MiniClusterType clusterType;
+ private QTestMiniClusters.MiniClusterType clusterType;
private String initScript;
private String cleanupScript;
private boolean withLlapIo;
- private QTestUtil.FsType fsType;
- private QTestUtil.QTestSetup qtestSetup;
+ private FsType fsType;
+ private QTestSetup qtestSetup;
private QTestArguments() {
}
- public QTestUtil.MiniClusterType getClusterType() {
+ public QTestMiniClusters.MiniClusterType getClusterType() {
return clusterType;
}
- private void setClusterType(QTestUtil.MiniClusterType clusterType) {
+ private void setClusterType(QTestMiniClusters.MiniClusterType clusterType) {
this.clusterType = clusterType;
}
@@ -92,19 +95,19 @@ public final class QTestArguments {
this.withLlapIo = withLlapIo;
}
- public QTestUtil.FsType getFsType() {
+ public FsType getFsType() {
return fsType;
}
- private void setFsType(QTestUtil.FsType fsType) {
+ private void setFsType(QTestMiniClusters.FsType fsType) {
this.fsType = fsType;
}
- public QTestUtil.QTestSetup getQTestSetup() {
+ public QTestSetup getQTestSetup() {
return qtestSetup;
}
- private void setQTestSetup(QTestUtil.QTestSetup qtestSetup) {
+ private void setQTestSetup(QTestSetup qtestSetup) {
this.qtestSetup = qtestSetup;
}
@@ -116,12 +119,12 @@ public final class QTestArguments {
private String outDir;
private String logDir;
private String confDir;
- private QTestUtil.MiniClusterType clusterType;
+ private QTestMiniClusters.MiniClusterType clusterType;
private String initScript;
private String cleanupScript;
private boolean withLlapIo;
- private QTestUtil.FsType fsType;
- private QTestUtil.QTestSetup qtestSetup;
+ private FsType fsType;
+ private QTestSetup qtestSetup;
private QTestArgumentsBuilder(){
}
@@ -145,7 +148,7 @@ public final class QTestArguments {
return this;
}
- public QTestArgumentsBuilder withClusterType(QTestUtil.MiniClusterType clusterType) {
+ public QTestArgumentsBuilder withClusterType(QTestMiniClusters.MiniClusterType clusterType) {
this.clusterType = clusterType;
return this;
}
@@ -165,12 +168,12 @@ public final class QTestArguments {
return this;
}
- public QTestArgumentsBuilder withFsType(QTestUtil.FsType fsType) {
+ public QTestArgumentsBuilder withFsType(QTestMiniClusters.FsType fsType) {
this.fsType = fsType;
return this;
}
- public QTestArgumentsBuilder withQTestSetup(QTestUtil.QTestSetup qtestSetup) {
+ public QTestArgumentsBuilder withQTestSetup(QTestSetup qtestSetup) {
this.qtestSetup = qtestSetup;
return this;
}
@@ -189,7 +192,7 @@ public final class QTestArguments {
fsType != null ? fsType : clusterType.getDefaultFsType());
testArguments.setQTestSetup(
- qtestSetup != null ? qtestSetup : new QTestUtil.QTestSetup());
+ qtestSetup != null ? qtestSetup : new QTestSetup());
return testArguments;
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestMiniClusters.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestMiniClusters.java
new file mode 100644
index 0000000..bd4c76e
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestMiniClusters.java
@@ -0,0 +1,615 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.nio.file.Files;
+import java.nio.file.Paths;
+import java.sql.Timestamp;
+import java.text.SimpleDateFormat;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+import java.util.stream.IntStream;
+
+import org.apache.avro.generic.GenericRecord;
+import org.apache.avro.io.BinaryEncoder;
+import org.apache.avro.io.DatumWriter;
+import org.apache.avro.io.EncoderFactory;
+import org.apache.avro.specific.SpecificDatumWriter;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
+import org.apache.hadoop.hive.cli.CliSessionState;
+import org.apache.hadoop.hive.cli.control.AbstractCliConfig;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
+import org.apache.hadoop.hive.llap.LlapItUtils;
+import org.apache.hadoop.hive.llap.daemon.MiniLlapCluster;
+import org.apache.hadoop.hive.llap.io.api.LlapProxy;
+import org.apache.hadoop.hive.ql.exec.Utilities;
+import org.apache.hadoop.hive.ql.exec.spark.session.SparkSession;
+import org.apache.hadoop.hive.ql.exec.spark.session.SparkSessionManagerImpl;
+import org.apache.hadoop.hive.ql.exec.tez.TezSessionState;
+import org.apache.hadoop.hive.ql.lockmgr.zookeeper.CuratorFrameworkSingleton;
+import org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.apache.hadoop.hive.shims.HadoopShims;
+import org.apache.hadoop.hive.shims.ShimLoader;
+import org.apache.hadoop.hive.shims.HadoopShims.HdfsErasureCodingShim;
+import org.apache.hive.druid.MiniDruidCluster;
+import org.apache.hive.kafka.SingleNodeKafkaCluster;
+import org.apache.hive.kafka.Wikipedia;
+import org.apache.logging.log4j.util.Strings;
+import org.apache.zookeeper.WatchedEvent;
+import org.apache.zookeeper.Watcher;
+import org.apache.zookeeper.ZooKeeper;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.base.Preconditions;
+
+/**
+ * QTestMiniClusters: decouples cluster details from QTestUtil (kafka/druid/spark/llap/tez/mr, file
+ * system)
+ */
+public class QTestMiniClusters {
+ private static final Logger LOG = LoggerFactory.getLogger("QTestMiniClusters");
+ private static final SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
+
+ // security property names
+ private static final String SECURITY_KEY_PROVIDER_URI_NAME = "dfs.encryption.key.provider.uri";
+ /**
+ * The default Erasure Coding Policy to use in Erasure Coding tests.
+ */
+ public static final String DEFAULT_TEST_EC_POLICY = "RS-3-2-1024k";
+
+ private QTestSetup setup;
+ private QTestArguments testArgs;
+ private MiniClusterType clusterType;
+
+ private HadoopShims shims;
+ private SparkSession sparkSession = null;
+ private FileSystem fs;
+ private HadoopShims.MiniMrShim mr = null;
+ private HadoopShims.MiniDFSShim dfs = null;
+ private HadoopShims.HdfsEncryptionShim hes = null;
+ private MiniLlapCluster llapCluster = null;
+ private MiniDruidCluster druidCluster = null;
+ private SingleNodeKafkaCluster kafkaCluster = null;
+
+ public enum CoreClusterType {
+ MR, TEZ, SPARK
+ }
+
+ public enum FsType {
+ LOCAL, HDFS, ENCRYPTED_HDFS, ERASURE_CODED_HDFS,
+ }
+
+ public enum MiniClusterType {
+ MR(CoreClusterType.MR, FsType.HDFS),
+ TEZ(CoreClusterType.TEZ, FsType.HDFS),
+ TEZ_LOCAL(CoreClusterType.TEZ, FsType.LOCAL),
+ SPARK(CoreClusterType.SPARK, FsType.LOCAL),
+ MINI_SPARK_ON_YARN(CoreClusterType.SPARK, FsType.HDFS),
+ LLAP(CoreClusterType.TEZ, FsType.HDFS),
+ LLAP_LOCAL(CoreClusterType.TEZ, FsType.LOCAL),
+ NONE(CoreClusterType.MR,FsType.LOCAL),
+ DRUID_LOCAL(CoreClusterType.TEZ, FsType.LOCAL),
+ DRUID(CoreClusterType.TEZ, FsType.HDFS),
+ DRUID_KAFKA(CoreClusterType.TEZ, FsType.HDFS),
+ KAFKA(CoreClusterType.TEZ, FsType.HDFS);
+
+ private final CoreClusterType coreClusterType;
+ private final FsType defaultFsType;
+
+ MiniClusterType(CoreClusterType coreClusterType, FsType defaultFsType) {
+ this.coreClusterType = coreClusterType;
+ this.defaultFsType = defaultFsType;
+ }
+
+ public CoreClusterType getCoreClusterType() {
+ return coreClusterType;
+ }
+
+ public FsType getDefaultFsType() {
+ return defaultFsType;
+ }
+
+ public static MiniClusterType valueForString(String type) {
+ // Replace this with valueOf.
+ if (type.equals("miniMR")) {
+ return MR;
+ } else if (type.equals("tez")) {
+ return TEZ;
+ } else if (type.equals("tez_local")) {
+ return TEZ_LOCAL;
+ } else if (type.equals("spark")) {
+ return SPARK;
+ } else if (type.equals("miniSparkOnYarn")) {
+ return MINI_SPARK_ON_YARN;
+ } else if (type.equals("llap")) {
+ return LLAP;
+ } else if (type.equals("llap_local")) {
+ return LLAP_LOCAL;
+ } else if (type.equals("druidLocal")) {
+ return DRUID_LOCAL;
+ } else if (type.equals("druid")) {
+ return DRUID;
+ } else if (type.equals("druid-kafka")) {
+ return DRUID_KAFKA;
+ } else if (type.equals("kafka")) {
+ return KAFKA;
+ } else {
+ throw new RuntimeException(String.format("cannot recognize MiniClusterType from '%s'", type));
+ }
+ }
+
+ public String getQOutFileExtensionPostfix() {
+ return toString().toLowerCase();
+ }
+ }
+
+ /**
+ * QTestSetup defines test fixtures which are reused across testcases, and are needed before any
+ * test can be run
+ */
+ public static class QTestSetup {
+ private MiniZooKeeperCluster zooKeeperCluster = null;
+ private int zkPort;
+ private ZooKeeper zooKeeper;
+
+ public QTestSetup() {
+ }
+
+ public void preTest(HiveConf conf) throws Exception {
+
+ if (zooKeeperCluster == null) {
+ // create temp dir
+ File tmpDir = Files
+ .createTempDirectory(Paths.get(QTestSystemProperties.getTempDir()), "tmp_").toFile();
+
+ zooKeeperCluster = new MiniZooKeeperCluster();
+ zkPort = zooKeeperCluster.startup(tmpDir);
+ }
+
+ if (zooKeeper != null) {
+ zooKeeper.close();
+ }
+
+ int sessionTimeout = (int) conf.getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT,
+ TimeUnit.MILLISECONDS);
+ zooKeeper = new ZooKeeper("localhost:" + zkPort, sessionTimeout, new Watcher() {
+ @Override
+ public void process(WatchedEvent arg0) {
+ }
+ });
+
+ String zkServer = "localhost";
+ conf.set("hive.zookeeper.quorum", zkServer);
+ conf.set("hive.zookeeper.client.port", "" + zkPort);
+ }
+
+ public void postTest(HiveConf conf) throws Exception {
+ if (zooKeeperCluster == null) {
+ return;
+ }
+
+ if (zooKeeper != null) {
+ zooKeeper.close();
+ }
+
+ ZooKeeperHiveLockManager.releaseAllLocks(conf);
+ }
+
+ public void tearDown() throws Exception {
+ CuratorFrameworkSingleton.closeAndReleaseInstance();
+
+ if (zooKeeperCluster != null) {
+ zooKeeperCluster.shutdown();
+ zooKeeperCluster = null;
+ }
+ }
+ }
+
+ public void setup(QTestArguments testArgs, HiveConf conf, String scriptsDir,
+ String logDir) throws Exception {
+ this.shims = ShimLoader.getHadoopShims();
+ this.clusterType = testArgs.getClusterType();
+ this.testArgs = testArgs;
+
+ setupFileSystem(testArgs.getFsType(), conf);
+
+ this.setup = testArgs.getQTestSetup();
+ setup.preTest(conf);
+
+ String uriString = fs.getUri().toString();
+
+ if (clusterType == MiniClusterType.DRUID_KAFKA || clusterType == MiniClusterType.DRUID_LOCAL
+ || clusterType == MiniClusterType.DRUID) {
+ final String tempDir = QTestSystemProperties.getTempDir();
+ druidCluster = new MiniDruidCluster(
+ clusterType == MiniClusterType.DRUID ? "mini-druid" : "mini-druid-kafka", logDir, tempDir,
+ setup.zkPort, Utilities.jarFinderGetJar(MiniDruidCluster.class));
+ final Path druidDeepStorage = fs.makeQualified(new Path(druidCluster.getDeepStorageDir()));
+ fs.mkdirs(druidDeepStorage);
+ final Path scratchDir =
+ fs.makeQualified(new Path(QTestSystemProperties.getTempDir(), "druidStagingDir"));
+ fs.mkdirs(scratchDir);
+ conf.set("hive.druid.working.directory", scratchDir.toUri().getPath());
+ druidCluster.init(conf);
+ druidCluster.start();
+ }
+
+ if (clusterType == MiniClusterType.KAFKA || clusterType == MiniClusterType.DRUID_KAFKA) {
+ kafkaCluster =
+ new SingleNodeKafkaCluster("kafka", QTestSystemProperties.getTempDir() + "/kafka-cluster",
+ setup.zkPort, clusterType == MiniClusterType.KAFKA ? 9093 : 9092);
+ kafkaCluster.init(conf);
+ kafkaCluster.start();
+ kafkaCluster.createTopicWithData("test-topic", new File(scriptsDir, "kafka_init_data.json"));
+ kafkaCluster.createTopicWithData("wiki_kafka_csv",
+ new File(scriptsDir, "kafka_init_data.csv"));
+ kafkaCluster.createTopicWithData("wiki_kafka_avro_table", getAvroRows());
+ }
+
+ String confDir = testArgs.getConfDir();
+ if (clusterType.getCoreClusterType() == CoreClusterType.TEZ) {
+ if (confDir != null && !confDir.isEmpty()) {
+ conf.addResource(
+ new URL("file://" + new File(confDir).toURI().getPath() + "/tez-site.xml"));
+ }
+ int numTrackers = 2;
+ if (EnumSet
+ .of(MiniClusterType.LLAP, MiniClusterType.LLAP_LOCAL, MiniClusterType.DRUID_LOCAL,
+ MiniClusterType.DRUID_KAFKA, MiniClusterType.DRUID, MiniClusterType.KAFKA)
+ .contains(clusterType)) {
+ llapCluster = LlapItUtils.startAndGetMiniLlapCluster(conf, setup.zooKeeperCluster, confDir);
+ }
+ if (EnumSet
+ .of(MiniClusterType.LLAP_LOCAL, MiniClusterType.TEZ_LOCAL, MiniClusterType.DRUID_LOCAL)
+ .contains(clusterType)) {
+ mr = shims.getLocalMiniTezCluster(conf,
+ clusterType == MiniClusterType.LLAP_LOCAL || clusterType == MiniClusterType.DRUID_LOCAL);
+ } else {
+ mr = shims
+ .getMiniTezCluster(conf, numTrackers, uriString,
+ EnumSet
+ .of(MiniClusterType.LLAP, MiniClusterType.LLAP_LOCAL,
+ MiniClusterType.DRUID_KAFKA, MiniClusterType.DRUID, MiniClusterType.KAFKA)
+ .contains(clusterType));
+ }
+ } else if (clusterType == MiniClusterType.MINI_SPARK_ON_YARN) {
+ mr = shims.getMiniSparkCluster(conf, 2, uriString, 1);
+ } else if (clusterType == MiniClusterType.MR) {
+ mr = shims.getMiniMrCluster(conf, 2, uriString, 1);
+ }
+
+ if (testArgs.isWithLlapIo() && (clusterType == MiniClusterType.NONE)) {
+ LOG.info("initializing llap IO");
+ LlapProxy.initializeLlapIo(conf);
+ }
+ }
+
+ public void initConf(HiveConf conf) throws IOException {
+ if (mr != null) {
+ mr.setupConfiguration(conf);
+
+ // TODO Ideally this should be done independent of whether mr is setup or not.
+ setFsRelatedProperties(conf, fs.getScheme().equals("file"), fs);
+ }
+
+ if (llapCluster != null) {
+ Configuration clusterSpecificConf = llapCluster.getClusterSpecificConfiguration();
+ for (Map.Entry<String, String> confEntry : clusterSpecificConf) {
+ // Conf.get takes care of parameter replacement, iterator.value does not.
+ conf.set(confEntry.getKey(), clusterSpecificConf.get(confEntry.getKey()));
+ }
+ }
+ if (druidCluster != null) {
+ final Path druidDeepStorage = fs.makeQualified(new Path(druidCluster.getDeepStorageDir()));
+ fs.mkdirs(druidDeepStorage);
+ conf.set("hive.druid.storage.storageDirectory", druidDeepStorage.toUri().getPath());
+ conf.set("hive.druid.metadata.db.type", "derby");
+ conf.set("hive.druid.metadata.uri", druidCluster.getMetadataURI());
+ conf.set("hive.druid.coordinator.address.default", druidCluster.getCoordinatorURI());
+ conf.set("hive.druid.overlord.address.default", druidCluster.getOverlordURI());
+ conf.set("hive.druid.broker.address.default", druidCluster.getBrokerURI());
+ final Path scratchDir =
+ fs.makeQualified(new Path(QTestSystemProperties.getTempDir(), "druidStagingDir"));
+ fs.mkdirs(scratchDir);
+ conf.set("hive.druid.working.directory", scratchDir.toUri().getPath());
+ }
+
+ if (testArgs.isWithLlapIo() && (clusterType == MiniClusterType.NONE)) {
+ LOG.info("initializing llap IO");
+ LlapProxy.initializeLlapIo(conf);
+ }
+ }
+
+ public void postInit(HiveConf conf) {
+ createRemoteDirs(conf);
+ }
+
+ public void preTest(HiveConf conf) throws Exception {
+ setup.preTest(conf);
+ }
+
+ public void postTest(HiveConf conf) throws Exception {
+ setup.postTest(conf);
+ }
+
+ public void restartSessions(boolean canReuseSession, CliSessionState ss, SessionState oldSs)
+ throws IOException {
+ if (oldSs != null && canReuseSession
+ && clusterType.getCoreClusterType() == CoreClusterType.TEZ) {
+ // Copy the tezSessionState from the old CliSessionState.
+ TezSessionState tezSessionState = oldSs.getTezSession();
+ oldSs.setTezSession(null);
+ ss.setTezSession(tezSessionState);
+ oldSs.close();
+ }
+
+ if (oldSs != null && clusterType.getCoreClusterType() == CoreClusterType.SPARK) {
+ sparkSession = oldSs.getSparkSession();
+ ss.setSparkSession(sparkSession);
+ oldSs.setSparkSession(null);
+ oldSs.close();
+ }
+ }
+
+ public void shutDown() throws Exception {
+ if (clusterType.getCoreClusterType() == CoreClusterType.TEZ
+ && SessionState.get().getTezSession() != null) {
+ SessionState.get().getTezSession().destroy();
+ }
+
+ if (druidCluster != null) {
+ druidCluster.stop();
+ druidCluster = null;
+ }
+
+ if (kafkaCluster != null) {
+ kafkaCluster.stop();
+ kafkaCluster = null;
+ }
+ setup.tearDown();
+ if (sparkSession != null) {
+ try {
+ SparkSessionManagerImpl.getInstance().closeSession(sparkSession);
+ } catch (Exception ex) {
+ LOG.error("Error closing spark session.", ex);
+ } finally {
+ sparkSession = null;
+ }
+ }
+ if (mr != null) {
+ mr.shutdown();
+ mr = null;
+ }
+ FileSystem.closeAll();
+ if (dfs != null) {
+ dfs.shutdown();
+ dfs = null;
+ }
+ }
+
+ public void setSparkSession(SparkSession sparkSession) {
+ this.sparkSession = sparkSession;
+ }
+
+ public SparkSession getSparkSession() {
+ return sparkSession;
+ }
+
+ public HadoopShims.HdfsEncryptionShim getHdfsEncryptionShim() {
+ return hes;
+ }
+
+ public HadoopShims.MiniMrShim getMr() {
+ return mr;
+ }
+
+ public MiniClusterType getClusterType() {
+ return this.clusterType;
+ }
+
+ /**
+ * Should deleted test tables have their data purged.
+ *
+ * @return true if data should be purged
+ */
+ public boolean fsNeedsPurge(FsType type) {
+ if (type == FsType.ENCRYPTED_HDFS || type == FsType.ERASURE_CODED_HDFS) {
+ return true;
+ }
+ return false;
+ }
+
+ private void createRemoteDirs(HiveConf conf) {
+ // Create remote dirs once.
+ if (getMr() != null) {
+ assert fs != null;
+ Path warehousePath = fs.makeQualified(new Path(conf.getVar(ConfVars.METASTOREWAREHOUSE)));
+ assert warehousePath != null;
+ Path hiveJarPath = fs.makeQualified(new Path(conf.getVar(ConfVars.HIVE_JAR_DIRECTORY)));
+ assert hiveJarPath != null;
+ Path userInstallPath =
+ fs.makeQualified(new Path(conf.getVar(ConfVars.HIVE_USER_INSTALL_DIR)));
+ assert userInstallPath != null;
+ try {
+ fs.mkdirs(warehousePath);
+ } catch (IOException e) {
+ LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath,
+ e.getMessage());
+ }
+ try {
+ fs.mkdirs(hiveJarPath);
+ } catch (IOException e) {
+ LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath,
+ e.getMessage());
+ }
+ try {
+ fs.mkdirs(userInstallPath);
+ } catch (IOException e) {
+ LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath,
+ e.getMessage());
+ }
+ }
+ }
+
+ private void setupFileSystem(FsType fsType, HiveConf conf) throws IOException {
+ if (fsType == FsType.LOCAL) {
+ fs = FileSystem.getLocal(conf);
+ } else if (fsType == FsType.HDFS || fsType == FsType.ENCRYPTED_HDFS
+ || fsType == FsType.ERASURE_CODED_HDFS) {
+ int numDataNodes = 4;
+
+ // Setup before getting dfs
+ switch (fsType) {
+ case ENCRYPTED_HDFS:
+ // Set the security key provider so that the MiniDFS cluster is initialized
+ // with encryption
+ conf.set(SECURITY_KEY_PROVIDER_URI_NAME, getKeyProviderURI());
+ conf.setInt("fs.trash.interval", 50);
+ break;
+ case ERASURE_CODED_HDFS:
+ // We need more NameNodes for EC.
+ // To fully exercise hdfs code paths we need 5 NameNodes for the RS-3-2-1024k policy.
+ // With 6 NameNodes we can also run the RS-6-3-1024k policy.
+ numDataNodes = 6;
+ break;
+ default:
+ break;
+ }
+
+ dfs = shims.getMiniDfs(conf, numDataNodes, true, null);
+ fs = dfs.getFileSystem();
+
+ // Setup after getting dfs
+ switch (fsType) {
+ case ENCRYPTED_HDFS:
+ // set up the java key provider for encrypted hdfs cluster
+ hes = shims.createHdfsEncryptionShim(fs, conf);
+ LOG.info("key provider is initialized");
+ break;
+ case ERASURE_CODED_HDFS:
+ // The Erasure policy can't be set in a q_test_init script as QTestUtil runs that code in
+ // a mode that disallows test-only CommandProcessors.
+ // Set the default policy on the root of the file system here.
+ HdfsErasureCodingShim erasureCodingShim = shims.createHdfsErasureCodingShim(fs, conf);
+ erasureCodingShim.enableErasureCodingPolicy(DEFAULT_TEST_EC_POLICY);
+ erasureCodingShim.setErasureCodingPolicy(new Path("hdfs:///"), DEFAULT_TEST_EC_POLICY);
+ break;
+ default:
+ break;
+ }
+ } else {
+ throw new IllegalArgumentException("Unknown or unhandled fsType [" + fsType + "]");
+ }
+ }
+
+ private String getKeyProviderURI() {
+ // Use the target directory if it is not specified
+ String HIVE_ROOT = AbstractCliConfig.HIVE_ROOT;
+ String keyDir = HIVE_ROOT + "ql/target/";
+
+ // put the jks file in the current test path only for test purpose
+ return "jceks://file" + new Path(keyDir, "test.jks").toUri();
+ }
+
+ private static List<byte[]> getAvroRows() {
+ int numRows = 10;
+ List<byte[]> events;
+ final DatumWriter<GenericRecord> writer = new SpecificDatumWriter<>(Wikipedia.getClassSchema());
+ events = IntStream.rangeClosed(0, numRows)
+ .mapToObj(i -> Wikipedia.newBuilder()
+ // 1534736225090 -> 08/19/2018 20:37:05
+ .setTimestamp(formatter.format(new Timestamp(1534736225090L + 1000 * 3600 * i)))
+ .setAdded(i * 300).setDeleted(-i).setIsrobot(i % 2 == 0)
+ .setChannel("chanel number " + i).setComment("comment number " + i).setCommentlength(i)
+ .setDiffurl(String.format("url %s", i)).setFlags("flag").setIsminor(i % 2 > 0)
+ .setIsanonymous(i % 3 != 0).setNamespace("namespace")
+ .setIsunpatrolled(new Boolean(i % 3 == 0)).setIsnew(new Boolean(i % 2 > 0))
+ .setPage(String.format("page is %s", i * 100)).setDelta(i).setDeltabucket(i * 100.4)
+ .setUser("test-user-" + i).build())
+ .map(genericRecord -> {
+ java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
+ BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
+ try {
+ writer.write(genericRecord, encoder);
+ encoder.flush();
+ out.close();
+ } catch (IOException e) {
+ throw new RuntimeException(e);
+ }
+ return out.toByteArray();
+ }).collect(Collectors.toList());
+ return events;
+ }
+
+ private void setFsRelatedProperties(HiveConf conf, boolean isLocalFs, FileSystem fs) {
+ String fsUriString = fs.getUri().toString();
+
+ // Different paths if running locally vs a remote fileSystem. Ideally this difference should not
+ // exist.
+ Path warehousePath;
+ Path jarPath;
+ Path userInstallPath;
+ if (isLocalFs) {
+ String buildDir = QTestSystemProperties.getBuildDir();
+ Preconditions.checkState(Strings.isNotBlank(buildDir));
+ Path path = new Path(fsUriString, buildDir);
+
+ // Create a fake fs root for local fs
+ Path localFsRoot = new Path(path, "localfs");
+ warehousePath = new Path(localFsRoot, "warehouse");
+ jarPath = new Path(localFsRoot, "jar");
+ userInstallPath = new Path(localFsRoot, "user_install");
+ } else {
+ // TODO Why is this changed from the default in hive-conf?
+ warehousePath = new Path(fsUriString, "/build/ql/test/data/warehouse/");
+ jarPath = new Path(new Path(fsUriString, "/user"), "hive");
+ userInstallPath = new Path(fsUriString, "/user");
+ }
+
+ warehousePath = fs.makeQualified(warehousePath);
+ jarPath = fs.makeQualified(jarPath);
+ userInstallPath = fs.makeQualified(userInstallPath);
+
+ conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsUriString);
+
+ // Remote dirs
+ conf.setVar(ConfVars.METASTOREWAREHOUSE, warehousePath.toString());
+ conf.setVar(ConfVars.HIVE_JAR_DIRECTORY, jarPath.toString());
+ conf.setVar(ConfVars.HIVE_USER_INSTALL_DIR, userInstallPath.toString());
+ // ConfVars.SCRATCHDIR - {test.tmp.dir}/scratchdir
+
+ // Local dirs
+ // ConfVars.LOCALSCRATCHDIR - {test.tmp.dir}/localscratchdir
+
+ // TODO Make sure to cleanup created dirs.
+ }
+}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestResultProcessor.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestResultProcessor.java
new file mode 100644
index 0000000..18b49fa
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestResultProcessor.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.nio.charset.StandardCharsets;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.io.output.ByteArrayOutputStream;
+import org.apache.hadoop.hive.cli.CliSessionState;
+import org.apache.hadoop.hive.common.io.DigestPrintStream;
+import org.apache.hadoop.hive.common.io.SessionStream;
+import org.apache.hadoop.hive.common.io.SortAndDigestPrintStream;
+import org.apache.hadoop.hive.common.io.SortPrintStream;
+import org.apache.hadoop.hive.ql.session.SessionState;
+import org.apache.hive.common.util.StreamPrinter;
+
+/**
+ * QTestResultProcessor: handles file-level q test result post-processing: sort, diff (similar to
+ * QOutProcessor, but this works with files, and QOutProcessor is for text-processing within a qtest
+ * result file)
+ *
+ */
+public class QTestResultProcessor {
+ private static final Pattern SORT_BEFORE_DIFF = Pattern.compile("-- SORT_BEFORE_DIFF");
+ private static final Pattern SORT_QUERY_RESULTS = Pattern.compile("-- SORT_QUERY_RESULTS");
+ private static final Pattern HASH_QUERY_RESULTS = Pattern.compile("-- HASH_QUERY_RESULTS");
+ private static final Pattern SORT_AND_HASH_QUERY_RESULTS =
+ Pattern.compile("-- SORT_AND_HASH_QUERY_RESULTS");
+ private static final Pattern NO_SESSION_REUSE = Pattern.compile("-- NO_SESSION_REUSE");
+
+ private static final String SORT_SUFFIX = ".sorted";
+
+ private final Set<String> qSortSet = new HashSet<String>();
+ private final Set<String> qSortQuerySet = new HashSet<String>();
+ private final Set<String> qHashQuerySet = new HashSet<String>();
+ private final Set<String> qSortNHashQuerySet = new HashSet<String>();
+ private final Set<String> qNoSessionReuseQuerySet = new HashSet<String>();
+
+ public void add(File qf, String query) {
+ if (matches(SORT_BEFORE_DIFF, query)) {
+ qSortSet.add(qf.getName());
+ } else if (matches(SORT_QUERY_RESULTS, query)) {
+ qSortQuerySet.add(qf.getName());
+ } else if (matches(HASH_QUERY_RESULTS, query)) {
+ qHashQuerySet.add(qf.getName());
+ } else if (matches(SORT_AND_HASH_QUERY_RESULTS, query)) {
+ qSortNHashQuerySet.add(qf.getName());
+ }
+
+ if (matches(NO_SESSION_REUSE, query)) {
+ qNoSessionReuseQuerySet.add(qf.getName());
+ }
+ }
+
+ private boolean matches(Pattern pattern, String query) {
+ Matcher matcher = pattern.matcher(query);
+ if (matcher.find()) {
+ return true;
+ }
+ return false;
+ }
+
+ public boolean shouldSort(String fileName) {
+ return qSortSet.contains(fileName);
+ }
+
+ public void setOutputs(CliSessionState ss, OutputStream fo, String fileName) throws Exception {
+ if (qSortQuerySet.contains(fileName)) {
+ ss.out = new SortPrintStream(fo, "UTF-8");
+ } else if (qHashQuerySet.contains(fileName)) {
+ ss.out = new DigestPrintStream(fo, "UTF-8");
+ } else if (qSortNHashQuerySet.contains(fileName)) {
+ ss.out = new SortAndDigestPrintStream(fo, "UTF-8");
+ } else {
+ ss.out = new SessionStream(fo, true, "UTF-8");
+ }
+ }
+
+ public boolean shouldNotReuseSession(String fileName) {
+ return qNoSessionReuseQuerySet.contains(fileName);
+ }
+
+ public QTestProcessExecResult executeDiffCommand(String inFileName, String outFileName,
+ boolean ignoreWhiteSpace, String tname) throws Exception {
+
+ QTestProcessExecResult result;
+
+ if (shouldSort(tname)) {
+ String inSorted = inFileName + SORT_SUFFIX;
+ String outSorted = outFileName + SORT_SUFFIX;
+
+ sortResult(inFileName, outFileName, inSorted, outSorted);
+
+ inFileName = inSorted;
+ outFileName = outSorted;
+ }
+
+ ArrayList<String> diffCommandArgs = new ArrayList<String>();
+ diffCommandArgs.add("diff");
+
+ // Text file comparison
+ diffCommandArgs.add("-a");
+
+ // Ignore changes in the amount of white space
+ if (ignoreWhiteSpace) {
+ diffCommandArgs.add("-b");
+ }
+
+ // Add files to compare to the arguments list
+ diffCommandArgs.add(getQuotedString(inFileName));
+ diffCommandArgs.add(getQuotedString(outFileName));
+
+ result = executeCmd(diffCommandArgs);
+
+ if (shouldSort(tname)) {
+ new File(inFileName).delete();
+ new File(outFileName).delete();
+ }
+
+ return result;
+ }
+
+ public void overwriteResults(String inFileName, String outFileName) throws Exception {
+ // This method can be replaced with Files.copy(source, target, REPLACE_EXISTING)
+ // once Hive uses JAVA 7.
+ System.out.println("Overwriting results " + inFileName + " to " + outFileName);
+ int result = executeCmd(new String[]{
+ "cp", getQuotedString(inFileName), getQuotedString(outFileName) }).getReturnCode();
+ if (result != 0) {
+ throw new IllegalStateException("Unexpected error while overwriting " + inFileName + " with " + outFileName);
+ }
+ }
+
+ private void sortResult(String inFileName, String outFileName, String inSorted, String outSorted)
+ throws Exception {
+ // sort will try to open the output file in write mode on windows. We need to
+ // close it first.
+ SessionState ss = SessionState.get();
+ if (ss != null && ss.out != null && ss.out != System.out) {
+ ss.out.close();
+ }
+
+ sortFiles(inFileName, inSorted);
+ sortFiles(outFileName, outSorted);
+ }
+
+ private void sortFiles(String in, String out) throws Exception {
+ int result =
+ executeCmd(new String[] { "sort", getQuotedString(in), }, out, null).getReturnCode();
+ if (result != 0) {
+ throw new IllegalStateException("Unexpected error while sorting " + in);
+ }
+ }
+
+ private static QTestProcessExecResult executeCmd(Collection<String> args) throws Exception {
+ return executeCmd(args, null, null);
+ }
+
+ private static QTestProcessExecResult executeCmd(String[] args) throws Exception {
+ return executeCmd(args, null, null);
+ }
+
+ private static QTestProcessExecResult executeCmd(Collection<String> args, String outFile,
+ String errFile) throws Exception {
+ String[] cmdArray = args.toArray(new String[args.size()]);
+ return executeCmd(cmdArray, outFile, errFile);
+ }
+
+ public static QTestProcessExecResult executeCmd(String[] args, String outFile, String errFile)
+ throws Exception {
+ System.out.println("Running: " + org.apache.commons.lang.StringUtils.join(args, ' '));
+
+ PrintStream out = outFile == null ? SessionState.getConsole().getChildOutStream()
+ : new PrintStream(new FileOutputStream(outFile), true, "UTF-8");
+ PrintStream err = errFile == null ? SessionState.getConsole().getChildErrStream()
+ : new PrintStream(new FileOutputStream(errFile), true, "UTF-8");
+
+ Process executor = Runtime.getRuntime().exec(args);
+
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ PrintStream str = new PrintStream(bos, true, "UTF-8");
+
+ StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, err);
+ StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, out, str);
+
+ outPrinter.start();
+ errPrinter.start();
+
+ int result = executor.waitFor();
+
+ outPrinter.join();
+ errPrinter.join();
+
+ if (outFile != null) {
+ out.close();
+ }
+
+ if (errFile != null) {
+ err.close();
+ }
+
+ return QTestProcessExecResult.create(result,
+ new String(bos.toByteArray(), StandardCharsets.UTF_8));
+ }
+
+ private static String getQuotedString(String str) {
+ return str;
+ }
+}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestRunnerUtils.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestRunnerUtils.java
new file mode 100644
index 0000000..1026195
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestRunnerUtils.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql;
+
+import java.io.File;
+
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
+import org.apache.logging.log4j.util.Strings;
+
+public class QTestRunnerUtils {
+ public static final String DEFAULT_INIT_SCRIPT = "q_test_init.sql";
+ public static final String DEFAULT_CLEANUP_SCRIPT = "q_test_cleanup.sql";
+
+ /**
+ * QTRunner: Runnable class for running a single query file.
+ **/
+ public static class QTRunner implements Runnable {
+ private final QTestUtil qt;
+ private final File file;
+
+ public QTRunner(QTestUtil qt, File file) {
+ this.qt = qt;
+ this.file = file;
+ }
+
+ @Override
+ public void run() {
+ try {
+ qt.startSessionState(false);
+ // assumption is that environment has already been cleaned once globally
+ // hence each thread does not call cleanUp() and createSources() again
+ qt.cliInit(file);
+ qt.executeClient(file.getName());
+ } catch (Throwable e) {
+ System.err
+ .println("Query file " + file.getName() + " failed with exception " + e.getMessage());
+ e.printStackTrace();
+ outputTestFailureHelpMessage();
+ }
+ }
+ }
+
+ /**
+ * Setup to execute a set of query files. Uses QTestUtil to do so.
+ *
+ * @param qfiles array of input query files containing arbitrary number of hive queries
+ * @param resDir output directory
+ * @param logDir log directory
+ * @return one QTestUtil for each query file
+ */
+ public static QTestUtil[] queryListRunnerSetup(File[] qfiles, String resDir, String logDir,
+ String initScript, String cleanupScript) throws Exception {
+ QTestUtil[] qt = new QTestUtil[qfiles.length];
+ for (int i = 0; i < qfiles.length; i++) {
+
+ qt[i] = new QTestUtil(QTestArguments.QTestArgumentsBuilder.instance().withOutDir(resDir)
+ .withLogDir(logDir).withClusterType(MiniClusterType.NONE).withConfDir(null)
+ .withInitScript(initScript == null ? DEFAULT_INIT_SCRIPT : initScript)
+ .withCleanupScript(cleanupScript == null ? DEFAULT_CLEANUP_SCRIPT : cleanupScript)
+ .withLlapIo(false).build());
+
+ qt[i].addFile(qfiles[i], false);
+ qt[i].clearTestSideEffects();
+ }
+
+ return qt;
+ }
+
+ /**
+ * Executes a set of query files in sequence.
+ *
+ * @param qfiles array of input query files containing arbitrary number of hive queries
+ * @param qt array of QTestUtils, one per qfile
+ * @return true if all queries passed, false otw
+ */
+ public static boolean queryListRunnerSingleThreaded(File[] qfiles, QTestUtil[] qt)
+ throws Exception {
+ boolean failed = false;
+ qt[0].cleanUp();
+ qt[0].createSources();
+ for (int i = 0; i < qfiles.length && !failed; i++) {
+ qt[i].clearTestSideEffects();
+ qt[i].cliInit(qfiles[i]);
+ qt[i].executeClient(qfiles[i].getName());
+ QTestProcessExecResult result = qt[i].checkCliDriverResults(qfiles[i].getName());
+ if (result.getReturnCode() != 0) {
+ failed = true;
+ StringBuilder builder = new StringBuilder();
+ builder.append("Test ").append(qfiles[i].getName())
+ .append(" results check failed with error code ").append(result.getReturnCode());
+ if (Strings.isNotEmpty(result.getCapturedOutput())) {
+ builder.append(" and diff value ").append(result.getCapturedOutput());
+ }
+ System.err.println(builder.toString());
+ outputTestFailureHelpMessage();
+ }
+ qt[i].clearPostTestEffects();
+ }
+ return (!failed);
+ }
+
+ /**
+ * Executes a set of query files parallel.
+ * <p>
+ * Each query file is run in a separate thread. The caller has to arrange that different query
+ * files do not collide (in terms of destination tables)
+ *
+ * @param qfiles array of input query files containing arbitrary number of hive queries
+ * @param qt array of QTestUtils, one per qfile
+ * @return true if all queries passed, false otw
+ */
+ public static boolean queryListRunnerMultiThreaded(File[] qfiles, QTestUtil[] qt)
+ throws Exception {
+ boolean failed = false;
+
+ // in multithreaded mode - do cleanup/initialization just once
+
+ qt[0].cleanUp();
+ qt[0].createSources();
+ qt[0].clearTestSideEffects();
+
+ QTRunner[] qtRunners = new QTRunner[qfiles.length];
+ Thread[] qtThread = new Thread[qfiles.length];
+
+ for (int i = 0; i < qfiles.length; i++) {
+ qtRunners[i] = new QTRunner(qt[i], qfiles[i]);
+ qtThread[i] = new Thread(qtRunners[i]);
+ }
+
+ for (int i = 0; i < qfiles.length; i++) {
+ qtThread[i].start();
+ }
+
+ for (int i = 0; i < qfiles.length; i++) {
+ qtThread[i].join();
+ QTestProcessExecResult result = qt[i].checkCliDriverResults(qfiles[i].getName());
+ if (result.getReturnCode() != 0) {
+ failed = true;
+ StringBuilder builder = new StringBuilder();
+ builder.append("Test ").append(qfiles[i].getName())
+ .append(" results check failed with error code ").append(result.getReturnCode());
+ if (Strings.isNotEmpty(result.getCapturedOutput())) {
+ builder.append(" and diff value ").append(result.getCapturedOutput());
+ }
+ System.err.println(builder.toString());
+ outputTestFailureHelpMessage();
+ }
+ }
+ return (!failed);
+ }
+
+ public static void outputTestFailureHelpMessage() {
+ System.err.println(QTestUtil.DEBUG_HINT);
+ System.err.flush();
+ }
+}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSyntaxUtil.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSyntaxUtil.java
index 3630da2..3412cae 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSyntaxUtil.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSyntaxUtil.java
@@ -49,26 +49,26 @@ import org.apache.hive.common.util.HiveStringUtils;
*/
public class QTestSyntaxUtil {
- private QTestUtil qUtil;
+ private QTestUtil qTestUtil;
private HiveConf conf;
private ParseDriver pd;
public QTestSyntaxUtil(QTestUtil qTestUtil, HiveConf conf, ParseDriver pd) {
- qUtil = qTestUtil;
+ this.qTestUtil = qTestUtil;
this.conf = conf;
this.pd = pd;
}
public void checkQFileSyntax(List<String> cmds) {
String command = "";
- if (shouldCheckSyntax()) {
+ if (QTestSystemProperties.shouldCheckSyntax()) {
//check syntax first
for (String oneCmd : cmds) {
if (StringUtils.endsWith(oneCmd, "\\")) {
command += StringUtils.chop(oneCmd) + "\\;";
continue;
} else {
- if (qUtil.isHiveCommand(oneCmd)) {
+ if (qTestUtil.isHiveCommand(oneCmd)) {
command = oneCmd;
} else {
command += oneCmd;
@@ -83,10 +83,6 @@ public class QTestSyntaxUtil {
}
}
- private boolean shouldCheckSyntax() {
- return "true".equalsIgnoreCase(System.getProperty("test.check.syntax"));
- }
-
private boolean checkSyntax(String cmd) {
ASTNode tree;
int ret = 0;
@@ -113,7 +109,7 @@ public class QTestSyntaxUtil {
ctx.setCmd(cmd);
ctx.setHDFSCleanup(true);
tree = pd.parse(cmd, ctx);
- qUtil.analyzeAST(tree);
+ qTestUtil.analyzeAST(tree);
} catch (Exception e) {
return false;
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSystemProperties.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSystemProperties.java
new file mode 100644
index 0000000..f82d17e
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestSystemProperties.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql;
+
+import java.util.Set;
+
+public class QTestSystemProperties {
+ public static final String SYS_PROP_TMP_DIR_PROPERTY = "test.tmp.dir"; // typically target/tmp
+ private static final String SYS_PROP_SRC_TABLES_PROPERTY = "test.src.tables";
+ private static final String SYS_PROP_OUTPUT_OVERWRITE = "test.output.overwrite";
+ private static final String SYS_PROP_SRC_UDFS = "test.src.udfs";
+ private static final String SYS_PROP_VECTORIZATION_ENABLED = "test.vectorization.enabled";
+ private static final String SYS_PROP_CHECK_SYNTAX = "test.check.syntax";
+ private static final String SYS_PROP_FORCE_EXCLUSIONS = "test.force.exclusions";
+ private static final String SYS_PROP_BUILD_DIR = "build.dir"; // typically target
+
+ public static String getTempDir() {
+ return System.getProperty(SYS_PROP_TMP_DIR_PROPERTY);
+ }
+
+ public static String[] getSrcTables() {
+ return System.getProperty(SYS_PROP_SRC_TABLES_PROPERTY, "").trim().split(",");
+ }
+
+ public static void setSrcTables(Set<String> srcTables) {
+ System.setProperty(SYS_PROP_SRC_TABLES_PROPERTY, String.join(",", srcTables));
+ }
+
+ public static String[] getSourceUdfs(String defaultTestSrcUDFs) {
+ return System.getProperty(SYS_PROP_SRC_UDFS, defaultTestSrcUDFs).trim().split(",");
+ }
+
+ public static String getBuildDir() {
+ return System.getProperty(SYS_PROP_BUILD_DIR);
+ }
+
+ public static boolean isVectorizationEnabled() {
+ return isTrue(SYS_PROP_VECTORIZATION_ENABLED);
+ }
+
+ public static boolean shouldOverwriteResults() {
+ return isTrue(SYS_PROP_OUTPUT_OVERWRITE);
+ }
+
+ public static boolean shouldCheckSyntax() {
+ return isTrue(SYS_PROP_CHECK_SYNTAX);
+ }
+
+ public static boolean shouldForceExclusions() {
+ return isTrue(SYS_PROP_FORCE_EXCLUSIONS);
+ }
+
+ private static boolean isTrue(String propertyName) {
+ return "true".equals(System.getProperty(propertyName));
+ }
+}
\ No newline at end of file
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
index f77e40a..d2c2ccd 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/QTestUtil.java
@@ -20,84 +20,45 @@ package org.apache.hadoop.hive.ql;
import static org.apache.hadoop.hive.metastore.Warehouse.DEFAULT_DATABASE_NAME;
-import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
-import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
-import java.io.FilenameFilter;
import java.io.IOException;
-import java.io.InputStreamReader;
import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.StringWriter;
import java.net.URL;
-import java.nio.charset.StandardCharsets;
-import java.nio.file.Files;
-import java.nio.file.Paths;
import java.sql.SQLException;
-import java.sql.Timestamp;
-import java.text.SimpleDateFormat;
import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.Deque;
-import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
-import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
-import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-import java.util.stream.IntStream;
-
-import org.apache.avro.generic.GenericRecord;
-import org.apache.avro.io.BinaryEncoder;
-import org.apache.avro.io.DatumWriter;
-import org.apache.avro.io.EncoderFactory;
-import org.apache.avro.specific.SpecificDatumWriter;
-import org.apache.commons.io.IOUtils;
-import org.apache.commons.io.output.ByteArrayOutputStream;
+
+import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
-import org.apache.hadoop.conf.Configuration;
-import org.apache.hadoop.fs.CommonConfigurationKeysPublic;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
import org.apache.hadoop.hive.cli.CliDriver;
import org.apache.hadoop.hive.cli.CliSessionState;
import org.apache.hadoop.hive.cli.control.AbstractCliConfig;
import org.apache.hadoop.hive.common.io.CachingPrintStream;
-import org.apache.hadoop.hive.common.io.DigestPrintStream;
import org.apache.hadoop.hive.common.io.SessionStream;
-import org.apache.hadoop.hive.common.io.SortAndDigestPrintStream;
-import org.apache.hadoop.hive.common.io.SortPrintStream;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
-import org.apache.hadoop.hive.llap.LlapItUtils;
-import org.apache.hadoop.hive.llap.daemon.MiniLlapCluster;
-import org.apache.hadoop.hive.llap.io.api.LlapProxy;
import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.txn.TxnDbUtil;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
import org.apache.hadoop.hive.ql.cache.results.QueryResultsCache;
-import org.apache.hadoop.hive.ql.dataset.Dataset;
-import org.apache.hadoop.hive.ql.dataset.DatasetCollection;
-import org.apache.hadoop.hive.ql.dataset.DatasetParser;
+import org.apache.hadoop.hive.ql.dataset.QTestDatasetHandler;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.Utilities;
-import org.apache.hadoop.hive.ql.exec.spark.session.SparkSession;
-import org.apache.hadoop.hive.ql.exec.spark.session.SparkSessionManagerImpl;
-import org.apache.hadoop.hive.ql.exec.tez.TezSessionState;
-import org.apache.hadoop.hive.ql.lockmgr.zookeeper.CuratorFrameworkSingleton;
-import org.apache.hadoop.hive.ql.lockmgr.zookeeper.ZooKeeperHiveLockManager;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveMaterializedViewsRegistry;
import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
@@ -115,131 +76,49 @@ import org.apache.hadoop.hive.ql.processors.CommandProcessorFactory;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.processors.HiveCommand;
import org.apache.hadoop.hive.ql.session.SessionState;
-import org.apache.hadoop.hive.shims.HadoopShims;
-import org.apache.hadoop.hive.shims.HadoopShims.HdfsErasureCodingShim;
-import org.apache.hadoop.hive.shims.ShimLoader;
-import org.apache.hive.common.util.StreamPrinter;
-import org.apache.hive.druid.MiniDruidCluster;
-import org.apache.hive.kafka.SingleNodeKafkaCluster;
-import org.apache.hive.kafka.Wikipedia;
-import org.apache.logging.log4j.util.Strings;
-import org.apache.tools.ant.BuildException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.ZooKeeper;
import org.junit.Assert;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
-import com.google.common.collect.ImmutableList;
/**
* QTestUtil.
*/
public class QTestUtil {
-
private static final Logger LOG = LoggerFactory.getLogger("QTestUtil");
- private static final String UTF_8 = "UTF-8";
-
- // security property names
- private static final String SECURITY_KEY_PROVIDER_URI_NAME = "dfs.encryption.key.provider.uri";
- private static final String CRLF = System.getProperty("line.separator");
public static final String QTEST_LEAVE_FILES = "QTEST_LEAVE_FILES";
- private final static String defaultInitScript = "q_test_init.sql";
- private final static String defaultCleanupScript = "q_test_cleanup.sql";
- private static SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
private final String[] testOnlyCommands = new String[]{ "crypto", "erasure" };
-
- public static final String TEST_TMP_DIR_PROPERTY = "test.tmp.dir"; // typically target/tmp
- private static final String BUILD_DIR_PROPERTY = "build.dir"; // typically target
- private static final String TEST_SRC_TABLES_PROPERTY = "test.src.tables";
-
- /**
- * The default Erasure Coding Policy to use in Erasure Coding tests.
- */
- public static final String DEFAULT_TEST_EC_POLICY = "RS-3-2-1024k";
+ public static String DEBUG_HINT =
+ "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
+ + "or check ./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
private String testWarehouse;
@Deprecated private final String testFiles;
- private final File datasetDir;
private final String outDir;
protected final String logDir;
- private final TreeMap<String, String> qMap;
- private final Set<String> qSortSet;
- private final Set<String> qSortQuerySet;
- private final Set<String> qHashQuerySet;
- private final Set<String> qSortNHashQuerySet;
- private final Set<String> qNoSessionReuseQuerySet;
- private static final String SORT_SUFFIX = ".sorted";
- private static Set<String> srcTables;
+ private final TreeMap<String, String> qMap = new TreeMap<String, String>();
private final Set<String> srcUDFs;
- private final MiniClusterType clusterType;
private final FsType fsType;
private ParseDriver pd;
protected Hive db;
- private QueryState queryState;
protected HiveConf conf;
protected HiveConf savedConf;
private IDriver drv;
private BaseSemanticAnalyzer sem;
- private final boolean overWrite;
private CliDriver cliDriver;
- private HadoopShims.MiniMrShim mr = null;
- private HadoopShims.MiniDFSShim dfs = null;
- private FileSystem fs;
- private HadoopShims.HdfsEncryptionShim hes = null;
- private MiniLlapCluster llapCluster = null;
- private final QTestSetup setup;
- private SparkSession sparkSession = null;
- private boolean isSessionStateStarted = false;
- private QOutProcessor qOutProcessor;
+ private final QTestMiniClusters miniClusters = new QTestMiniClusters();
+ private final QOutProcessor qOutProcessor;
+ private static QTestResultProcessor qTestResultProcessor = new QTestResultProcessor();
+ protected QTestDatasetHandler datasetHandler;
private final String initScript;
private final String cleanupScript;
- private MiniDruidCluster druidCluster;
- private SingleNodeKafkaCluster kafkaCluster;
-
- public static Set<String> getSrcTables() {
- if (srcTables == null) {
- initSrcTables();
- }
- return srcTables;
- }
-
- public static void addSrcTable(String table) {
- getSrcTables().add(table);
- storeSrcTables();
- }
-
- public static Set<String> initSrcTables() {
- if (srcTables == null) {
- initSrcTablesFromSystemProperty();
- storeSrcTables();
- }
-
- return srcTables;
- }
-
- private static void storeSrcTables() {
- System.setProperty(TEST_SRC_TABLES_PROPERTY, String.join(",", srcTables));
- }
-
- private static void initSrcTablesFromSystemProperty() {
- srcTables = new HashSet<String>();
- // FIXME: moved default value to here...for now
- // i think this features is never really used from the command line
- for (String srcTable : System.getProperty(TEST_SRC_TABLES_PROPERTY, "").trim().split(",")) {
- srcTable = srcTable.trim();
- if (!srcTable.isEmpty()) {
- srcTables.add(srcTable);
- }
- }
- }
+ private boolean isSessionStateStarted = false;
- private CliDriver getCliDriver() {
+ protected CliDriver getCliDriver() {
if (cliDriver == null) {
throw new RuntimeException("no clidriver");
}
@@ -256,7 +135,7 @@ public class QTestUtil {
// FIXME: moved default value to here...for now
// i think this features is never really used from the command line
String defaultTestSrcUDFs = "qtest_get_java_boolean";
- for (String srcUDF : System.getProperty("test.src.udfs", defaultTestSrcUDFs).trim().split(",")) {
+ for (String srcUDF : QTestSystemProperties.getSourceUdfs(defaultTestSrcUDFs)) {
srcUDF = srcUDF.trim();
if (!srcUDF.isEmpty()) {
srcUDFs.add(srcUDF);
@@ -273,181 +152,14 @@ public class QTestUtil {
}
public void initConf() throws Exception {
-
- String vectorizationEnabled = System.getProperty("test.vectorization.enabled");
- if (vectorizationEnabled != null && vectorizationEnabled.equalsIgnoreCase("true")) {
+ if (QTestSystemProperties.isVectorizationEnabled()) {
conf.setBoolVar(ConfVars.HIVE_VECTORIZATION_ENABLED, true);
}
// Plug verifying metastore in for testing DirectSQL.
conf.setVar(ConfVars.METASTORE_RAW_STORE_IMPL, "org.apache.hadoop.hive.metastore.VerifyingObjectStore");
- if (mr != null) {
- mr.setupConfiguration(conf);
-
- // TODO Ideally this should be done independent of whether mr is setup or not.
- setFsRelatedProperties(conf, fs.getScheme().equals("file"), fs);
- }
-
- if (llapCluster != null) {
- Configuration clusterSpecificConf = llapCluster.getClusterSpecificConfiguration();
- for (Map.Entry<String, String> confEntry : clusterSpecificConf) {
- // Conf.get takes care of parameter replacement, iterator.value does not.
- conf.set(confEntry.getKey(), clusterSpecificConf.get(confEntry.getKey()));
- }
- }
- if (druidCluster != null) {
- final Path druidDeepStorage = fs.makeQualified(new Path(druidCluster.getDeepStorageDir()));
- fs.mkdirs(druidDeepStorage);
- conf.set("hive.druid.storage.storageDirectory", druidDeepStorage.toUri().getPath());
- conf.set("hive.druid.metadata.db.type", "derby");
- conf.set("hive.druid.metadata.uri", druidCluster.getMetadataURI());
- conf.set("hive.druid.coordinator.address.default", druidCluster.getCoordinatorURI());
- conf.set("hive.druid.overlord.address.default", druidCluster.getOverlordURI());
- conf.set("hive.druid.broker.address.default", druidCluster.getBrokerURI());
- final Path scratchDir = fs.makeQualified(new Path(System.getProperty("test.tmp.dir"), "druidStagingDir"));
- fs.mkdirs(scratchDir);
- conf.set("hive.druid.working.directory", scratchDir.toUri().getPath());
- }
- }
-
- private void setFsRelatedProperties(HiveConf conf, boolean isLocalFs, FileSystem fs) {
- String fsUriString = fs.getUri().toString();
-
- // Different paths if running locally vs a remote fileSystem. Ideally this difference should not exist.
- Path warehousePath;
- Path jarPath;
- Path userInstallPath;
- if (isLocalFs) {
- String buildDir = System.getProperty(BUILD_DIR_PROPERTY);
- Preconditions.checkState(Strings.isNotBlank(buildDir));
- Path path = new Path(fsUriString, buildDir);
-
- // Create a fake fs root for local fs
- Path localFsRoot = new Path(path, "localfs");
- warehousePath = new Path(localFsRoot, "warehouse");
- jarPath = new Path(localFsRoot, "jar");
- userInstallPath = new Path(localFsRoot, "user_install");
- } else {
- // TODO Why is this changed from the default in hive-conf?
- warehousePath = new Path(fsUriString, "/build/ql/test/data/warehouse/");
- jarPath = new Path(new Path(fsUriString, "/user"), "hive");
- userInstallPath = new Path(fsUriString, "/user");
- }
-
- warehousePath = fs.makeQualified(warehousePath);
- jarPath = fs.makeQualified(jarPath);
- userInstallPath = fs.makeQualified(userInstallPath);
-
- conf.set(CommonConfigurationKeysPublic.FS_DEFAULT_NAME_KEY, fsUriString);
-
- // Remote dirs
- conf.setVar(ConfVars.METASTOREWAREHOUSE, warehousePath.toString());
- conf.setVar(ConfVars.HIVE_JAR_DIRECTORY, jarPath.toString());
- conf.setVar(ConfVars.HIVE_USER_INSTALL_DIR, userInstallPath.toString());
- // ConfVars.SCRATCHDIR - {test.tmp.dir}/scratchdir
-
- // Local dirs
- // ConfVars.LOCALSCRATCHDIR - {test.tmp.dir}/localscratchdir
-
- // TODO Make sure to cleanup created dirs.
- }
-
- private void createRemoteDirs() {
- assert fs != null;
- Path warehousePath = fs.makeQualified(new Path(conf.getVar(ConfVars.METASTOREWAREHOUSE)));
- assert warehousePath != null;
- Path hiveJarPath = fs.makeQualified(new Path(conf.getVar(ConfVars.HIVE_JAR_DIRECTORY)));
- assert hiveJarPath != null;
- Path userInstallPath = fs.makeQualified(new Path(conf.getVar(ConfVars.HIVE_USER_INSTALL_DIR)));
- assert userInstallPath != null;
- try {
- fs.mkdirs(warehousePath);
- } catch (IOException e) {
- LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath, e.getMessage());
- }
- try {
- fs.mkdirs(hiveJarPath);
- } catch (IOException e) {
- LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath, e.getMessage());
- }
- try {
- fs.mkdirs(userInstallPath);
- } catch (IOException e) {
- LOG.error("Failed to create path={}. Continuing. Exception message={}", warehousePath, e.getMessage());
- }
- }
-
- private enum CoreClusterType {
- MR, TEZ, SPARK
- }
-
- public enum FsType {
- local, hdfs, encrypted_hdfs, erasure_coded_hdfs,
- }
-
- public enum MiniClusterType {
-
- mr(CoreClusterType.MR, FsType.hdfs), tez(CoreClusterType.TEZ, FsType.hdfs), tez_local(CoreClusterType.TEZ,
- FsType.local), spark(CoreClusterType.SPARK, FsType.local), miniSparkOnYarn(CoreClusterType.SPARK,
- FsType.hdfs), llap(CoreClusterType.TEZ, FsType.hdfs), llap_local(CoreClusterType.TEZ, FsType.local), none(
- CoreClusterType.MR,
- FsType.local), druidLocal(CoreClusterType.TEZ, FsType.local), druid(CoreClusterType.TEZ,
- FsType.hdfs), druidKafka(CoreClusterType.TEZ, FsType.hdfs), kafka(CoreClusterType.TEZ, FsType.hdfs);
-
- private final CoreClusterType coreClusterType;
- private final FsType defaultFsType;
-
- MiniClusterType(CoreClusterType coreClusterType, FsType defaultFsType) {
- this.coreClusterType = coreClusterType;
- this.defaultFsType = defaultFsType;
- }
-
- public CoreClusterType getCoreClusterType() {
- return coreClusterType;
- }
-
- public FsType getDefaultFsType() {
- return defaultFsType;
- }
-
- public static MiniClusterType valueForString(String type) {
- // Replace this with valueOf.
- if (type.equals("miniMR")) {
- return mr;
- } else if (type.equals("tez")) {
- return tez;
- } else if (type.equals("tez_local")) {
- return tez_local;
- } else if (type.equals("spark")) {
- return spark;
- } else if (type.equals("miniSparkOnYarn")) {
- return miniSparkOnYarn;
- } else if (type.equals("llap")) {
- return llap;
- } else if (type.equals("llap_local")) {
- return llap_local;
- } else if (type.equals("druidLocal")) {
- return druidLocal;
- } else if (type.equals("druid")) {
- return druid;
- } else if (type.equals("druid-kafka")) {
- return druidKafka;
- } else if (type.equals("kafka")) {
- return kafka;
- } else {
- return none;
- }
- }
- }
-
- private String getKeyProviderURI() {
- // Use the target directory if it is not specified
- String HIVE_ROOT = AbstractCliConfig.HIVE_ROOT;
- String keyDir = HIVE_ROOT + "ql/target/";
-
- // put the jks file in the current test path only for test purpose
- return "jceks://file" + new Path(keyDir, "test.jks").toUri();
+ miniClusters.initConf(conf);
}
public QTestUtil(QTestArguments testArgs) throws Exception {
@@ -479,60 +191,27 @@ public class QTestUtil {
System.out.println("Setting hive-site: " + HiveConf.getHiveSiteLocation());
}
- queryState = new QueryState.Builder().withHiveConf(new HiveConf(IDriver.class)).build();
+ QueryState queryState = new QueryState.Builder().withHiveConf(new HiveConf(IDriver.class)).build();
conf = queryState.getConf();
- qMap = new TreeMap<String, String>();
- qSortSet = new HashSet<String>();
- qSortQuerySet = new HashSet<String>();
- qHashQuerySet = new HashSet<String>();
- qSortNHashQuerySet = new HashSet<String>();
- qNoSessionReuseQuerySet = new HashSet<String>();
- this.clusterType = testArgs.getClusterType();
-
- HadoopShims shims = ShimLoader.getHadoopShims();
- setupFileSystem(shims);
-
- setup = testArgs.getQTestSetup();
- setup.preTest(conf);
+ sem = new SemanticAnalyzer(queryState);
- setupMiniCluster(shims, testArgs.getConfDir());
+ this.miniClusters.setup(testArgs, conf, getScriptsDir(), logDir);
initConf();
- if (testArgs.isWithLlapIo() && (clusterType == MiniClusterType.none)) {
- LOG.info("initializing llap IO");
- LlapProxy.initializeLlapIo(conf);
- }
-
- // Use the current directory if it is not specified
- String dataDir = conf.get("test.data.files");
- if (dataDir == null) {
- dataDir = new File(".").getAbsolutePath() + "/data/files";
- }
- testFiles = dataDir;
- conf.set("test.data.dir", dataDir);
-
- // Use path relative to dataDir directory if it is not specified
- datasetDir =
- conf.get("test.data.set.files") == null ?
- new File(new File(dataDir).getAbsolutePath() + "/datasets") :
- new File(conf.get("test.data.set.files"));
+ datasetHandler = new QTestDatasetHandler(this, conf);
+ testFiles = datasetHandler.getDataDir(conf);
+ conf.set("test.data.dir", datasetHandler.getDataDir(conf));
String scriptsDir = getScriptsDir();
this.initScript = scriptsDir + File.separator + testArgs.getInitScript();
this.cleanupScript = scriptsDir + File.separator + testArgs.getCleanupScript();
- overWrite = shouldOverwriteResults();
-
- init();
+ postInit();
savedConf = new HiveConf(conf);
}
- private boolean shouldOverwriteResults() {
- return "true".equalsIgnoreCase(System.getProperty("test.output.overwrite"));
- }
-
private String getScriptsDir() {
// Use the current directory if it is not specified
String scriptsDir = conf.get("test.data.scripts");
@@ -542,277 +221,45 @@ public class QTestUtil {
return scriptsDir;
}
- private void setupFileSystem(HadoopShims shims) throws IOException {
-
- if (fsType == FsType.local) {
- fs = FileSystem.getLocal(conf);
- } else if (fsType == FsType.hdfs || fsType == FsType.encrypted_hdfs || fsType == FsType.erasure_coded_hdfs) {
- int numDataNodes = 4;
-
- // Setup before getting dfs
- switch (fsType) {
- case encrypted_hdfs:
- // Set the security key provider so that the MiniDFS cluster is initialized
- // with encryption
- conf.set(SECURITY_KEY_PROVIDER_URI_NAME, getKeyProviderURI());
- conf.setInt("fs.trash.interval", 50);
- break;
- case erasure_coded_hdfs:
- // We need more NameNodes for EC.
- // To fully exercise hdfs code paths we need 5 NameNodes for the RS-3-2-1024k policy.
- // With 6 NameNodes we can also run the RS-6-3-1024k policy.
- numDataNodes = 6;
- break;
- default:
- break;
- }
-
- dfs = shims.getMiniDfs(conf, numDataNodes, true, null);
- fs = dfs.getFileSystem();
-
- // Setup after getting dfs
- switch (fsType) {
- case encrypted_hdfs:
- // set up the java key provider for encrypted hdfs cluster
- hes = shims.createHdfsEncryptionShim(fs, conf);
- LOG.info("key provider is initialized");
- break;
- case erasure_coded_hdfs:
- // The Erasure policy can't be set in a q_test_init script as QTestUtil runs that code in
- // a mode that disallows test-only CommandProcessors.
- // Set the default policy on the root of the file system here.
- HdfsErasureCodingShim erasureCodingShim = shims.createHdfsErasureCodingShim(fs, conf);
- erasureCodingShim.enableErasureCodingPolicy(DEFAULT_TEST_EC_POLICY);
- erasureCodingShim.setErasureCodingPolicy(new Path("hdfs:///"), DEFAULT_TEST_EC_POLICY);
- break;
- default:
- break;
- }
- } else {
- throw new IllegalArgumentException("Unknown or unhandled fsType [" + fsType + "]");
- }
- }
-
- private void setupMiniCluster(HadoopShims shims, String confDir) throws IOException {
-
- String uriString = fs.getUri().toString();
-
- if (clusterType == MiniClusterType.druidKafka
- || clusterType == MiniClusterType.druidLocal
- || clusterType == MiniClusterType.druid) {
- final String tempDir = System.getProperty("test.tmp.dir");
- druidCluster =
- new MiniDruidCluster(clusterType == MiniClusterType.druid ? "mini-druid" : "mini-druid-kafka",
- logDir,
- tempDir,
- setup.zkPort,
- Utilities.jarFinderGetJar(MiniDruidCluster.class));
- final Path druidDeepStorage = fs.makeQualified(new Path(druidCluster.getDeepStorageDir()));
- fs.mkdirs(druidDeepStorage);
- final Path scratchDir = fs.makeQualified(new Path(System.getProperty("test.tmp.dir"), "druidStagingDir"));
- fs.mkdirs(scratchDir);
- conf.set("hive.druid.working.directory", scratchDir.toUri().getPath());
- druidCluster.init(conf);
- druidCluster.start();
- }
-
- if (clusterType == MiniClusterType.kafka || clusterType == MiniClusterType.druidKafka) {
- kafkaCluster =
- new SingleNodeKafkaCluster("kafka",
- System.getProperty("test.tmp.dir") + "/kafka-cluster",
- setup.zkPort,
- clusterType == MiniClusterType.kafka ? 9093 : 9092);
- kafkaCluster.init(conf);
- kafkaCluster.start();
- kafkaCluster.createTopicWithData("test-topic", new File(getScriptsDir(), "kafka_init_data.json"));
- kafkaCluster.createTopicWithData("wiki_kafka_csv", new File(getScriptsDir(), "kafka_init_data.csv"));
- kafkaCluster.createTopicWithData("wiki_kafka_avro_table", getAvroRows());
- }
-
- if (clusterType.getCoreClusterType() == CoreClusterType.TEZ) {
- if (confDir != null && !confDir.isEmpty()) {
- conf.addResource(new URL("file://" + new File(confDir).toURI().getPath() + "/tez-site.xml"));
- }
- int numTrackers = 2;
- if (EnumSet.of(MiniClusterType.llap,
- MiniClusterType.llap_local,
- MiniClusterType.druidLocal,
- MiniClusterType.druidKafka,
- MiniClusterType.druid,
- MiniClusterType.kafka).contains(clusterType)) {
- llapCluster = LlapItUtils.startAndGetMiniLlapCluster(conf, setup.zooKeeperCluster, confDir);
- }
- if (EnumSet.of(MiniClusterType.llap_local, MiniClusterType.tez_local, MiniClusterType.druidLocal)
- .contains(clusterType)) {
- mr =
- shims.getLocalMiniTezCluster(conf,
- clusterType == MiniClusterType.llap_local || clusterType == MiniClusterType.druidLocal);
- } else {
- mr =
- shims.getMiniTezCluster(conf,
- numTrackers,
- uriString,
- EnumSet.of(MiniClusterType.llap,
- MiniClusterType.llap_local,
- MiniClusterType.druidKafka,
- MiniClusterType.druid,
- MiniClusterType.kafka).contains(clusterType));
- }
- } else if (clusterType == MiniClusterType.miniSparkOnYarn) {
- mr = shims.getMiniSparkCluster(conf, 2, uriString, 1);
- } else if (clusterType == MiniClusterType.mr) {
- mr = shims.getMiniMrCluster(conf, 2, uriString, 1);
- }
- }
-
- private static List<byte[]> getAvroRows() {
- int numRows = 10;
- List<byte[]> events;
- final DatumWriter<GenericRecord> writer = new SpecificDatumWriter<>(Wikipedia.getClassSchema());
- events = IntStream.rangeClosed(0, numRows).mapToObj(i -> Wikipedia.newBuilder()
- // 1534736225090 -> 08/19/2018 20:37:05
- .setTimestamp(formatter.format(new Timestamp(1534736225090L + 1000 * 3600 * i)))
- .setAdded(i * 300)
- .setDeleted(-i)
- .setIsrobot(i % 2 == 0)
- .setChannel("chanel number " + i)
- .setComment("comment number " + i)
- .setCommentlength(i)
- .setDiffurl(String.format("url %s", i))
- .setFlags("flag")
- .setIsminor(i % 2 > 0)
- .setIsanonymous(i % 3 != 0)
- .setNamespace("namespace")
- .setIsunpatrolled(new Boolean(i % 3 == 0))
- .setIsnew(new Boolean(i % 2 > 0))
- .setPage(String.format("page is %s", i * 100))
- .setDelta(i)
- .setDeltabucket(i * 100.4)
- .setUser("test-user-" + i)
- .build()).map(genericRecord -> {
- java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
- BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(out, null);
- try {
- writer.write(genericRecord, encoder);
- encoder.flush();
- out.close();
- } catch (IOException e) {
- throw new RuntimeException(e);
- }
- return out.toByteArray();
- }).collect(Collectors.toList());
- return events;
- }
-
public void shutdown() throws Exception {
if (System.getenv(QTEST_LEAVE_FILES) == null) {
cleanUp();
}
- if (clusterType.getCoreClusterType() == CoreClusterType.TEZ && SessionState.get().getTezSession() != null) {
- SessionState.get().getTezSession().destroy();
- }
- if (druidCluster != null) {
- druidCluster.stop();
- druidCluster = null;
- }
+ miniClusters.shutDown();
- if (kafkaCluster != null) {
- kafkaCluster.stop();
- kafkaCluster = null;
- }
- setup.tearDown();
- if (sparkSession != null) {
- try {
- SparkSessionManagerImpl.getInstance().closeSession(sparkSession);
- } catch (Exception ex) {
- LOG.error("Error closing spark session.", ex);
- } finally {
- sparkSession = null;
- }
- }
- if (mr != null) {
- mr.shutdown();
- mr = null;
- }
- FileSystem.closeAll();
- if (dfs != null) {
- dfs.shutdown();
- dfs = null;
- }
Hive.closeCurrent();
}
- public String readEntireFileIntoString(File queryFile) throws IOException {
- InputStreamReader
- isr =
- new InputStreamReader(new BufferedInputStream(new FileInputStream(queryFile)), QTestUtil.UTF_8);
- StringWriter sw = new StringWriter();
- try {
- IOUtils.copy(isr, sw);
- } finally {
- if (isr != null) {
- isr.close();
- }
- }
- return sw.toString();
- }
-
public void addFile(String queryFile) throws IOException {
addFile(new File(queryFile), false);
}
public void addFile(File qf, boolean partial) throws IOException {
- String query = readEntireFileIntoString(qf);
+ String query = FileUtils.readFileToString(qf);
qMap.put(qf.getName(), query);
if (partial) {
return;
}
- if (matches(SORT_BEFORE_DIFF, query)) {
- qSortSet.add(qf.getName());
- } else if (matches(SORT_QUERY_RESULTS, query)) {
- qSortQuerySet.add(qf.getName());
- } else if (matches(HASH_QUERY_RESULTS, query)) {
- qHashQuerySet.add(qf.getName());
- } else if (matches(SORT_AND_HASH_QUERY_RESULTS, query)) {
- qSortNHashQuerySet.add(qf.getName());
- }
- if (matches(NO_SESSION_REUSE, query)) {
- qNoSessionReuseQuerySet.add(qf.getName());
- }
-
+ qTestResultProcessor.add(qf, query);
qOutProcessor.initMasks(qf, query);
}
- private static final Pattern SORT_BEFORE_DIFF = Pattern.compile("-- SORT_BEFORE_DIFF");
- private static final Pattern SORT_QUERY_RESULTS = Pattern.compile("-- SORT_QUERY_RESULTS");
- private static final Pattern HASH_QUERY_RESULTS = Pattern.compile("-- HASH_QUERY_RESULTS");
- private static final Pattern SORT_AND_HASH_QUERY_RESULTS = Pattern.compile("-- SORT_AND_HASH_QUERY_RESULTS");
- private static final Pattern NO_SESSION_REUSE = Pattern.compile("-- NO_SESSION_REUSE");
-
- private boolean matches(Pattern pattern, String query) {
- Matcher matcher = pattern.matcher(query);
- if (matcher.find()) {
- return true;
- }
- return false;
- }
-
/**
* Clear out any side effects of running tests
*/
public void clearPostTestEffects() throws Exception {
- setup.postTest(conf);
+ miniClusters.postTest(conf);
}
public void clearKeysCreatedInTests() {
- if (hes == null) {
+ if (miniClusters.getHdfsEncryptionShim() == null) {
return;
}
try {
- for (String keyAlias : hes.getKeys()) {
- hes.deleteKey(keyAlias);
+ for (String keyAlias : miniClusters.getHdfsEncryptionShim().getKeys()) {
+ miniClusters.getHdfsEncryptionShim().deleteKey(keyAlias);
}
} catch (IOException e) {
LOG.error("Fail to clean the keys created in test due to the error", e);
@@ -858,7 +305,7 @@ public class QTestUtil {
if (!tblObj.isMaterializedView()) {
continue;
}
- db.dropTable(dbName, tblName, true, true, fsType == FsType.encrypted_hdfs);
+ db.dropTable(dbName, tblName, true, true, fsType == FsType.ENCRYPTED_HDFS);
}
}
@@ -867,15 +314,14 @@ public class QTestUtil {
for (String dbName : db.getAllDatabases()) {
SessionState.get().setCurrentDatabase(dbName);
for (String tblName : db.getAllTables()) {
- if (!DEFAULT_DATABASE_NAME.equals(dbName) || !getSrcTables().contains(tblName)) {
- Table tblObj = null;
+ if (!DEFAULT_DATABASE_NAME.equals(dbName) || !QTestDatasetHandler.isSourceTable(tblName)) {
try {
- tblObj = db.getTable(tblName);
+ db.getTable(tblName);
} catch (InvalidTableException e) {
LOG.warn("Trying to drop table " + e.getTableName() + ". But it does not exist.");
continue;
}
- db.dropTable(dbName, tblName, true, true, fsNeedsPurge(fsType));
+ db.dropTable(dbName, tblName, true, true, miniClusters.fsNeedsPurge(fsType));
}
}
if (!DEFAULT_DATABASE_NAME.equals(dbName)) {
@@ -890,7 +336,7 @@ public class QTestUtil {
FileSystem fileSystem = p.getFileSystem(conf);
if (fileSystem.exists(p)) {
for (FileStatus status : fileSystem.listStatus(p)) {
- if (status.isDirectory() && !getSrcTables().contains(status.getPath().getName())) {
+ if (status.isDirectory() && !QTestDatasetHandler.isSourceTable(status.getPath().getName())) {
fileSystem.delete(status.getPath(), true);
}
}
@@ -929,7 +375,7 @@ public class QTestUtil {
ss.in = System.in;
SessionState oldSs = SessionState.get();
- restartSessions(canReuseSession, ss, oldSs);
+ miniClusters.restartSessions(canReuseSession, ss, oldSs);
closeSession(oldSs);
SessionState.start(ss);
@@ -964,7 +410,7 @@ public class QTestUtil {
}
protected void initConfFromSetup() throws Exception {
- setup.preTest(conf);
+ miniClusters.preTest(conf);
}
public void cleanUp() throws Exception {
@@ -972,7 +418,7 @@ public class QTestUtil {
}
public void cleanUp(String fileName) throws Exception {
- boolean canReuseSession = (fileName == null) || !qNoSessionReuseQuerySet.contains(fileName);
+ boolean canReuseSession = (fileName == null) || !qTestResultProcessor.shouldNotReuseSession(fileName);
if (!isSessionStateStarted) {
startSessionState(canReuseSession);
}
@@ -1009,7 +455,7 @@ public class QTestUtil {
private void cleanupFromFile() throws IOException {
File cleanupFile = new File(cleanupScript);
if (cleanupFile.isFile()) {
- String cleanupCommands = readEntireFileIntoString(cleanupFile);
+ String cleanupCommands = FileUtils.readFileToString(cleanupFile);
LOG.info("Cleanup (" + cleanupScript + "):\n" + cleanupCommands);
int result = getCliDriver().processLine(cleanupCommands).getResponseCode();
@@ -1027,7 +473,7 @@ public class QTestUtil {
}
public void createSources(String fileName) throws Exception {
- boolean canReuseSession = (fileName == null) || !qNoSessionReuseQuerySet.contains(fileName);
+ boolean canReuseSession = (fileName == null) || !qTestResultProcessor.shouldNotReuseSession(fileName);
if (!isSessionStateStarted) {
startSessionState(canReuseSession);
}
@@ -1048,7 +494,7 @@ public class QTestUtil {
return;
}
- String initCommands = readEntireFileIntoString(scriptFile);
+ String initCommands = FileUtils.readFileToString(scriptFile);
LOG.info("Initial setup (" + initScript + "):\n" + initCommands);
int result = cliDriver.processLine(initCommands).getResponseCode();
@@ -1058,66 +504,32 @@ public class QTestUtil {
}
}
- private void initDataSetForTest(File file) throws Exception {
- synchronized (QTestUtil.class) {
- DatasetParser parser = new DatasetParser();
- parser.parse(file);
-
- DatasetCollection datasets = parser.getDatasets();
-
- Set<String> missingDatasets = datasets.getTables();
- missingDatasets.removeAll(getSrcTables());
- if (missingDatasets.isEmpty()) {
- return;
- }
- newSession(true);
- for (String table : missingDatasets) {
- initDataset(table);
- }
- newSession(true);
- }
- }
-
- protected void initDataset(String table) throws Exception {
+ private void postInit() throws Exception {
+ miniClusters.postInit(conf);
- File tableFile = new File(new File(datasetDir, table), Dataset.INIT_FILE_NAME);
- String commands = null;
- try {
- commands = readEntireFileIntoString(tableFile);
- } catch (IOException e) {
- throw new RuntimeException(String.format("dataset file not found %s", tableFile), e);
- }
+ testWarehouse = conf.getVar(HiveConf.ConfVars.METASTOREWAREHOUSE);
- int result = getCliDriver().processLine(commands).getResponseCode();
- LOG.info("Result from cliDrriver.processLine in initFromDatasets=" + result);
- if (result != 0) {
- Assert.fail("Failed during initFromDatasets processLine with code=" + result);
- }
+ db = Hive.get(conf);
+ drv = DriverFactory.newDriver(conf);
+ pd = new ParseDriver();
- addSrcTable(table);
+ initMaterializedViews(); // Create views registry
+ firstStartSessionState();
}
- public void init() throws Exception {
-
- // Create remote dirs once.
- if (mr != null) {
- createRemoteDirs();
- }
+ private void initMaterializedViews() {
+ String registryImpl = db.getConf().get("hive.server2.materializedviews.registry.impl");
+ db.getConf().set("hive.server2.materializedviews.registry.impl", "DUMMY");
+ HiveMaterializedViewsRegistry.get().init(db);
+ db.getConf().set("hive.server2.materializedviews.registry.impl", registryImpl);
+ }
- testWarehouse = conf.getVar(HiveConf.ConfVars.METASTOREWAREHOUSE);
+ //FIXME: check why mr is needed for starting a session state from conf
+ private void firstStartSessionState() {
String execEngine = conf.get("hive.execution.engine");
conf.set("hive.execution.engine", "mr");
SessionState.start(conf);
conf.set("hive.execution.engine", execEngine);
- db = Hive.get(conf);
- // Create views registry
- String registryImpl = db.getConf().get("hive.server2.materializedviews.registry.impl");
- db.getConf().set("hive.server2.materializedviews.registry.impl", "DUMMY");
- HiveMaterializedViewsRegistry.get().init(db);
- db.getConf().set("hive.server2.materializedviews.registry.impl", registryImpl);
- drv = DriverFactory.newDriver(conf);
- pd = new ParseDriver();
- sem = new SemanticAnalyzer(queryState);
}
public void init(String fileName) throws Exception {
@@ -1129,9 +541,9 @@ public class QTestUtil {
public String cliInit(File file) throws Exception {
String fileName = file.getName();
- initDataSetForTest(file);
+ datasetHandler.initDataSetForTest(file, getCliDriver());
- if (qNoSessionReuseQuerySet.contains(fileName)) {
+ if (qTestResultProcessor.shouldNotReuseSession(fileName)) {
newSession(false);
}
@@ -1166,42 +578,20 @@ public class QTestUtil {
if (ss.err != null) {
ss.out.flush();
}
- if (qSortQuerySet.contains(fileName)) {
- ss.out = new SortPrintStream(fo, "UTF-8");
- } else if (qHashQuerySet.contains(fileName)) {
- ss.out = new DigestPrintStream(fo, "UTF-8");
- } else if (qSortNHashQuerySet.contains(fileName)) {
- ss.out = new SortAndDigestPrintStream(fo, "UTF-8");
- } else {
- ss.out = new SessionStream(fo, true, "UTF-8");
- }
- ss.err = new CachingPrintStream(fo, true, "UTF-8");
- ss.setIsSilent(true);
- }
- private void restartSessions(boolean canReuseSession, CliSessionState ss, SessionState oldSs) throws IOException {
- if (oldSs != null && canReuseSession && clusterType.getCoreClusterType() == CoreClusterType.TEZ) {
- // Copy the tezSessionState from the old CliSessionState.
- TezSessionState tezSessionState = oldSs.getTezSession();
- oldSs.setTezSession(null);
- ss.setTezSession(tezSessionState);
- oldSs.close();
- }
+ qTestResultProcessor.setOutputs(ss, fo, fileName);
- if (oldSs != null && clusterType.getCoreClusterType() == CoreClusterType.SPARK) {
- sparkSession = oldSs.getSparkSession();
- ss.setSparkSession(sparkSession);
- oldSs.setSparkSession(null);
- oldSs.close();
- }
+ ss.err = new CachingPrintStream(fo, true, "UTF-8");
+ ss.setIsSilent(true);
}
- private CliSessionState startSessionState(boolean canReuseSession) throws IOException {
+ public CliSessionState startSessionState(boolean canReuseSession) throws IOException {
HiveConf.setVar(conf,
HiveConf.ConfVars.HIVE_AUTHENTICATOR_MANAGER,
"org.apache.hadoop.hive.ql.security.DummyAuthenticator");
+ //FIXME: check why mr is needed for starting a session state from conf
String execEngine = conf.get("hive.execution.engine");
conf.set("hive.execution.engine", "mr");
@@ -1212,7 +602,7 @@ public class QTestUtil {
SessionState oldSs = SessionState.get();
- restartSessions(canReuseSession, ss, oldSs);
+ miniClusters.restartSessions(canReuseSession, ss, oldSs);
closeSession(oldSs);
SessionState.start(ss);
@@ -1248,7 +638,8 @@ public class QTestUtil {
}
public CommandProcessorResponse executeClient(String tname1, String tname2) {
- String commands = getCommand(tname1) + CRLF + getCommand(tname2);
+ String commands =
+ getCommand(tname1) + System.getProperty("line.separator") + getCommand(tname2);
return executeClientInternal(commands);
}
@@ -1427,9 +818,9 @@ public class QTestUtil {
outfd.write(e.getMessage());
outfd.close();
- QTestProcessExecResult result = executeDiffCommand(outf.getPath(), expf, false, qSortSet.contains(qf.getName()));
- if (overWrite) {
- overwriteResults(outf.getPath(), expf);
+ QTestProcessExecResult result = qTestResultProcessor.executeDiffCommand(outf.getPath(), expf, false, qf.getName());
+ if (QTestSystemProperties.shouldOverwriteResults()) {
+ qTestResultProcessor.overwriteResults(outf.getPath(), expf);
return QTestProcessExecResult.createWithoutOutput(0);
}
@@ -1458,9 +849,9 @@ public class QTestUtil {
+ "\n");
outfd.close();
- QTestProcessExecResult result = executeDiffCommand(outf.getPath(), expf, false, qSortSet.contains(qf.getName()));
- if (overWrite) {
- overwriteResults(outf.getPath(), expf);
+ QTestProcessExecResult result = qTestResultProcessor.executeDiffCommand(outf.getPath(), expf, false, qf.getName());
+ if (QTestSystemProperties.shouldOverwriteResults()) {
+ qTestResultProcessor.overwriteResults(outf.getPath(), expf);
return QTestProcessExecResult.createWithoutOutput(0);
}
@@ -1479,7 +870,7 @@ public class QTestUtil {
String ret = (new File(outDir, testName)).getPath();
// List of configurations. Currently the list consists of hadoop version and execution mode only
List<String> configs = new ArrayList<String>();
- configs.add(this.clusterType.toString());
+ configs.add(miniClusters.getClusterType().getQOutFileExtensionPostfix());
Deque<String> stack = new LinkedList<String>();
StringBuilder sb = new StringBuilder();
@@ -1512,10 +903,10 @@ public class QTestUtil {
File f = new File(logDir, tname + outFileExtension);
qOutProcessor.maskPatterns(f.getPath(), tname);
- QTestProcessExecResult exitVal = executeDiffCommand(f.getPath(), outFileName, false, qSortSet.contains(tname));
+ QTestProcessExecResult exitVal = qTestResultProcessor.executeDiffCommand(f.getPath(), outFileName, false, tname);
- if (overWrite) {
- overwriteResults(f.getPath(), outFileName);
+ if (QTestSystemProperties.shouldOverwriteResults()) {
+ qTestResultProcessor.overwriteResults(f.getPath(), outFileName);
return QTestProcessExecResult.createWithoutOutput(0);
}
@@ -1529,7 +920,7 @@ public class QTestUtil {
qOutProcessor.maskPatterns(outputs.get(i), tname);
QTestProcessExecResult
result =
- executeDiffCommand(outputs.get(i - 1), outputs.get(i), false, qSortSet.contains(tname));
+ qTestResultProcessor.executeDiffCommand(outputs.get(i - 1), outputs.get(i), false, tname);
if (result.getReturnCode() != 0) {
System.out.println("Files don't match: " + outputs.get(i - 1) + " and " + outputs.get(i));
return result;
@@ -1538,135 +929,6 @@ public class QTestUtil {
return QTestProcessExecResult.createWithoutOutput(0);
}
- private static void overwriteResults(String inFileName, String outFileName) throws Exception {
- // This method can be replaced with Files.copy(source, target, REPLACE_EXISTING)
- // once Hive uses JAVA 7.
- System.out.println("Overwriting results " + inFileName + " to " + outFileName);
- int result = executeCmd(new String[]{
- "cp", getQuotedString(inFileName), getQuotedString(outFileName) }).getReturnCode();
- if (result != 0) {
- throw new IllegalStateException("Unexpected error while overwriting " + inFileName + " with " + outFileName);
- }
- }
-
- private static QTestProcessExecResult executeDiffCommand(String inFileName,
- String outFileName,
- boolean ignoreWhiteSpace,
- boolean sortResults) throws Exception {
-
- QTestProcessExecResult result;
-
- if (sortResults) {
- // sort will try to open the output file in write mode on windows. We need to
- // close it first.
- SessionState ss = SessionState.get();
- if (ss != null && ss.out != null && ss.out != System.out) {
- ss.out.close();
- }
-
- String inSorted = inFileName + SORT_SUFFIX;
- String outSorted = outFileName + SORT_SUFFIX;
-
- sortFiles(inFileName, inSorted);
- sortFiles(outFileName, outSorted);
-
- inFileName = inSorted;
- outFileName = outSorted;
- }
-
- ArrayList<String> diffCommandArgs = new ArrayList<String>();
- diffCommandArgs.add("diff");
-
- // Text file comparison
- diffCommandArgs.add("-a");
-
- // Ignore changes in the amount of white space
- if (ignoreWhiteSpace) {
- diffCommandArgs.add("-b");
- }
-
- // Add files to compare to the arguments list
- diffCommandArgs.add(getQuotedString(inFileName));
- diffCommandArgs.add(getQuotedString(outFileName));
-
- result = executeCmd(diffCommandArgs);
-
- if (sortResults) {
- new File(inFileName).delete();
- new File(outFileName).delete();
- }
-
- return result;
- }
-
- private static void sortFiles(String in, String out) throws Exception {
- int result = executeCmd(new String[]{
- "sort", getQuotedString(in), }, out, null).getReturnCode();
- if (result != 0) {
- throw new IllegalStateException("Unexpected error while sorting " + in);
- }
- }
-
- private static QTestProcessExecResult executeCmd(Collection<String> args) throws Exception {
- return executeCmd(args, null, null);
- }
-
- private static QTestProcessExecResult executeCmd(String[] args) throws Exception {
- return executeCmd(args, null, null);
- }
-
- private static QTestProcessExecResult executeCmd(Collection<String> args, String outFile, String errFile)
- throws Exception {
- String[] cmdArray = args.toArray(new String[args.size()]);
- return executeCmd(cmdArray, outFile, errFile);
- }
-
- private static QTestProcessExecResult executeCmd(String[] args, String outFile, String errFile) throws Exception {
- System.out.println("Running: " + org.apache.commons.lang.StringUtils.join(args, ' '));
-
- PrintStream
- out =
- outFile == null ?
- SessionState.getConsole().getChildOutStream() :
- new PrintStream(new FileOutputStream(outFile), true, "UTF-8");
- PrintStream
- err =
- errFile == null ?
- SessionState.getConsole().getChildErrStream() :
- new PrintStream(new FileOutputStream(errFile), true, "UTF-8");
-
- Process executor = Runtime.getRuntime().exec(args);
-
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- PrintStream str = new PrintStream(bos, true, "UTF-8");
-
- StreamPrinter errPrinter = new StreamPrinter(executor.getErrorStream(), null, err);
- StreamPrinter outPrinter = new StreamPrinter(executor.getInputStream(), null, out, str);
-
- outPrinter.start();
- errPrinter.start();
-
- int result = executor.waitFor();
-
- outPrinter.join();
- errPrinter.join();
-
- if (outFile != null) {
- out.close();
- }
-
- if (errFile != null) {
- err.close();
- }
-
- return QTestProcessExecResult.
- create(result, new String(bos.toByteArray(), StandardCharsets.UTF_8));
- }
-
- private static String getQuotedString(String str) {
- return str;
- }
-
public ASTNode parseQuery(String tname) throws Exception {
return pd.parse(qMap.get(tname));
}
@@ -1685,278 +947,19 @@ public class QTestUtil {
return sem.getRootTasks();
}
- /**
- * QTestSetup defines test fixtures which are reused across testcases,
- * and are needed before any test can be run
- */
- public static class QTestSetup {
- private MiniZooKeeperCluster zooKeeperCluster = null;
- private int zkPort;
- private ZooKeeper zooKeeper;
-
- public QTestSetup() {
- }
-
- public void preTest(HiveConf conf) throws Exception {
-
- if (zooKeeperCluster == null) {
- //create temp dir
- String tmpBaseDir = System.getProperty(TEST_TMP_DIR_PROPERTY);
- File tmpDir = Files.createTempDirectory(Paths.get(tmpBaseDir), "tmp_").toFile();
-
- zooKeeperCluster = new MiniZooKeeperCluster();
- zkPort = zooKeeperCluster.startup(tmpDir);
- }
-
- if (zooKeeper != null) {
- zooKeeper.close();
- }
-
- int
- sessionTimeout =
- (int) conf.getTimeVar(HiveConf.ConfVars.HIVE_ZOOKEEPER_SESSION_TIMEOUT, TimeUnit.MILLISECONDS);
- zooKeeper = new ZooKeeper("localhost:" + zkPort, sessionTimeout, new Watcher() {
- @Override public void process(WatchedEvent arg0) {
- }
- });
-
- String zkServer = "localhost";
- conf.set("hive.zookeeper.quorum", zkServer);
- conf.set("hive.zookeeper.client.port", "" + zkPort);
- }
-
- public void postTest(HiveConf conf) throws Exception {
- if (zooKeeperCluster == null) {
- return;
- }
-
- if (zooKeeper != null) {
- zooKeeper.close();
- }
-
- ZooKeeperHiveLockManager.releaseAllLocks(conf);
- }
-
- public void tearDown() throws Exception {
- CuratorFrameworkSingleton.closeAndReleaseInstance();
-
- if (zooKeeperCluster != null) {
- zooKeeperCluster.shutdown();
- zooKeeperCluster = null;
- }
- }
- }
-
- /**
- * QTRunner: Runnable class for running a single query file.
- **/
- public static class QTRunner implements Runnable {
- private final QTestUtil qt;
- private final File file;
-
- public QTRunner(QTestUtil qt, File file) {
- this.qt = qt;
- this.file = file;
- }
-
- @Override public void run() {
- try {
- qt.startSessionState(false);
- // assumption is that environment has already been cleaned once globally
- // hence each thread does not call cleanUp() and createSources() again
- qt.cliInit(file);
- qt.executeClient(file.getName());
- } catch (Throwable e) {
- System.err.println("Query file " + file.getName() + " failed with exception " + e.getMessage());
- e.printStackTrace();
- outputTestFailureHelpMessage();
- }
- }
- }
-
- /**
- * Setup to execute a set of query files. Uses QTestUtil to do so.
- *
- * @param qfiles array of input query files containing arbitrary number of hive
- * queries
- * @param resDir output directory
- * @param logDir log directory
- * @return one QTestUtil for each query file
- */
- public static QTestUtil[] queryListRunnerSetup(File[] qfiles,
- String resDir,
- String logDir,
- String initScript,
- String cleanupScript) throws Exception {
- QTestUtil[] qt = new QTestUtil[qfiles.length];
- for (int i = 0; i < qfiles.length; i++) {
-
- qt[i] =
- new QTestUtil(QTestArguments.QTestArgumentsBuilder.instance()
- .withOutDir(resDir)
- .withLogDir(logDir)
- .withClusterType(MiniClusterType.none)
- .withConfDir(null)
- .withInitScript(initScript == null ? defaultInitScript : initScript)
- .withCleanupScript(cleanupScript == null ? defaultCleanupScript : cleanupScript)
- .withLlapIo(false)
- .build());
-
- qt[i].addFile(qfiles[i], false);
- qt[i].clearTestSideEffects();
- }
-
- return qt;
- }
-
- /**
- * Executes a set of query files in sequence.
- *
- * @param qfiles array of input query files containing arbitrary number of hive
- * queries
- * @param qt array of QTestUtils, one per qfile
- * @return true if all queries passed, false otw
- */
- public static boolean queryListRunnerSingleThreaded(File[] qfiles, QTestUtil[] qt) throws Exception {
- boolean failed = false;
- qt[0].cleanUp();
- qt[0].createSources();
- for (int i = 0; i < qfiles.length && !failed; i++) {
- qt[i].clearTestSideEffects();
- qt[i].cliInit(qfiles[i]);
- qt[i].executeClient(qfiles[i].getName());
- QTestProcessExecResult result = qt[i].checkCliDriverResults(qfiles[i].getName());
- if (result.getReturnCode() != 0) {
- failed = true;
- StringBuilder builder = new StringBuilder();
- builder.append("Test ")
- .append(qfiles[i].getName())
- .append(" results check failed with error code ")
- .append(result.getReturnCode());
- if (Strings.isNotEmpty(result.getCapturedOutput())) {
- builder.append(" and diff value ").append(result.getCapturedOutput());
- }
- System.err.println(builder.toString());
- outputTestFailureHelpMessage();
- }
- qt[i].clearPostTestEffects();
- }
- return (!failed);
- }
-
- /**
- * Executes a set of query files parallel.
- * <p>
- * Each query file is run in a separate thread. The caller has to arrange
- * that different query files do not collide (in terms of destination tables)
- *
- * @param qfiles array of input query files containing arbitrary number of hive
- * queries
- * @param qt array of QTestUtils, one per qfile
- * @return true if all queries passed, false otw
- */
- public static boolean queryListRunnerMultiThreaded(File[] qfiles, QTestUtil[] qt) throws Exception {
- boolean failed = false;
-
- // in multithreaded mode - do cleanup/initialization just once
-
- qt[0].cleanUp();
- qt[0].createSources();
- qt[0].clearTestSideEffects();
-
- QTRunner[] qtRunners = new QTRunner[qfiles.length];
- Thread[] qtThread = new Thread[qfiles.length];
-
- for (int i = 0; i < qfiles.length; i++) {
- qtRunners[i] = new QTRunner(qt[i], qfiles[i]);
- qtThread[i] = new Thread(qtRunners[i]);
- }
-
- for (int i = 0; i < qfiles.length; i++) {
- qtThread[i].start();
- }
-
- for (int i = 0; i < qfiles.length; i++) {
- qtThread[i].join();
- QTestProcessExecResult result = qt[i].checkCliDriverResults(qfiles[i].getName());
- if (result.getReturnCode() != 0) {
- failed = true;
- StringBuilder builder = new StringBuilder();
- builder.append("Test ")
- .append(qfiles[i].getName())
- .append(" results check failed with error code ")
- .append(result.getReturnCode());
- if (Strings.isNotEmpty(result.getCapturedOutput())) {
- builder.append(" and diff value ").append(result.getCapturedOutput());
- }
- System.err.println(builder.toString());
- outputTestFailureHelpMessage();
- }
- }
- return (!failed);
- }
-
- public static void outputTestFailureHelpMessage() {
- System.err.println("See ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, or check "
- + "./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific "
- + "test cases logs.");
- System.err.flush();
- }
-
- private static String[] cachedQvFileList = null;
- private static ImmutableList<String> cachedDefaultQvFileList = null;
- private static Pattern qvSuffix = Pattern.compile("_[0-9]+.qv$", Pattern.CASE_INSENSITIVE);
-
- public static List<String> getVersionFiles(String queryDir, String tname) {
- ensureQvFileList(queryDir);
- List<String> result = getVersionFilesInternal(tname);
- if (result == null) {
- result = cachedDefaultQvFileList;
- }
- return result;
- }
-
- private static void ensureQvFileList(String queryDir) {
- if (cachedQvFileList != null) {
- return;
- }
- // Not thread-safe.
- System.out.println("Getting versions from " + queryDir);
- cachedQvFileList = (new File(queryDir)).list(new FilenameFilter() {
- @Override public boolean accept(File dir, String name) {
- return name.toLowerCase().endsWith(".qv");
- }
- });
- if (cachedQvFileList == null) {
- return; // no files at all
- }
- Arrays.sort(cachedQvFileList, String.CASE_INSENSITIVE_ORDER);
- List<String> defaults = getVersionFilesInternal("default");
- cachedDefaultQvFileList = (defaults != null) ? ImmutableList.copyOf(defaults) : ImmutableList.<String>of();
- }
-
- private static List<String> getVersionFilesInternal(String tname) {
- if (cachedQvFileList == null) {
- return new ArrayList<String>();
- }
- int pos = Arrays.binarySearch(cachedQvFileList, tname, String.CASE_INSENSITIVE_ORDER);
- if (pos >= 0) {
- throw new BuildException("Unexpected file list element: " + cachedQvFileList[pos]);
- }
- List<String> result = null;
- for (pos = (-pos - 1); pos < cachedQvFileList.length; ++pos) {
- String candidate = cachedQvFileList[pos];
- if (candidate.length() <= tname.length()
- || !tname.equalsIgnoreCase(candidate.substring(0, tname.length()))
- || !qvSuffix.matcher(candidate.substring(tname.length())).matches()) {
- break;
- }
- if (result == null) {
- result = new ArrayList<String>();
- }
- result.add(candidate);
- }
- return result;
+ public void failed(int ecode, String fname, String debugHint) {
+ String command = SessionState.get() != null ? SessionState.get().getLastCommand() : null;
+ String
+ message =
+ "Client execution failed with error code = "
+ + ecode
+ + (command != null ? " running \"" + command : "")
+ + "\" fname="
+ + fname
+ + " "
+ + (debugHint != null ? debugHint : "");
+ LOG.error(message);
+ Assert.fail(message);
}
// for negative tests, which is succeeded.. no need to print the query string
@@ -2004,16 +1007,4 @@ public class QTestUtil {
public static void initEventNotificationPoll() throws Exception {
NotificationEventPoll.initialize(SessionState.get().getConf());
}
-
- /**
- * Should deleted test tables have their data purged.
- *
- * @return true if data should be purged
- */
- private static boolean fsNeedsPurge(FsType type) {
- if (type == FsType.encrypted_hdfs || type == FsType.erasure_coded_hdfs) {
- return true;
- }
- return false;
- }
}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/dataset/QTestDatasetHandler.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/dataset/QTestDatasetHandler.java
new file mode 100644
index 0000000..14560e4
--- /dev/null
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/dataset/QTestDatasetHandler.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.dataset;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.hadoop.hive.cli.CliDriver;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.QTestSystemProperties;
+import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
+import org.junit.Assert;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+public class QTestDatasetHandler {
+ private static final Logger LOG = LoggerFactory.getLogger("QTestDatasetHandler");
+
+ private File datasetDir;
+ private QTestUtil qt;
+ private static Set<String> srcTables;
+
+ public QTestDatasetHandler(QTestUtil qTestUtil, HiveConf conf) {
+ // Use path relative to dataDir directory if it is not specified
+ String dataDir = getDataDir(conf);
+
+ datasetDir = conf.get("test.data.set.files") == null ? new File(dataDir + "/datasets")
+ : new File(conf.get("test.data.set.files"));
+ this.qt = qTestUtil;
+ }
+
+ public String getDataDir(HiveConf conf) {
+ String dataDir = conf.get("test.data.files");
+ // Use the current directory if it is not specified
+ if (dataDir == null) {
+ dataDir = new File(".").getAbsolutePath() + "/data/files";
+ }
+
+ return dataDir;
+ }
+
+ public void initDataSetForTest(File file, CliDriver cliDriver) throws Exception {
+ synchronized (QTestUtil.class) {
+ DatasetParser parser = new DatasetParser();
+ parser.parse(file);
+
+ DatasetCollection datasets = parser.getDatasets();
+
+ Set<String> missingDatasets = datasets.getTables();
+ missingDatasets.removeAll(getSrcTables());
+ if (missingDatasets.isEmpty()) {
+ return;
+ }
+ qt.newSession(true);
+ for (String table : missingDatasets) {
+ if (initDataset(table, cliDriver)) {
+ addSrcTable(table);
+ }
+ }
+ qt.newSession(true);
+ }
+ }
+
+ public boolean initDataset(String table, CliDriver cliDriver) throws Exception {
+ File tableFile = new File(new File(datasetDir, table), Dataset.INIT_FILE_NAME);
+ String commands = null;
+ try {
+ commands = FileUtils.readFileToString(tableFile);
+ } catch (IOException e) {
+ throw new RuntimeException(String.format("dataset file not found %s", tableFile), e);
+ }
+
+ CommandProcessorResponse result = cliDriver.processLine(commands);
+ LOG.info("Result from cliDrriver.processLine in initFromDatasets=" + result);
+ if (result.getResponseCode() != 0) {
+ Assert.fail("Failed during initFromDatasets processLine with code=" + result);
+ }
+
+ return true;
+ }
+
+ public static Set<String> getSrcTables() {
+ if (srcTables == null) {
+ initSrcTables();
+ }
+ return srcTables;
+ }
+
+ public static void addSrcTable(String table) {
+ getSrcTables().add(table);
+ storeSrcTables();
+ }
+
+ public static Set<String> initSrcTables() {
+ if (srcTables == null) {
+ initSrcTablesFromSystemProperty();
+ storeSrcTables();
+ }
+
+ return srcTables;
+ }
+
+ public static boolean isSourceTable(String name) {
+ return getSrcTables().contains(name);
+ }
+
+ private static void storeSrcTables() {
+ QTestSystemProperties.setSrcTables(srcTables);
+ }
+
+ private static void initSrcTablesFromSystemProperty() {
+ srcTables = new HashSet<String>();
+ // FIXME: moved default value to here...for now
+ // i think this features is never really used from the command line
+ for (String srcTable : QTestSystemProperties.getSrcTables()) {
+ srcTable = srcTable.trim();
+ if (!srcTable.isEmpty()) {
+ srcTables.add(srcTable);
+ }
+ }
+ }
+}
diff --git a/itests/util/src/main/java/org/apache/hadoop/hive/ql/parse/CoreParseNegative.java b/itests/util/src/main/java/org/apache/hadoop/hive/ql/parse/CoreParseNegative.java
index 6eb20fe..9a136e2 100644
--- a/itests/util/src/main/java/org/apache/hadoop/hive/ql/parse/CoreParseNegative.java
+++ b/itests/util/src/main/java/org/apache/hadoop/hive/ql/parse/CoreParseNegative.java
@@ -28,7 +28,7 @@ import org.apache.hadoop.hive.cli.control.CliConfigs;
import org.apache.hadoop.hive.ql.QTestArguments;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
import org.apache.hadoop.hive.ql.QTestUtil;
-import org.apache.hadoop.hive.ql.QTestUtil.MiniClusterType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.MiniClusterType;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.BeforeClass;
@@ -40,7 +40,6 @@ public class CoreParseNegative extends CliAdapter{
private static QTestUtil qt;
private static CliConfigs.ParseNegativeConfig cliConfig = new CliConfigs.ParseNegativeConfig();
- private static boolean firstRun;
public CoreParseNegative(AbstractCliConfig testCliConfig) {
super(testCliConfig);
@@ -52,7 +51,6 @@ public class CoreParseNegative extends CliAdapter{
MiniClusterType miniMR = cliConfig.getClusterType();
String initScript = cliConfig.getInitScript();
String cleanupScript = cliConfig.getCleanupScript();
- firstRun = true;
try {
qt = new QTestUtil(
@@ -67,6 +65,8 @@ public class CoreParseNegative extends CliAdapter{
.build());
qt.newSession();
+ qt.cleanUp();
+ qt.createSources();
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
@@ -102,9 +102,6 @@ public class CoreParseNegative extends CliAdapter{
}
}
- private static String debugHint = "\nSee ./ql/target/tmp/log/hive.log or ./itests/qtest/target/tmp/log/hive.log, "
- + "or check ./ql/target/surefire-reports or ./itests/qtest/target/surefire-reports/ for specific test cases logs.";
-
@Override
public void runTest(String tname, String fname, String fpath) throws Exception {
long startTime = System.currentTimeMillis();
@@ -112,33 +109,25 @@ public class CoreParseNegative extends CliAdapter{
System.err.println("Begin query: " + fname);
qt.addFile(fpath);
- if (firstRun) {
- qt.init(fname);
- firstRun = false;
- }
-
qt.cliInit(new File(fpath));
ASTNode tree = qt.parseQuery(fname);
qt.analyzeAST(tree);
- fail("Unexpected success for query: " + fname + debugHint);
- }
- catch (ParseException pe) {
+ fail("Unexpected success for query: " + fname + QTestUtil.DEBUG_HINT);
+ } catch (ParseException pe) {
QTestProcessExecResult result = qt.checkNegativeResults(fname, pe);
if (result.getReturnCode() != 0) {
- qt.failedQuery(null, result.getReturnCode(), fname, result.getCapturedOutput() + "\r\n" + debugHint);
+ qt.failedQuery(null, result.getReturnCode(), fname, result.getCapturedOutput() + "\r\n" + QTestUtil.DEBUG_HINT);
}
- }
- catch (SemanticException se) {
+ } catch (SemanticException se) {
QTestProcessExecResult result = qt.checkNegativeResults(fname, se);
if (result.getReturnCode() != 0) {
- String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ?
- debugHint : "\r\n" + result.getCapturedOutput();
+ String message = Strings.isNullOrEmpty(result.getCapturedOutput()) ? QTestUtil.DEBUG_HINT
+ : "\r\n" + result.getCapturedOutput();
qt.failedDiff(result.getReturnCode(), fname, message);
}
- }
- catch (Exception e) {
- qt.failedWithException(e, fname, debugHint);
+ } catch (Exception e) {
+ qt.failedWithException(e, fname, QTestUtil.DEBUG_HINT);
}
long elapsedTime = System.currentTimeMillis() - startTime;
diff --git a/itests/util/src/main/java/org/apache/hive/beeline/QFile.java b/itests/util/src/main/java/org/apache/hive/beeline/QFile.java
index 6e64c53..34e7113 100644
--- a/itests/util/src/main/java/org/apache/hive/beeline/QFile.java
+++ b/itests/util/src/main/java/org/apache/hive/beeline/QFile.java
@@ -20,7 +20,7 @@ package org.apache.hive.beeline;
import org.apache.commons.io.FileUtils;
import org.apache.hadoop.hive.ql.QTestProcessExecResult;
-import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.dataset.QTestDatasetHandler;
import org.apache.hadoop.util.Shell;
import org.apache.hive.common.util.StreamPrinter;
import org.apache.hive.beeline.ConvertedOutputFile.Converter;
@@ -43,7 +43,7 @@ import java.util.regex.Pattern;
* input and output files, and provides methods for filtering the output of the runs.
*/
public final class QFile {
- private static final Set<String> srcTables = QTestUtil.getSrcTables();
+ private static final Set<String> srcTables = QTestDatasetHandler.getSrcTables();
private static final String DEBUG_HINT =
"The following files can help you identifying the problem:%n"
+ " - Query file: %1s%n"
diff --git a/itests/util/src/main/java/org/apache/hive/beeline/QFileBeeLineClient.java b/itests/util/src/main/java/org/apache/hive/beeline/QFileBeeLineClient.java
index be4c6e8..2a1bb2c 100644
--- a/itests/util/src/main/java/org/apache/hive/beeline/QFileBeeLineClient.java
+++ b/itests/util/src/main/java/org/apache/hive/beeline/QFileBeeLineClient.java
@@ -20,6 +20,7 @@ package org.apache.hive.beeline;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.hadoop.hive.ql.QTestUtil;
+import org.apache.hadoop.hive.ql.dataset.QTestDatasetHandler;
import org.apache.hive.beeline.ConvertedOutputFile.Converter;
import java.io.File;
@@ -152,7 +153,7 @@ public class QFileBeeLineClient implements AutoCloseable {
.map(database -> "DROP DATABASE `" + database + "` CASCADE;")
.collect(Collectors.toSet());
- Set<String> srcTables = QTestUtil.getSrcTables();
+ Set<String> srcTables = QTestDatasetHandler.getSrcTables();
dropCommands.addAll(getTables().stream()
.filter(table -> !srcTables.contains(table))
.map(table -> "DROP TABLE `" + table + "` PURGE;")
diff --git a/itests/util/src/test/java/org/apache/hadoop/hive/ql/TestQOutProcessor.java b/itests/util/src/test/java/org/apache/hadoop/hive/ql/TestQOutProcessor.java
index 9e19f27..617fcd7 100644
--- a/itests/util/src/test/java/org/apache/hadoop/hive/ql/TestQOutProcessor.java
+++ b/itests/util/src/test/java/org/apache/hadoop/hive/ql/TestQOutProcessor.java
@@ -17,7 +17,7 @@
*/
package org.apache.hadoop.hive.ql;
-import org.apache.hadoop.hive.ql.QTestUtil.FsType;
+import org.apache.hadoop.hive.ql.QTestMiniClusters.FsType;
import org.junit.Assert;
import org.junit.Test;
@@ -25,7 +25,7 @@ import org.junit.Test;
* This class contains unit tests for QTestUtil
*/
public class TestQOutProcessor {
- QOutProcessor qOutProcessor = new QOutProcessor(FsType.local);
+ QOutProcessor qOutProcessor = new QOutProcessor(FsType.LOCAL);
@Test
public void testSelectiveHdfsPatternMaskOnlyHdfsPath() {
[hive] 02/02: HIVE-21703: Break up DDLTask - extract Partition
related operations (Miklos Gergely via Zoltan Haindrich)
Posted by kg...@apache.org.
This is an automated email from the ASF dual-hosted git repository.
kgyrtkirk pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git
commit cdf8d8b7984dbb20b4f3153e0ecc829e03a9cb69
Author: Miklos Gergely <mg...@hortonworks.com>
AuthorDate: Mon May 13 14:46:06 2019 +0200
HIVE-21703: Break up DDLTask - extract Partition related operations (Miklos Gergely via Zoltan Haindrich)
Signed-off-by: Zoltan Haindrich <ki...@rxd.hu>
---
.../cli/SemanticAnalysis/HCatSemanticAnalyzer.java | 37 +--
.../hive/hcatalog/streaming/HiveEndPoint.java | 4 +-
.../hive/ql/parse/TestReplicationScenarios.java | 11 +-
.../hadoop/hive/ql/ddl/table/AlterTableUtils.java | 64 ++++
.../partition/AlterTableAddPartitionDesc.java} | 45 +--
.../partition/AlterTableAddPartitionOperation.java | 49 +++
.../partition/AlterTableAlterPartitionDesc.java | 80 +++++
.../AlterTableAlterPartitionOperation.java | 137 ++++++++
.../partition/AlterTableDropPartitionDesc.java} | 38 ++-
.../AlterTableDropPartitionOperation.java | 115 +++++++
.../AlterTableExchangePartitionsDesc.java} | 48 ++-
.../AlterTableExchangePartitionsOperation.java | 65 ++++
.../partition/AlterTableRenamePartitionDesc.java | 103 ++++++
.../AlterTableRenamePartitionOperation.java | 99 ++++++
.../table/partition}/ShowPartitionsDesc.java | 78 +----
.../table/partition/ShowPartitionsOperation.java | 66 ++++
.../table/partition/package-info.java} | 10 +-
.../org/apache/hadoop/hive/ql/exec/DDLTask.java | 357 ---------------------
.../exec/repl/bootstrap/events/PartitionEvent.java | 4 +-
.../ql/exec/repl/bootstrap/events/TableEvent.java | 4 +-
.../events/filesystem/FSPartitionEvent.java | 6 +-
.../bootstrap/events/filesystem/FSTableEvent.java | 16 +-
.../exec/repl/bootstrap/load/ReplicationState.java | 8 +-
.../repl/bootstrap/load/table/LoadPartitions.java | 44 +--
.../org/apache/hadoop/hive/ql/metadata/Hive.java | 23 +-
.../hadoop/hive/ql/parse/DDLSemanticAnalyzer.java | 62 ++--
.../hive/ql/parse/ImportSemanticAnalyzer.java | 47 ++-
.../repl/load/message/DropPartitionHandler.java | 12 +-
.../repl/load/message/RenamePartitionHandler.java | 10 +-
.../hive/ql/plan/AlterTableAlterPartDesc.java | 72 -----
.../org/apache/hadoop/hive/ql/plan/DDLWork.java | 102 ------
.../hadoop/hive/ql/plan/RenamePartitionDesc.java | 141 --------
.../clientpositive/alter_partition_change_col.q | 1 +
.../clientpositive/alter_rename_partition.q | 1 +
.../clientpositive/drop_partitions_filter.q | 5 +
.../queries/clientpositive/exchgpartition2lel.q | 1 +
.../test/queries/clientpositive/show_partitions.q | 4 +-
.../add_partition_with_whitelist.q.out | 2 +-
ql/src/test/results/clientnegative/addpart1.q.out | 2 +-
.../alter_partition_with_whitelist.q.out | 2 +-
.../alter_rename_partition_failure.q.out | 2 +-
.../alter_rename_partition_failure2.q.out | 2 +-
.../clientnegative/exchange_partition.q.out | 2 +-
ql/src/test/results/clientnegative/external2.q.out | 2 +-
.../results/clientpositive/add_part_multiple.q.out | 4 +-
.../alter_partition_change_col.q.out | 16 +
.../clientpositive/alter_rename_partition.q.out | 22 ++
.../clientpositive/drop_deleted_partitions.q.out | 5 +-
.../clientpositive/drop_multi_partitions.q.out | 5 +-
.../clientpositive/drop_partitions_filter.q.out | 72 +++++
.../clientpositive/llap/exchgpartition2lel.q.out | 19 ++
.../results/clientpositive/show_partitions.q.out | 47 +++
ql/src/test/results/clientpositive/showparts.q.out | 5 +-
.../clientpositive/spark/add_part_multiple.q.out | 4 +-
.../hive/streaming/HiveStreamingConnection.java | 4 +-
55 files changed, 1207 insertions(+), 979 deletions(-)
diff --git a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/cli/SemanticAnalysis/HCatSemanticAnalyzer.java b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/cli/SemanticAnalysis/HCatSemanticAnalyzer.java
index 6b43b53..abd351d 100644
--- a/hcatalog/core/src/main/java/org/apache/hive/hcatalog/cli/SemanticAnalysis/HCatSemanticAnalyzer.java
+++ b/hcatalog/core/src/main/java/org/apache/hive/hcatalog/cli/SemanticAnalysis/HCatSemanticAnalyzer.java
@@ -28,6 +28,8 @@ import org.apache.hadoop.hive.ql.ddl.database.SwitchDatabaseDesc;
import org.apache.hadoop.hive.ql.ddl.table.info.DescTableDesc;
import org.apache.hadoop.hive.ql.ddl.table.info.ShowTableStatusDesc;
import org.apache.hadoop.hive.ql.ddl.table.info.ShowTablesDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableDropPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.ShowPartitionsDesc;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.Utilities;
import org.apache.hadoop.hive.ql.metadata.Hive;
@@ -41,9 +43,7 @@ import org.apache.hadoop.hive.ql.parse.HiveSemanticAnalyzerHookContext;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.plan.AlterTableDesc;
import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.HiveOperation;
-import org.apache.hadoop.hive.ql.plan.ShowPartitionsDesc;
import org.apache.hadoop.hive.ql.security.authorization.Privilege;
import org.apache.hadoop.hive.ql.session.SessionState;
import org.apache.hive.hcatalog.common.ErrorType;
@@ -314,20 +314,10 @@ public class HCatSemanticAnalyzer extends HCatSemanticAnalyzerBase {
String dbName = showTableStatus.getDbName() == null ? SessionState.get().getCurrentDatabase()
: showTableStatus.getDbName();
authorize(cntxt.getHive().getDatabase(dbName), Privilege.SELECT);
- }
- }
-
- @Override
- protected void authorizeDDLWork(HiveSemanticAnalyzerHookContext cntxt, Hive hive, DDLWork work)
- throws HiveException {
- // TODO: add alter database support in HCat
-
- // Table operations.
-
- DropPartitionDesc dropPartition = work.getDropPartitionDesc();
- if (dropPartition != null) {
+ } else if (ddlDesc instanceof AlterTableDropPartitionDesc) {
+ AlterTableDropPartitionDesc dropPartition = (AlterTableDropPartitionDesc)ddlDesc;
//this is actually a ALTER TABLE DROP PARITITION statement
- for (DropPartitionDesc.PartSpec partSpec : dropPartition.getPartSpecs()) {
+ for (AlterTableDropPartitionDesc.PartitionDesc partSpec : dropPartition.getPartSpecs()) {
// partitions are not added as write entries in drop partitions in Hive
Table table = hive.getTable(SessionState.get().getCurrentDatabase(), dropPartition.getTableName());
List<Partition> partitions = null;
@@ -340,8 +330,19 @@ public class HCatSemanticAnalyzer extends HCatSemanticAnalyzerBase {
authorize(part, Privilege.DROP);
}
}
+ } else if (ddlDesc instanceof ShowPartitionsDesc) {
+ ShowPartitionsDesc showParts = (ShowPartitionsDesc)ddlDesc;
+ String tableName = extractTableName(showParts.getTabName());
+ authorizeTable(cntxt.getHive(), tableName, Privilege.SELECT);
}
+ }
+
+ @Override
+ protected void authorizeDDLWork(HiveSemanticAnalyzerHookContext cntxt, Hive hive, DDLWork work)
+ throws HiveException {
+ // TODO: add alter database support in HCat
+ // Table operations.
AlterTableDesc alterTable = work.getAlterTblDesc();
if (alterTable != null) {
Table table = hive.getTable(SessionState.get().getCurrentDatabase(),
@@ -372,11 +373,5 @@ public class HCatSemanticAnalyzer extends HCatSemanticAnalyzerBase {
}
//other alter operations are already supported by Hive
}
-
- ShowPartitionsDesc showParts = work.getShowPartsDesc();
- if (showParts != null) {
- String tableName = extractTableName(showParts.getTabName());
- authorizeTable(cntxt.getHive(), tableName, Privilege.SELECT);
- }
}
}
diff --git a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/HiveEndPoint.java b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/HiveEndPoint.java
index 66a1737..fee7ffc 100644
--- a/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/HiveEndPoint.java
+++ b/hcatalog/streaming/src/java/org/apache/hive/hcatalog/streaming/HiveEndPoint.java
@@ -27,7 +27,7 @@ import org.apache.hadoop.hive.metastore.api.Partition;
import org.apache.hadoop.hive.ql.io.AcidUtils;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.hadoop.hive.cli.CliSessionState;
@@ -467,7 +467,7 @@ public class HiveEndPoint {
Map<String, String> partSpec =
Warehouse.makeSpecFromValues(tableObject.getPartitionKeys(), ep.partitionVals);
- AddPartitionDesc addPartitionDesc = new AddPartitionDesc(ep.database, ep.table, true);
+ AlterTableAddPartitionDesc addPartitionDesc = new AlterTableAddPartitionDesc(ep.database, ep.table, true);
String partLocation = new Path(tableObject.getDataLocation(),
Warehouse.makePartPath(partSpec)).toString();
addPartitionDesc.addPartition(partSpec, partLocation);
diff --git a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
index 3820fab..54de320 100644
--- a/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
+++ b/itests/hive-unit/src/test/java/org/apache/hadoop/hive/ql/parse/TestReplicationScenarios.java
@@ -59,7 +59,8 @@ import org.apache.hadoop.hive.metastore.messaging.json.gzip.GzipJSONMessageEncod
import org.apache.hadoop.hive.ql.DriverFactory;
import org.apache.hadoop.hive.ql.ErrorMsg;
import org.apache.hadoop.hive.ql.IDriver;
-import org.apache.hadoop.hive.ql.exec.DDLTask;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.hive.ql.exec.MoveTask;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
@@ -378,11 +379,9 @@ public class TestReplicationScenarios {
private boolean hasPartitionTask(Task rootTask) {
checkTaskPresent validator = new checkTaskPresent() {
public boolean validate(Task task) {
- if (task instanceof DDLTask) {
- DDLTask ddlTask = (DDLTask)task;
- if (ddlTask.getWork().getAddPartitionDesc() != null) {
- return true;
- }
+ if (task instanceof DDLTask2) {
+ DDLTask2 ddlTask = (DDLTask2)task;
+ return ddlTask.getWork().getDDLDesc() instanceof AlterTableAddPartitionDesc;
}
return false;
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/AlterTableUtils.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/AlterTableUtils.java
new file mode 100644
index 0000000..3c6d7ea
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/AlterTableUtils.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table;
+
+import java.util.Map;
+
+import org.apache.hadoop.hive.ql.metadata.Hive;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+
+/**
+ * Utilities used by some ALTER TABLE commands.
+ */
+public final class AlterTableUtils {
+ private AlterTableUtils() {
+ throw new UnsupportedOperationException("AlterTableUtils should not be instantiated");
+ }
+
+ /**
+ * Validate if the given table/partition is eligible for update.
+ */
+ public static boolean allowOperationInReplicationScope(Hive db, String tableName, Map<String, String> partSpec,
+ ReplicationSpec replicationSpec) throws HiveException {
+ if ((null == replicationSpec) || (!replicationSpec.isInReplicationScope())) {
+ // Always allow the operation if it is not in replication scope.
+ return true;
+ }
+
+ // If the table/partition exist and is older than the event, then just apply the event else noop.
+ Table existingTable = db.getTable(tableName, false);
+ if ((existingTable != null) && replicationSpec.allowEventReplacementInto(existingTable.getParameters())) {
+ // Table exists and is older than the update. Now, need to ensure if update allowed on the partition.
+ if (partSpec != null) {
+ Partition existingPtn = db.getPartition(existingTable, partSpec, false);
+ return ((existingPtn != null) && replicationSpec.allowEventReplacementInto(existingPtn.getParameters()));
+ }
+
+ // Replacement is allowed as the existing table is older than event
+ return true;
+ }
+
+ // The table is missing either due to drop/rename which follows the operation.
+ // Or the existing table is newer than our update. So, don't allow the update.
+ return false;
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/AddPartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionDesc.java
similarity index 87%
rename from ql/src/java/org/apache/hadoop/hive/ql/plan/AddPartitionDesc.java
rename to ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionDesc.java
index 8ea857e..08a2ffb 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/AddPartitionDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionDesc.java
@@ -15,35 +15,42 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.hadoop.hive.ql.plan;
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
import java.io.Serializable;
import java.util.ArrayList;
-import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Order;
import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+import org.apache.hadoop.hive.ql.plan.Explain;
+import org.apache.hadoop.hive.ql.plan.Explain.Level;
/**
- * Contains the information needed to add one or more partitions.
+ * DDL task description for ALTER TABLE ... DROP PARTITION ... commands.
*/
-public class AddPartitionDesc extends DDLDesc implements Serializable {
-
+@Explain(displayName = "Add Partition", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+public class AlterTableAddPartitionDesc implements DDLDesc, Serializable {
+ private static final long serialVersionUID = 1L;
- public static class OnePartitionDesc {
- public OnePartitionDesc() {}
+ static {
+ DDLTask2.registerOperation(AlterTableAddPartitionDesc.class, AlterTableAddPartitionOperation.class);
+ }
- OnePartitionDesc(
+ public static class PartitionDesc {
+ PartitionDesc(
Map<String, String> partSpec, String location, Map<String, String> params) {
this(partSpec, location);
this.partParams = params;
}
- OnePartitionDesc(Map<String, String> partSpec, String location) {
+ PartitionDesc(Map<String, String> partSpec, String location) {
this.partSpec = partSpec;
this.location = location;
}
@@ -158,12 +165,10 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
public void setWriteId(long writeId) { this.writeId = writeId; }
}
- private static final long serialVersionUID = 1L;
-
String tableName;
String dbName;
boolean ifNotExists;
- List<OnePartitionDesc> partitions = null;
+ List<PartitionDesc> partitions = null;
boolean replaceMode = false;
private ReplicationSpec replicationSpec = null;
@@ -171,10 +176,10 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
/**
* For serialization only.
*/
- public AddPartitionDesc() {
+ public AlterTableAddPartitionDesc() {
}
- public AddPartitionDesc(
+ public AlterTableAddPartitionDesc(
String dbName, String tableName, boolean ifNotExists) {
super();
this.dbName = dbName;
@@ -196,7 +201,7 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
* partition parameters.
*/
@Deprecated
- public AddPartitionDesc(String dbName, String tableName,
+ public AlterTableAddPartitionDesc(String dbName, String tableName,
Map<String, String> partSpec, String location, Map<String, String> params) {
super();
this.dbName = dbName;
@@ -212,9 +217,9 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
private void addPartition(
Map<String, String> partSpec, String location, Map<String, String> params) {
if (this.partitions == null) {
- this.partitions = new ArrayList<OnePartitionDesc>();
+ this.partitions = new ArrayList<PartitionDesc>();
}
- this.partitions.add(new OnePartitionDesc(partSpec, location, params));
+ this.partitions.add(new PartitionDesc(partSpec, location, params));
}
/**
@@ -255,7 +260,7 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
if (this.partitions == null || this.partitions.isEmpty()) return "<no partition>";
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
- for (OnePartitionDesc desc : this.partitions) {
+ for (PartitionDesc desc : this.partitions) {
if (!isFirst) {
sb.append(", ");
}
@@ -270,7 +275,7 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
if (this.partitions == null || this.partitions.isEmpty()) return "<no partition>";
boolean isFirst = true;
StringBuilder sb = new StringBuilder();
- for (OnePartitionDesc desc : this.partitions) {
+ for (PartitionDesc desc : this.partitions) {
if (!isFirst) {
sb.append(", ");
}
@@ -299,7 +304,7 @@ public class AddPartitionDesc extends DDLDesc implements Serializable {
return this.partitions.size();
}
- public OnePartitionDesc getPartition(int i) {
+ public PartitionDesc getPartition(int i) {
return this.partitions.get(i);
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionOperation.java
new file mode 100644
index 0000000..19eb790
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAddPartitionOperation.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.util.List;
+
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.hooks.WriteEntity;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+
+/**
+ * Operation process of adding a partition to a table.
+ */
+public class AlterTableAddPartitionOperation extends DDLOperation {
+ private final AlterTableAddPartitionDesc desc;
+
+ public AlterTableAddPartitionOperation(DDLOperationContext context, AlterTableAddPartitionDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ List<Partition> parts = context.getDb().createPartitions(desc);
+ for (Partition part : parts) {
+ DDLUtils.addIfAbsentByName(new WriteEntity(part, WriteEntity.WriteType.INSERT), context);
+ }
+ return 0;
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionDesc.java
new file mode 100644
index 0000000..33b0205
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionDesc.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
+import org.apache.hadoop.hive.ql.plan.Explain;
+import org.apache.hadoop.hive.ql.plan.DDLDesc.DDLDescWithWriteId;
+import org.apache.hadoop.hive.ql.plan.Explain.Level;
+
+/**
+ * DDL task description for ALTER TABLE ... PARTITION COLUMN ... commands.
+ */
+@Explain(displayName = "Alter Partition", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+public class AlterTableAlterPartitionDesc implements DDLDesc, DDLDescWithWriteId {
+ public static final long serialVersionUID = 1;
+
+ static {
+ DDLTask2.registerOperation(AlterTableAlterPartitionDesc.class, AlterTableAlterPartitionOperation.class);
+ }
+
+ private final String fqTableName;
+ private final FieldSchema partKeySpec;
+
+ public AlterTableAlterPartitionDesc(String fqTableName, FieldSchema partKeySpec) {
+ this.fqTableName = fqTableName;
+ this.partKeySpec = partKeySpec;
+ }
+
+ @Explain(displayName = "table", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public String getTableName() {
+ return fqTableName;
+ }
+
+ public FieldSchema getPartKeySpec() {
+ return partKeySpec;
+ }
+
+ @Explain(displayName = "partition key name", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public String getPartKeyName() {
+ return partKeySpec.getName();
+ }
+
+ @Explain(displayName = "partition key type", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public String getPartKeyType() {
+ return partKeySpec.getType();
+ }
+
+ @Override
+ public void setWriteId(long writeId) {
+ // We don't actually need the write id, but by implementing DDLDescWithWriteId it ensures that it is allocated
+ }
+
+ @Override
+ public String getFullTableName() {
+ return fqTableName;
+ }
+
+ @Override
+ public boolean mayNeedWriteId() {
+ return true; // Checked before setting as the acid desc.
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionOperation.java
new file mode 100644
index 0000000..57cba22
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableAlterPartitionOperation.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.metastore.api.FieldSchema;
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.hooks.ReadEntity;
+import org.apache.hadoop.hive.ql.hooks.WriteEntity;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
+import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
+import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
+import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
+
+/**
+ * Operation process of altering a partition to a table.
+ */
+public class AlterTableAlterPartitionOperation extends DDLOperation {
+ private final AlterTableAlterPartitionDesc desc;
+
+ public AlterTableAlterPartitionOperation(DDLOperationContext context, AlterTableAlterPartitionDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ Table tbl = context.getDb().getTable(desc.getTableName(), true);
+
+ check(tbl);
+ setNewPartitionKeys(tbl);
+ alterTable(tbl);
+
+ return 0;
+ }
+
+ private void check(Table tbl) throws HiveException {
+ assert(tbl.isPartitioned());
+ try {
+ int colIndex = getColumnIndex(tbl);
+ checkPartitionValues(tbl, colIndex);
+ } catch(Exception e) {
+ throw new HiveException("Exception while checking type conversion of existing partition values to " +
+ desc.getPartKeySpec() + " : " + e.getMessage());
+ }
+ }
+
+ private int getColumnIndex(Table tbl) throws HiveException {
+ int colIndex = -1;
+ for (FieldSchema col : tbl.getTTable().getPartitionKeys()) {
+ colIndex++;
+ if (col.getName().compareTo(desc.getPartKeyName()) == 0) {
+ return colIndex;
+ }
+ }
+
+ throw new HiveException("Cannot find partition column " + desc.getPartKeyName());
+ }
+
+ /**
+ * Check if the existing partition values can be type casted to the new column type
+ * with a non null value before trying to alter the partition column type.
+ */
+ private void checkPartitionValues(Table tbl, int colIndex) throws HiveException {
+ TypeInfo expectedType = TypeInfoUtils.getTypeInfoFromTypeString(desc.getPartKeyType());
+ ObjectInspector outputOI = TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(expectedType);
+ Converter converter = ObjectInspectorConverters.getConverter(
+ PrimitiveObjectInspectorFactory.javaStringObjectInspector, outputOI);
+
+ Set<Partition> partitions = context.getDb().getAllPartitionsOf(tbl);
+ for (Partition part : partitions) {
+ if (part.getName().equals(context.getConf().getVar(HiveConf.ConfVars.DEFAULTPARTITIONNAME))) {
+ continue;
+ }
+
+ try {
+ String value = part.getValues().get(colIndex);
+ Object convertedValue = converter.convert(value);
+ if (convertedValue == null) {
+ throw new HiveException(" Converting from " + TypeInfoFactory.stringTypeInfo + " to " + expectedType +
+ " for value : " + value + " resulted in NULL object");
+ }
+ } catch (Exception e) {
+ throw new HiveException("Exception while converting " + TypeInfoFactory.stringTypeInfo + " to " +
+ expectedType + " for value : " + part.getValues().get(colIndex));
+ }
+ }
+ }
+
+ private void setNewPartitionKeys(Table tbl) {
+ List<FieldSchema> newPartitionKeys = new ArrayList<FieldSchema>();
+ for (FieldSchema col : tbl.getTTable().getPartitionKeys()) {
+ if (col.getName().compareTo(desc.getPartKeyName()) == 0) {
+ newPartitionKeys.add(desc.getPartKeySpec());
+ } else {
+ newPartitionKeys.add(col);
+ }
+ }
+
+ tbl.getTTable().setPartitionKeys(newPartitionKeys);
+ }
+
+ private void alterTable(Table tbl) throws HiveException {
+ context.getDb().alterTable(tbl, false, null, true);
+ context.getWork().getInputs().add(new ReadEntity(tbl));
+ // We've already locked the table as the input, don't relock it as the output.
+ DDLUtils.addIfAbsentByName(new WriteEntity(tbl, WriteEntity.WriteType.DDL_NO_LOCK), context);
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/DropPartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionDesc.java
similarity index 67%
rename from ql/src/java/org/apache/hadoop/hive/ql/plan/DropPartitionDesc.java
rename to ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionDesc.java
index 81fcc46..c57aef7 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/DropPartitionDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionDesc.java
@@ -16,34 +16,42 @@
* limitations under the License.
*/
-package org.apache.hadoop.hive.ql.plan;
+package org.apache.hadoop.hive.ql.ddl.table.partition;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+import org.apache.hadoop.hive.ql.plan.Explain;
+import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.Explain.Level;
/**
- * DropPartitionDesc.
+ * DDL task description for ALTER TABLE ... DROP PARTITION ... commands.
*/
@Explain(displayName = "Drop Partition", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
-public class DropPartitionDesc extends DDLDesc implements Serializable {
+public class AlterTableDropPartitionDesc implements DDLDesc, Serializable {
private static final long serialVersionUID = 1L;
+ static {
+ DDLTask2.registerOperation(AlterTableDropPartitionDesc.class, AlterTableDropPartitionOperation.class);
+ }
+
/**
- * PartSpec.
+ * Partition description.
*/
- public static class PartSpec implements Serializable {
+ public static class PartitionDesc implements Serializable {
private static final long serialVersionUID = 1L;
- private ExprNodeGenericFuncDesc partSpec;
+ private final ExprNodeGenericFuncDesc partSpec;
// TODO: see if we can get rid of this... used in one place to distinguish archived parts
- private int prefixLength;
+ private final int prefixLength;
- public PartSpec(ExprNodeGenericFuncDesc partSpec, int prefixLength) {
+ public PartitionDesc(ExprNodeGenericFuncDesc partSpec, int prefixLength) {
this.partSpec = partSpec;
this.prefixLength = prefixLength;
}
@@ -58,18 +66,18 @@ public class DropPartitionDesc extends DDLDesc implements Serializable {
}
private final String tableName;
- private final ArrayList<PartSpec> partSpecs;
+ private final ArrayList<PartitionDesc> partSpecs;
private final boolean ifPurge;
private final ReplicationSpec replicationSpec;
- public DropPartitionDesc(String tableName, Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecs, boolean ifPurge,
- ReplicationSpec replicationSpec) {
+ public AlterTableDropPartitionDesc(String tableName, Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecs,
+ boolean ifPurge, ReplicationSpec replicationSpec) {
this.tableName = tableName;
- this.partSpecs = new ArrayList<PartSpec>(partSpecs.size());
+ this.partSpecs = new ArrayList<PartitionDesc>(partSpecs.size());
for (Map.Entry<Integer, List<ExprNodeGenericFuncDesc>> partSpec : partSpecs.entrySet()) {
int prefixLength = partSpec.getKey();
for (ExprNodeGenericFuncDesc expr : partSpec.getValue()) {
- this.partSpecs.add(new PartSpec(expr, prefixLength));
+ this.partSpecs.add(new PartitionDesc(expr, prefixLength));
}
}
this.ifPurge = ifPurge;
@@ -81,12 +89,12 @@ public class DropPartitionDesc extends DDLDesc implements Serializable {
return tableName;
}
- public ArrayList<PartSpec> getPartSpecs() {
+ public ArrayList<PartitionDesc> getPartSpecs() {
return partSpecs;
}
public boolean getIfPurge() {
- return ifPurge;
+ return ifPurge;
}
/**
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionOperation.java
new file mode 100644
index 0000000..eae2b51
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableDropPartitionOperation.java
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.hadoop.hive.metastore.PartitionDropOptions;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.hooks.WriteEntity;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+
+import com.google.common.collect.Iterables;
+
+/**
+ * Operation process of dropping some partitions of a table.
+ */
+public class AlterTableDropPartitionOperation extends DDLOperation {
+ private final AlterTableDropPartitionDesc desc;
+
+ public AlterTableDropPartitionOperation(DDLOperationContext context, AlterTableDropPartitionDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ // We need to fetch the table before it is dropped so that it can be passed to post-execution hook
+ Table tbl = null;
+ try {
+ tbl = context.getDb().getTable(desc.getTableName());
+ } catch (InvalidTableException e) {
+ // drop table is idempotent
+ }
+
+ ReplicationSpec replicationSpec = desc.getReplicationSpec();
+ if (replicationSpec.isInReplicationScope()) {
+ dropPartitionForReplication(tbl, replicationSpec);
+ } else {
+ dropPartitions();
+ }
+
+ return 0;
+ }
+
+ private void dropPartitionForReplication(Table tbl, ReplicationSpec replicationSpec) throws HiveException {
+ /**
+ * ALTER TABLE DROP PARTITION ... FOR REPLICATION(x) behaves as a DROP PARTITION IF OLDER THAN x
+ *
+ * So, we check each partition that matches our DropTableDesc.getPartSpecs(), and drop it only
+ * if it's older than the event that spawned this replicated request to drop partition
+ */
+ // TODO: Current implementation of replication will result in DROP_PARTITION under replication
+ // scope being called per-partition instead of multiple partitions. However, to be robust, we
+ // must still handle the case of multiple partitions in case this assumption changes in the
+ // future. However, if this assumption changes, we will not be very performant if we fetch
+ // each partition one-by-one, and then decide on inspection whether or not this is a candidate
+ // for dropping. Thus, we need a way to push this filter (replicationSpec.allowEventReplacementInto)
+ // to the metastore to allow it to do drop a partition or not, depending on a Predicate on the
+ // parameter key values.
+
+ if (tbl == null) {
+ // If table is missing, then partitions are also would've been dropped. Just no-op.
+ return;
+ }
+
+ for (AlterTableDropPartitionDesc.PartitionDesc partSpec : desc.getPartSpecs()){
+ List<Partition> partitions = new ArrayList<>();
+ try {
+ context.getDb().getPartitionsByExpr(tbl, partSpec.getPartSpec(), context.getConf(), partitions);
+ for (Partition p : Iterables.filter(partitions, replicationSpec.allowEventReplacementInto())) {
+ context.getDb().dropPartition(tbl.getDbName(), tbl.getTableName(), p.getValues(), true);
+ }
+ } catch (NoSuchObjectException e){
+ // ignore NSOE because that means there's nothing to drop.
+ } catch (Exception e) {
+ throw new HiveException(e.getMessage(), e);
+ }
+ }
+ }
+
+ private void dropPartitions() throws HiveException {
+ // ifExists is currently verified in DDLSemanticAnalyzer
+ List<Partition> droppedParts = context.getDb().dropPartitions(desc.getTableName(), desc.getPartSpecs(),
+ PartitionDropOptions.instance().deleteData(true).ifExists(true).purgeData(desc.getIfPurge()));
+ for (Partition partition : droppedParts) {
+ context.getConsole().printInfo("Dropped the partition " + partition.getName());
+ // We have already locked the table, don't lock the partitions.
+ DDLUtils.addIfAbsentByName(new WriteEntity(partition, WriteEntity.WriteType.DDL_NO_LOCK), context);
+ }
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableExchangePartition.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsDesc.java
similarity index 53%
rename from ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableExchangePartition.java
rename to ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsDesc.java
index 2a67494..176bae8 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableExchangePartition.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsDesc.java
@@ -16,52 +16,46 @@
* limitations under the License.
*/
-package org.apache.hadoop.hive.ql.plan;
+package org.apache.hadoop.hive.ql.ddl.table.partition;
import java.util.Map;
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.plan.Explain;
+import org.apache.hadoop.hive.ql.plan.Explain.Level;
-public class AlterTableExchangePartition extends DDLDesc {
-
- // The source table
- private Table sourceTable;
-
- // The destination table
- private Table destinationTable;
+/**
+ * DDL task description for ALTER TABLE ... EXCHANGE PARTITION ... WITH TABLE ... commands.
+ */
+@Explain(displayName = "Exchange Partitions", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+public class AlterTableExchangePartitionsDesc implements DDLDesc {
+ static {
+ DDLTask2.registerOperation(AlterTableExchangePartitionsDesc.class, AlterTableExchangePartitionsOperation.class);
+ }
- // The partition that has to be exchanged
- private Map<String, String> partitionSpecs;
+ private final Table sourceTable;
+ private final Table destinationTable;
+ private final Map<String, String> partitionSpecs;
- public AlterTableExchangePartition(Table sourceTable, Table destinationTable,
+ public AlterTableExchangePartitionsDesc(Table sourceTable, Table destinationTable,
Map<String, String> partitionSpecs) {
- super();
this.sourceTable = sourceTable;
this.destinationTable = destinationTable;
this.partitionSpecs = partitionSpecs;
}
- public void setSourceTable(Table sourceTable) {
- this.sourceTable = sourceTable;
- }
-
public Table getSourceTable() {
- return this.sourceTable;
- }
-
- public void setDestinationTable(Table destinationTable) {
- this.destinationTable = destinationTable;
+ return sourceTable;
}
public Table getDestinationTable() {
- return this.destinationTable;
- }
-
- public void setPartitionSpecs(Map<String, String> partitionSpecs) {
- this.partitionSpecs = partitionSpecs;
+ return destinationTable;
}
+ @Explain(displayName = "partitions", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
public Map<String, String> getPartitionSpecs() {
- return this.partitionSpecs;
+ return partitionSpecs;
}
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsOperation.java
new file mode 100644
index 0000000..6540083
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableExchangePartitionsOperation.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.util.List;
+import java.util.Map;
+
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.hooks.ReadEntity;
+import org.apache.hadoop.hive.ql.hooks.WriteEntity;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+import org.apache.hadoop.hive.ql.metadata.Table;
+
+/**
+ * Operation process of exchanging some partitions between tables.
+ */
+public class AlterTableExchangePartitionsOperation extends DDLOperation {
+ private final AlterTableExchangePartitionsDesc desc;
+
+ public AlterTableExchangePartitionsOperation(DDLOperationContext context, AlterTableExchangePartitionsDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ Map<String, String> partitionSpecs = desc.getPartitionSpecs();
+ Table destTable = desc.getDestinationTable();
+ Table sourceTable = desc.getSourceTable();
+
+ List<Partition> partitions = context.getDb().exchangeTablePartitions(partitionSpecs, sourceTable.getDbName(),
+ sourceTable.getTableName(), destTable.getDbName(), destTable.getTableName());
+ for (Partition partition : partitions) {
+ // Reuse the partition specs from dest partition since they should be the same
+ context.getWork().getInputs().add(new ReadEntity(new Partition(sourceTable, partition.getSpec(), null)));
+
+ DDLUtils.addIfAbsentByName(new WriteEntity(new Partition(sourceTable, partition.getSpec(), null),
+ WriteEntity.WriteType.DELETE), context);
+
+ DDLUtils.addIfAbsentByName(new WriteEntity(new Partition(destTable, partition.getSpec(), null),
+ WriteEntity.WriteType.INSERT), context);
+ }
+
+ return 0;
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionDesc.java
new file mode 100644
index 0000000..b534db1
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionDesc.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.io.Serializable;
+import java.util.LinkedHashMap;
+import java.util.Map;
+
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
+import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+import org.apache.hadoop.hive.ql.plan.DDLDesc.DDLDescWithWriteId;
+import org.apache.hadoop.hive.ql.plan.Explain;
+import org.apache.hadoop.hive.ql.plan.Explain.Level;
+
+/**
+ * DDL task description for ALTER TABLE ... PARTITION ... RENAME TO PARTITION ... commands.
+ */
+@Explain(displayName = "Rename Partition", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+public class AlterTableRenamePartitionDesc implements DDLDesc, Serializable, DDLDescWithWriteId {
+ private static final long serialVersionUID = 1L;
+
+ static {
+ DDLTask2.registerOperation(AlterTableRenamePartitionDesc.class, AlterTableRenamePartitionOperation.class);
+ }
+
+ private final String tableName;
+ private final Map<String, String> oldPartSpec;
+ private final Map<String, String> newPartSpec;
+ private final ReplicationSpec replicationSpec;
+ private final String fqTableName;
+
+ private long writeId;
+
+ public AlterTableRenamePartitionDesc(String tableName, Map<String, String> oldPartSpec,
+ Map<String, String> newPartSpec, ReplicationSpec replicationSpec, Table table) {
+ this.tableName = tableName;
+ this.oldPartSpec = new LinkedHashMap<String, String>(oldPartSpec);
+ this.newPartSpec = new LinkedHashMap<String, String>(newPartSpec);
+ this.replicationSpec = replicationSpec;
+ this.fqTableName = table != null ? (table.getDbName() + "." + table.getTableName()) : tableName;
+ }
+
+ @Explain(displayName = "table", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public String getTableName() {
+ return tableName;
+ }
+
+ @Explain(displayName = "old partitions", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public Map<String, String> getOldPartSpec() {
+ return oldPartSpec;
+ }
+
+ @Explain(displayName = "new partitions", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public Map<String, String> getNewPartSpec() {
+ return newPartSpec;
+ }
+
+ /**
+ * @return what kind of replication scope this rename is running under.
+ * This can result in a "RENAME IF NEWER THAN" kind of semantic
+ */
+ @Explain(displayName = "replication", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
+ public ReplicationSpec getReplicationSpec() {
+ return this.replicationSpec;
+ }
+
+ @Override
+ public void setWriteId(long writeId) {
+ this.writeId = writeId;
+ }
+
+ public long getWriteId() {
+ return writeId;
+ }
+
+ @Override
+ public String getFullTableName() {
+ return fqTableName;
+ }
+
+ @Override
+ public boolean mayNeedWriteId() {
+ return true; // The check is done when setting this as the ACID DDLDesc.
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionOperation.java
new file mode 100644
index 0000000..b26d346
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/AlterTableRenamePartitionOperation.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.util.ArrayList;
+import java.util.Map;
+
+import org.apache.hadoop.hive.common.FileUtils;
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.ddl.table.AlterTableUtils;
+import org.apache.hadoop.hive.ql.exec.Utilities;
+import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
+import org.apache.hadoop.hive.ql.hooks.ReadEntity;
+import org.apache.hadoop.hive.ql.hooks.WriteEntity;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Partition;
+import org.apache.hadoop.hive.ql.metadata.Table;
+import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
+import org.apache.hadoop.hive.ql.parse.repl.dump.Utils;
+
+/**
+ * Operation process of renaming a partition of a table.
+ */
+public class AlterTableRenamePartitionOperation extends DDLOperation {
+ private final AlterTableRenamePartitionDesc desc;
+
+ public AlterTableRenamePartitionOperation(DDLOperationContext context, AlterTableRenamePartitionDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ String tableName = desc.getTableName();
+ Map<String, String> oldPartSpec = desc.getOldPartSpec();
+ ReplicationSpec replicationSpec = desc.getReplicationSpec();
+
+ if (!AlterTableUtils.allowOperationInReplicationScope(context.getDb(), tableName, oldPartSpec, replicationSpec)) {
+ // no rename, the table is missing either due to drop/rename which follows the current rename.
+ // or the existing table is newer than our update.
+ LOG.debug("DDLTask: Rename Partition is skipped as table {} / partition {} is newer than update", tableName,
+ FileUtils.makePartName(new ArrayList<>(oldPartSpec.keySet()), new ArrayList<>(oldPartSpec.values())));
+ return 0;
+ }
+
+ String[] names = Utilities.getDbTableName(tableName);
+ if (Utils.isBootstrapDumpInProgress(context.getDb(), names[0])) {
+ LOG.error("DDLTask: Rename Partition not allowed as bootstrap dump in progress");
+ throw new HiveException("Rename Partition: Not allowed as bootstrap dump in progress");
+ }
+
+ Table tbl = context.getDb().getTable(tableName);
+ Partition oldPart = context.getDb().getPartition(tbl, oldPartSpec, false);
+ if (oldPart == null) {
+ String partName = FileUtils.makePartName(new ArrayList<String>(oldPartSpec.keySet()),
+ new ArrayList<String>(oldPartSpec.values()));
+ throw new HiveException("Rename partition: source partition [" + partName + "] does not exist.");
+ }
+
+ Partition part = context.getDb().getPartition(tbl, oldPartSpec, false);
+ part.setValues(desc.getNewPartSpec());
+
+ long writeId = desc.getWriteId();
+ if (replicationSpec != null && replicationSpec.isMigratingToTxnTable()) {
+ Long tmpWriteId = ReplUtils.getMigrationCurrentTblWriteId(context.getConf());
+ if (tmpWriteId == null) {
+ throw new HiveException("DDLTask : Write id is not set in the config by open txn task for migration");
+ }
+ writeId = tmpWriteId;
+ }
+
+ context.getDb().renamePartition(tbl, oldPartSpec, part, writeId);
+ Partition newPart = context.getDb().getPartition(tbl, desc.getNewPartSpec(), false);
+ context.getWork().getInputs().add(new ReadEntity(oldPart));
+
+ // We've already obtained a lock on the table, don't lock the partition too
+ DDLUtils.addIfAbsentByName(new WriteEntity(newPart, WriteEntity.WriteType.DDL_NO_LOCK), context);
+
+ return 0;
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/ShowPartitionsDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsDesc.java
similarity index 52%
rename from ql/src/java/org/apache/hadoop/hive/ql/plan/ShowPartitionsDesc.java
rename to ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsDesc.java
index c9ed41a..187a61f 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/ShowPartitionsDesc.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsDesc.java
@@ -16,104 +16,52 @@
* limitations under the License.
*/
-package org.apache.hadoop.hive.ql.plan;
+package org.apache.hadoop.hive.ql.ddl.table.partition;
import java.io.Serializable;
import java.util.Map;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.ql.ddl.DDLDesc;
+import org.apache.hadoop.hive.ql.ddl.DDLTask2;
+import org.apache.hadoop.hive.ql.plan.Explain;
import org.apache.hadoop.hive.ql.plan.Explain.Level;
-
/**
- * ShowPartitionsDesc.
- *
+ * DDL task description for SHOW PARTITIONS commands.
*/
@Explain(displayName = "Show Partitions", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
-public class ShowPartitionsDesc extends DDLDesc implements Serializable {
+public class ShowPartitionsDesc implements DDLDesc, Serializable {
private static final long serialVersionUID = 1L;
- String tabName;
- String resFile;
- // Filter the partitions to show based on on supplied spec
- Map<String, String> partSpec;
- /**
- * table name for the result of show tables.
- */
- private static final String table = "showpartitions";
- /**
- * thrift ddl for the result of show tables.
- */
- private static final String schema = "partition#string";
-
- public String getTable() {
- return table;
+ static {
+ DDLTask2.registerOperation(ShowPartitionsDesc.class, ShowPartitionsOperation.class);
}
- public String getSchema() {
- return schema;
- }
+ public static final String SCHEMA = "partition#string";
- public ShowPartitionsDesc() {
- }
+ private final String tabName;
+ private final String resFile;
+ private final Map<String, String> partSpec;
- /**
- * @param tabName
- * Name of the table whose partitions need to be listed.
- * @param resFile
- * File to store the results in
- */
- public ShowPartitionsDesc(String tabName, Path resFile,
- Map<String, String> partSpec) {
+ public ShowPartitionsDesc(String tabName, Path resFile, Map<String, String> partSpec) {
this.tabName = tabName;
this.resFile = resFile.toString();
this.partSpec = partSpec;
}
- /**
- * @return the name of the table.
- */
@Explain(displayName = "table", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
public String getTabName() {
return tabName;
}
- /**
- * @param tabName
- * the table whose partitions have to be listed
- */
- public void setTabName(String tabName) {
- this.tabName = tabName;
- }
-
- /**
- * @return the name of the table.
- */
@Explain(displayName = "partSpec", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
public Map<String, String> getPartSpec() {
return partSpec;
}
- /**
- * @param partSpec the partSpec to set.
- */
- public void setPartSpec(Map<String, String> partSpec) {
- this.partSpec = partSpec;
- }
-
- /**
- * @return the results file
- */
@Explain(displayName = "result file", explainLevels = { Level.EXTENDED })
public String getResFile() {
return resFile;
}
-
- /**
- * @param resFile
- * the results file to be used to return the results
- */
- public void setResFile(String resFile) {
- this.resFile = resFile;
- }
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsOperation.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsOperation.java
new file mode 100644
index 0000000..5df9474
--- /dev/null
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/ShowPartitionsOperation.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hadoop.hive.ql.ddl.table.partition;
+
+import java.io.DataOutputStream;
+import java.util.List;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.ddl.DDLOperation;
+import org.apache.hadoop.hive.ql.ddl.DDLOperationContext;
+import org.apache.hadoop.hive.ql.ddl.DDLUtils;
+import org.apache.hadoop.hive.ql.metadata.HiveException;
+import org.apache.hadoop.hive.ql.metadata.Table;
+
+/**
+ * Operation process of showing the partitions of a table.
+ */
+public class ShowPartitionsOperation extends DDLOperation {
+ private final ShowPartitionsDesc desc;
+
+ public ShowPartitionsOperation(DDLOperationContext context, ShowPartitionsDesc desc) {
+ super(context);
+ this.desc = desc;
+ }
+
+ @Override
+ public int execute() throws HiveException {
+ Table tbl = context.getDb().getTable(desc.getTabName());
+ if (!tbl.isPartitioned()) {
+ throw new HiveException(ErrorMsg.TABLE_NOT_PARTITIONED, desc.getTabName());
+ }
+
+ List<String> parts = null;
+ if (desc.getPartSpec() != null) {
+ parts = context.getDb().getPartitionNames(tbl.getDbName(), tbl.getTableName(), desc.getPartSpec(), (short) -1);
+ } else {
+ parts = context.getDb().getPartitionNames(tbl.getDbName(), tbl.getTableName(), (short) -1);
+ }
+
+ // write the results in the file
+ try (DataOutputStream outStream = DDLUtils.getOutputStream(new Path(desc.getResFile()), context)) {
+ context.getFormatter().showTablePartitions(outStream, parts);
+ } catch (Exception e) {
+ throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show partitions for table " + desc.getTabName());
+ }
+
+ return 0;
+ }
+}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/package-info.java
similarity index 76%
copy from ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java
copy to ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/package-info.java
index b59ab6c..180e705 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/partition/package-info.java
@@ -15,12 +15,6 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
-package org.apache.hadoop.hive.ql.exec.repl.bootstrap.events;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-
-public interface PartitionEvent extends TableEvent {
- AddPartitionDesc lastPartitionReplicated();
-
- TableEvent asTableEvent();
-}
+/** Partition related DDL operation descriptions and operations. */
+package org.apache.hadoop.hive.ql.ddl.table.partition;
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
index 529b9c5..0c531be 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/DDLTask.java
@@ -35,13 +35,11 @@ import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FsShell;
import org.apache.hadoop.fs.Path;
-import org.apache.hadoop.hive.common.FileUtils;
import org.apache.hadoop.hive.common.StatsSetupConst;
import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
@@ -50,7 +48,6 @@ import org.apache.hadoop.hive.metastore.HiveMetaHook;
import org.apache.hadoop.hive.metastore.HiveMetaStoreUtils;
import org.apache.hadoop.hive.metastore.Msck;
import org.apache.hadoop.hive.metastore.MsckInfo;
-import org.apache.hadoop.hive.metastore.PartitionDropOptions;
import org.apache.hadoop.hive.metastore.TableType;
import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.CompactionResponse;
@@ -86,12 +83,10 @@ import org.apache.hadoop.hive.ql.io.orc.OrcSerde;
import org.apache.hadoop.hive.ql.io.parquet.serde.ParquetHiveSerDe;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
-import org.apache.hadoop.hive.ql.metadata.InvalidTableException;
import org.apache.hadoop.hive.ql.metadata.Partition;
import org.apache.hadoop.hive.ql.metadata.PartitionIterable;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatUtils;
-import org.apache.hadoop.hive.ql.metadata.formatting.MetaDataFormatter;
import org.apache.hadoop.hive.ql.metadata.formatting.TextMetaDataTable;
import org.apache.hadoop.hive.ql.parse.AlterTablePartMergeFilesDesc;
import org.apache.hadoop.hive.ql.parse.DDLSemanticAnalyzer;
@@ -99,15 +94,11 @@ import org.apache.hadoop.hive.ql.parse.ExplainConfiguration.AnalyzeState;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.repl.dump.Utils;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-import org.apache.hadoop.hive.ql.plan.AlterTableAlterPartDesc;
import org.apache.hadoop.hive.ql.plan.AlterTableDesc;
import org.apache.hadoop.hive.ql.plan.AlterTableDesc.AlterTableTypes;
-import org.apache.hadoop.hive.ql.plan.AlterTableExchangePartition;
import org.apache.hadoop.hive.ql.plan.AlterTableSimpleDesc;
import org.apache.hadoop.hive.ql.plan.CacheMetadataDesc;
import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.FileMergeDesc;
import org.apache.hadoop.hive.ql.plan.InsertCommitHookDesc;
import org.apache.hadoop.hive.ql.plan.ListBucketingCtx;
@@ -117,11 +108,9 @@ import org.apache.hadoop.hive.ql.plan.MsckDesc;
import org.apache.hadoop.hive.ql.plan.OperatorDesc;
import org.apache.hadoop.hive.ql.plan.OrcFileMergeDesc;
import org.apache.hadoop.hive.ql.plan.RCFileMergeDesc;
-import org.apache.hadoop.hive.ql.plan.RenamePartitionDesc;
import org.apache.hadoop.hive.ql.plan.ReplRemoveFirstIncLoadPendFlagDesc;
import org.apache.hadoop.hive.ql.plan.ShowColumnsDesc;
import org.apache.hadoop.hive.ql.plan.ShowConfDesc;
-import org.apache.hadoop.hive.ql.plan.ShowPartitionsDesc;
import org.apache.hadoop.hive.ql.plan.TezWork;
import org.apache.hadoop.hive.ql.plan.api.StageType;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
@@ -132,13 +121,6 @@ import org.apache.hadoop.hive.serde2.avro.AvroSerdeUtils;
import org.apache.hadoop.hive.serde2.columnar.ColumnarSerDe;
import org.apache.hadoop.hive.serde2.dynamic_type.DynamicSerDe;
import org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe;
-import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspector;
-import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters;
-import org.apache.hadoop.hive.serde2.objectinspector.ObjectInspectorConverters.Converter;
-import org.apache.hadoop.hive.serde2.objectinspector.primitive.PrimitiveObjectInspectorFactory;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfo;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoFactory;
-import org.apache.hadoop.hive.serde2.typeinfo.TypeInfoUtils;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.mapreduce.MRJobConfig;
import org.apache.hadoop.tools.HadoopArchives;
@@ -165,8 +147,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
private static String INTERMEDIATE_ORIGINAL_DIR_SUFFIX;
private static String INTERMEDIATE_EXTRACTED_DIR_SUFFIX;
- private MetaDataFormatter formatter;
-
@Override
public boolean requireLock() {
return this.work != null && this.work.getNeedLock();
@@ -183,7 +163,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
// Pick the formatter to use to display the results. Either the
// normal human readable output or a json object.
- formatter = MetaDataFormatUtils.getFormatter(conf);
INTERMEDIATE_ARCHIVED_DIR_SUFFIX =
HiveConf.getVar(conf, ConfVars.METASTORE_INT_ARCHIVED);
INTERMEDIATE_ORIGINAL_DIR_SUFFIX =
@@ -203,12 +182,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
try {
db = Hive.get(conf);
- DropPartitionDesc dropPartition = work.getDropPartitionDesc();
- if (dropPartition != null) {
- dropPartitions(db, dropPartition);
- return 0;
- }
-
AlterTableDesc alterTbl = work.getAlterTblDesc();
if (alterTbl != null) {
if (!allowOperationInReplicationScope(db, alterTbl.getOldName(), null, alterTbl.getReplicationSpec())) {
@@ -226,16 +199,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
}
}
- AddPartitionDesc addPartitionDesc = work.getAddPartitionDesc();
- if (addPartitionDesc != null) {
- return addPartitions(db, addPartitionDesc);
- }
-
- RenamePartitionDesc renamePartitionDesc = work.getRenamePartitionDesc();
- if (renamePartitionDesc != null) {
- return renamePartition(db, renamePartitionDesc);
- }
-
AlterTableSimpleDesc simpleDesc = work.getAlterTblSimpleDesc();
if (simpleDesc != null) {
if (simpleDesc.getType() == AlterTableTypes.TOUCH) {
@@ -259,11 +222,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
return showColumns(db, showCols);
}
- ShowPartitionsDesc showParts = work.getShowPartsDesc();
- if (showParts != null) {
- return showPartitions(db, showParts);
- }
-
ShowConfDesc showConf = work.getShowConfDesc();
if (showConf != null) {
return showConf(db, showConf);
@@ -274,17 +232,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
return mergeFiles(db, mergeFilesDesc, driverContext);
}
- AlterTableAlterPartDesc alterPartDesc = work.getAlterTableAlterPartDesc();
- if(alterPartDesc != null) {
- return alterTableAlterPart(db, alterPartDesc);
- }
-
- AlterTableExchangePartition alterTableExchangePartition =
- work.getAlterTableExchangePartition();
- if (alterTableExchangePartition != null) {
- return exchangeTablePartition(db, alterTableExchangePartition);
- }
-
CacheMetadataDesc cacheMetadataDesc = work.getCacheMetadataDesc();
if (cacheMetadataDesc != null) {
return cacheMetadata(db, cacheMetadataDesc);
@@ -462,170 +409,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
}
/**
- * Add a partitions to a table.
- *
- * @param db
- * Database to add the partition to.
- * @param addPartitionDesc
- * Add these partitions.
- * @return Returns 0 when execution succeeds and above 0 if it fails.
- * @throws HiveException
- */
- private int addPartitions(Hive db, AddPartitionDesc addPartitionDesc) throws HiveException {
- List<Partition> parts = db.createPartitions(addPartitionDesc);
- for (Partition part : parts) {
- addIfAbsentByName(new WriteEntity(part, WriteEntity.WriteType.INSERT));
- }
- return 0;
- }
-
- /**
- * Rename a partition in a table
- *
- * @param db
- * Database to rename the partition.
- * @param renamePartitionDesc
- * rename old Partition to new one.
- * @return Returns 0 when execution succeeds and above 0 if it fails.
- * @throws HiveException
- */
- private int renamePartition(Hive db, RenamePartitionDesc renamePartitionDesc) throws HiveException {
- String tableName = renamePartitionDesc.getTableName();
- LinkedHashMap<String, String> oldPartSpec = renamePartitionDesc.getOldPartSpec();
-
- if (!allowOperationInReplicationScope(db, tableName, oldPartSpec, renamePartitionDesc.getReplicationSpec())) {
- // no rename, the table is missing either due to drop/rename which follows the current rename.
- // or the existing table is newer than our update.
- if (LOG.isDebugEnabled()) {
- LOG.debug("DDLTask: Rename Partition is skipped as table {} / partition {} is newer than update",
- tableName,
- FileUtils.makePartName(new ArrayList<>(oldPartSpec.keySet()), new ArrayList<>(oldPartSpec.values())));
- }
- return 0;
- }
-
- String names[] = Utilities.getDbTableName(tableName);
- if (Utils.isBootstrapDumpInProgress(db, names[0])) {
- LOG.error("DDLTask: Rename Partition not allowed as bootstrap dump in progress");
- throw new HiveException("Rename Partition: Not allowed as bootstrap dump in progress");
- }
-
- Table tbl = db.getTable(tableName);
- Partition oldPart = db.getPartition(tbl, oldPartSpec, false);
- if (oldPart == null) {
- String partName = FileUtils.makePartName(new ArrayList<String>(oldPartSpec.keySet()),
- new ArrayList<String>(oldPartSpec.values()));
- throw new HiveException("Rename partition: source partition [" + partName
- + "] does not exist.");
- }
- Partition part = db.getPartition(tbl, oldPartSpec, false);
- part.setValues(renamePartitionDesc.getNewPartSpec());
- long writeId = renamePartitionDesc.getWriteId();
- if (renamePartitionDesc.getReplicationSpec() != null
- && renamePartitionDesc.getReplicationSpec().isMigratingToTxnTable()) {
- Long tmpWriteId = ReplUtils.getMigrationCurrentTblWriteId(conf);
- if (tmpWriteId == null) {
- throw new HiveException("DDLTask : Write id is not set in the config by open txn task for migration");
- }
- writeId = tmpWriteId;
- }
- db.renamePartition(tbl, oldPartSpec, part, writeId);
- Partition newPart = db.getPartition(tbl, renamePartitionDesc.getNewPartSpec(), false);
- work.getInputs().add(new ReadEntity(oldPart));
- // We've already obtained a lock on the table, don't lock the partition too
- addIfAbsentByName(new WriteEntity(newPart, WriteEntity.WriteType.DDL_NO_LOCK));
- return 0;
- }
-
- /**
- * Alter partition column type in a table
- *
- * @param db
- * Database to rename the partition.
- * @param alterPartitionDesc
- * change partition column type.
- * @return Returns 0 when execution succeeds and above 0 if it fails.
- * @throws HiveException
- */
- private int alterTableAlterPart(Hive db, AlterTableAlterPartDesc alterPartitionDesc)
- throws HiveException {
-
- Table tbl = db.getTable(alterPartitionDesc.getTableName(), true);
-
- // This is checked by DDLSemanticAnalyzer
- assert(tbl.isPartitioned());
-
- List<FieldSchema> newPartitionKeys = new ArrayList<FieldSchema>();
-
- //Check if the existing partition values can be type casted to the new column type
- // with a non null value before trying to alter the partition column type.
- try {
- Set<Partition> partitions = db.getAllPartitionsOf(tbl);
- int colIndex = -1;
- for(FieldSchema col : tbl.getTTable().getPartitionKeys()) {
- colIndex++;
- if (col.getName().compareTo(alterPartitionDesc.getPartKeySpec().getName()) == 0) {
- break;
- }
- }
-
- if (colIndex == -1 || colIndex == tbl.getTTable().getPartitionKeys().size()) {
- throw new HiveException("Cannot find partition column " +
- alterPartitionDesc.getPartKeySpec().getName());
- }
-
- TypeInfo expectedType =
- TypeInfoUtils.getTypeInfoFromTypeString(alterPartitionDesc.getPartKeySpec().getType());
- ObjectInspector outputOI =
- TypeInfoUtils.getStandardWritableObjectInspectorFromTypeInfo(expectedType);
- Converter converter = ObjectInspectorConverters.getConverter(
- PrimitiveObjectInspectorFactory.javaStringObjectInspector, outputOI);
-
- // For all the existing partitions, check if the value can be type casted to a non-null object
- for(Partition part : partitions) {
- if (part.getName().equals(conf.getVar(HiveConf.ConfVars.DEFAULTPARTITIONNAME))) {
- continue;
- }
- try {
- String value = part.getValues().get(colIndex);
- Object convertedValue =
- converter.convert(value);
- if (convertedValue == null) {
- throw new HiveException(" Converting from " + TypeInfoFactory.stringTypeInfo + " to " +
- expectedType + " for value : " + value + " resulted in NULL object");
- }
- } catch (Exception e) {
- throw new HiveException("Exception while converting " +
- TypeInfoFactory.stringTypeInfo + " to " +
- expectedType + " for value : " + part.getValues().get(colIndex));
- }
- }
- } catch(Exception e) {
- throw new HiveException(
- "Exception while checking type conversion of existing partition values to " +
- alterPartitionDesc.getPartKeySpec() + " : " + e.getMessage());
- }
-
- for(FieldSchema col : tbl.getTTable().getPartitionKeys()) {
- if (col.getName().compareTo(alterPartitionDesc.getPartKeySpec().getName()) == 0) {
- newPartitionKeys.add(alterPartitionDesc.getPartKeySpec());
- } else {
- newPartitionKeys.add(col);
- }
- }
-
- tbl.getTTable().setPartitionKeys(newPartitionKeys);
-
- db.alterTable(tbl, false, null, true);
-
- work.getInputs().add(new ReadEntity(tbl));
- // We've already locked the table as the input, don't relock it as the output.
- addIfAbsentByName(new WriteEntity(tbl, WriteEntity.WriteType.DDL_NO_LOCK));
-
- return 0;
- }
-
- /**
* Rewrite the partition's metadata and force the pre/post execute hooks to
* be fired.
*
@@ -1345,48 +1128,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
}
/**
- * Write a list of partitions to a file.
- *
- * @param db
- * The database in question.
- * @param showParts
- * These are the partitions we're interested in.
- * @return Returns 0 when execution succeeds and above 0 if it fails.
- * @throws HiveException
- * Throws this exception if an unexpected error occurs.
- */
- private int showPartitions(Hive db, ShowPartitionsDesc showParts) throws HiveException {
- // get the partitions for the table and populate the output
- String tabName = showParts.getTabName();
- Table tbl = null;
- List<String> parts = null;
-
- tbl = db.getTable(tabName);
-
- if (!tbl.isPartitioned()) {
- throw new HiveException(ErrorMsg.TABLE_NOT_PARTITIONED, tabName);
- }
- if (showParts.getPartSpec() != null) {
- parts = db.getPartitionNames(tbl.getDbName(),
- tbl.getTableName(), showParts.getPartSpec(), (short) -1);
- } else {
- parts = db.getPartitionNames(tbl.getDbName(), tbl.getTableName(), (short) -1);
- }
-
- // write the results in the file
- DataOutputStream outStream = getOutputStream(showParts.getResFile());
- try {
- formatter.showTablePartitions(outStream, parts);
- } catch (Exception e) {
- throw new HiveException(e, ErrorMsg.GENERIC_ERROR, "show partitions for table " + tabName);
- } finally {
- IOUtils.closeStream(outStream);
- }
-
- return 0;
- }
-
- /**
* Write a list of the columns in the table to a file.
*
* @param db
@@ -2188,80 +1929,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
return 0;
}
- /**
- * Drop a given partitions.
- *
- * @param db
- * The database in question.
- * @param dropPartition
- * This is the partition we're dropping.
- * @throws HiveException
- * Throws this exception if an unexpected error occurs.
- */
- private void dropPartitions(Hive db, DropPartitionDesc dropPartition) throws HiveException {
- // We need to fetch the table before it is dropped so that it can be passed to
- // post-execution hook
- Table tbl = null;
- try {
- tbl = db.getTable(dropPartition.getTableName());
- } catch (InvalidTableException e) {
- // drop table is idempotent
- }
-
- ReplicationSpec replicationSpec = dropPartition.getReplicationSpec();
- if (replicationSpec.isInReplicationScope()){
- /**
- * ALTER TABLE DROP PARTITION ... FOR REPLICATION(x) behaves as a DROP PARTITION IF OLDER THAN x
- *
- * So, we check each partition that matches our DropTableDesc.getPartSpecs(), and drop it only
- * if it's older than the event that spawned this replicated request to drop partition
- */
- // TODO: Current implementation of replication will result in DROP_PARTITION under replication
- // scope being called per-partition instead of multiple partitions. However, to be robust, we
- // must still handle the case of multiple partitions in case this assumption changes in the
- // future. However, if this assumption changes, we will not be very performant if we fetch
- // each partition one-by-one, and then decide on inspection whether or not this is a candidate
- // for dropping. Thus, we need a way to push this filter (replicationSpec.allowEventReplacementInto)
- // to the metastore to allow it to do drop a partition or not, depending on a Predicate on the
- // parameter key values.
-
- if (tbl == null) {
- // If table is missing, then partitions are also would've been dropped. Just no-op.
- return;
- }
-
- for (DropPartitionDesc.PartSpec partSpec : dropPartition.getPartSpecs()){
- List<Partition> partitions = new ArrayList<>();
- try {
- db.getPartitionsByExpr(tbl, partSpec.getPartSpec(), conf, partitions);
- for (Partition p : Iterables.filter(partitions,
- replicationSpec.allowEventReplacementInto())){
- db.dropPartition(tbl.getDbName(),tbl.getTableName(),p.getValues(),true);
- }
- } catch (NoSuchObjectException e){
- // ignore NSOE because that means there's nothing to drop.
- } catch (Exception e) {
- throw new HiveException(e.getMessage(), e);
- }
- }
- return;
- }
-
- // ifExists is currently verified in DDLSemanticAnalyzer
- List<Partition> droppedParts
- = db.dropPartitions(dropPartition.getTableName(),
- dropPartition.getPartSpecs(),
- PartitionDropOptions.instance()
- .deleteData(true)
- .ifExists(true)
- .purgeData(dropPartition.getIfPurge()));
- for (Partition partition : droppedParts) {
- console.printInfo("Dropped the partition " + partition.getName());
- // We have already locked the table, don't lock the partitions.
- addIfAbsentByName(new WriteEntity(partition, WriteEntity.WriteType.DDL_NO_LOCK));
- }
- }
-
/**
* Update last_modified_by and last_modified_time parameters in parameter map.
*
@@ -2294,30 +1961,6 @@ public class DDLTask extends Task<DDLWork> implements Serializable {
}
}
- private int exchangeTablePartition(Hive db,
- AlterTableExchangePartition exchangePartition) throws HiveException {
- Map<String, String> partitionSpecs = exchangePartition.getPartitionSpecs();
- Table destTable = exchangePartition.getDestinationTable();
- Table sourceTable = exchangePartition.getSourceTable();
- List<Partition> partitions =
- db.exchangeTablePartitions(partitionSpecs, sourceTable.getDbName(),
- sourceTable.getTableName(),destTable.getDbName(),
- destTable.getTableName());
-
- for(Partition partition : partitions) {
- // Reuse the partition specs from dest partition since they should be the same
- work.getInputs().add(new ReadEntity(new Partition(sourceTable, partition.getSpec(), null)));
-
- addIfAbsentByName(new WriteEntity(new Partition(sourceTable, partition.getSpec(), null),
- WriteEntity.WriteType.DELETE));
-
- addIfAbsentByName(new WriteEntity(new Partition(destTable, partition.getSpec(), null),
- WriteEntity.WriteType.INSERT));
- }
-
- return 0;
- }
-
@Override
public StageType getType() {
return StageType.DDL;
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java
index b59ab6c..251193e 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/PartitionEvent.java
@@ -17,10 +17,10 @@
*/
package org.apache.hadoop.hive.ql.exec.repl.bootstrap.events;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
public interface PartitionEvent extends TableEvent {
- AddPartitionDesc lastPartitionReplicated();
+ AlterTableAddPartitionDesc lastPartitionReplicated();
TableEvent asTableEvent();
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/TableEvent.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/TableEvent.java
index 3dcc1d7..992a4ca 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/TableEvent.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/TableEvent.java
@@ -18,9 +18,9 @@
package org.apache.hadoop.hive.ql.exec.repl.bootstrap.events;
import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ImportTableDesc;
import java.util.List;
@@ -28,7 +28,7 @@ import java.util.List;
public interface TableEvent extends BootstrapEvent {
ImportTableDesc tableDesc(String dbName) throws SemanticException;
- List<AddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
+ List<AlterTableAddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
throws SemanticException;
List<String> partitions(ImportTableDesc tblDesc)
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSPartitionEvent.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSPartitionEvent.java
index ee804e8..0c27a99 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSPartitionEvent.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSPartitionEvent.java
@@ -19,12 +19,12 @@ package org.apache.hadoop.hive.ql.exec.repl.bootstrap.events.filesystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.hive.ql.exec.repl.bootstrap.events.PartitionEvent;
import org.apache.hadoop.hive.ql.exec.repl.bootstrap.events.TableEvent;
import org.apache.hadoop.hive.ql.exec.repl.bootstrap.load.ReplicationState;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ImportTableDesc;
import java.util.List;
@@ -46,7 +46,7 @@ public class FSPartitionEvent implements PartitionEvent {
}
@Override
- public AddPartitionDesc lastPartitionReplicated() {
+ public AlterTableAddPartitionDesc lastPartitionReplicated() {
assert replicationState != null && replicationState.partitionState != null;
return replicationState.partitionState.lastReplicatedPartition;
}
@@ -62,7 +62,7 @@ public class FSPartitionEvent implements PartitionEvent {
}
@Override
- public List<AddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
+ public List<AlterTableAddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
throws SemanticException {
return tableEvent.partitionDescriptions(tblDesc);
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSTableEvent.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSTableEvent.java
index 27009f0..64f9af3 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSTableEvent.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/events/filesystem/FSTableEvent.java
@@ -27,6 +27,7 @@ import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
import org.apache.hadoop.hive.metastore.api.MetaException;
import org.apache.hadoop.hive.metastore.api.Partition;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.hive.ql.exec.repl.bootstrap.events.TableEvent;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
import org.apache.hadoop.hive.ql.io.AcidUtils;
@@ -36,7 +37,6 @@ import org.apache.hadoop.hive.ql.parse.EximUtil;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.repl.load.MetaData;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ImportTableDesc;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
import org.apache.hadoop.hive.ql.util.HiveStrictManagedMigration;
@@ -140,13 +140,13 @@ public class FSTableEvent implements TableEvent {
}
@Override
- public List<AddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
+ public List<AlterTableAddPartitionDesc> partitionDescriptions(ImportTableDesc tblDesc)
throws SemanticException {
- List<AddPartitionDesc> descs = new ArrayList<>();
+ List<AlterTableAddPartitionDesc> descs = new ArrayList<>();
//TODO: if partitions are loaded lazily via the iterator then we will have to avoid conversion of everything here as it defeats the purpose.
for (Partition partition : metadata.getPartitions()) {
// TODO: this should ideally not create AddPartitionDesc per partition
- AddPartitionDesc partsDesc = partitionDesc(fromPath, tblDesc, partition);
+ AlterTableAddPartitionDesc partsDesc = partitionDesc(fromPath, tblDesc, partition);
descs.add(partsDesc);
}
return descs;
@@ -167,14 +167,14 @@ public class FSTableEvent implements TableEvent {
return partitions;
}
- private AddPartitionDesc partitionDesc(Path fromPath,
+ private AlterTableAddPartitionDesc partitionDesc(Path fromPath,
ImportTableDesc tblDesc, Partition partition) throws SemanticException {
try {
- AddPartitionDesc partsDesc =
- new AddPartitionDesc(tblDesc.getDatabaseName(), tblDesc.getTableName(),
+ AlterTableAddPartitionDesc partsDesc =
+ new AlterTableAddPartitionDesc(tblDesc.getDatabaseName(), tblDesc.getTableName(),
EximUtil.makePartSpec(tblDesc.getPartCols(), partition.getValues()),
partition.getSd().getLocation(), partition.getParameters());
- AddPartitionDesc.OnePartitionDesc partDesc = partsDesc.getPartition(0);
+ AlterTableAddPartitionDesc.PartitionDesc partDesc = partsDesc.getPartition(0);
partDesc.setInputFormat(partition.getSd().getInputFormat());
partDesc.setOutputFormat(partition.getSd().getOutputFormat());
partDesc.setNumBuckets(partition.getSd().getNumBuckets());
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/ReplicationState.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/ReplicationState.java
index 5a4dc4c..e15dec3 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/ReplicationState.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/ReplicationState.java
@@ -17,17 +17,17 @@
*/
package org.apache.hadoop.hive.ql.exec.repl.bootstrap.load;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-
import java.io.Serializable;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
+
public class ReplicationState implements Serializable {
public static class PartitionState {
final String tableName;
- public final AddPartitionDesc lastReplicatedPartition;
+ public final AlterTableAddPartitionDesc lastReplicatedPartition;
- public PartitionState(String tableName, AddPartitionDesc lastReplicatedPartition) {
+ public PartitionState(String tableName, AlterTableAddPartitionDesc lastReplicatedPartition) {
this.tableName = tableName;
this.lastReplicatedPartition = lastReplicatedPartition;
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/table/LoadPartitions.java b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/table/LoadPartitions.java
index 0add38b..6e19cb4 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/table/LoadPartitions.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/exec/repl/bootstrap/load/table/LoadPartitions.java
@@ -23,6 +23,9 @@ import org.apache.hadoop.hive.metastore.Warehouse;
import org.apache.hadoop.hive.metastore.api.Database;
import org.apache.hadoop.hive.metastore.api.InvalidOperationException;
import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.ql.ddl.DDLWork2;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableDropPartitionDesc;
import org.apache.hadoop.hive.ql.exec.ReplCopyTask;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
@@ -42,9 +45,6 @@ import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.ImportSemanticAnalyzer;
import org.apache.hadoop.hive.ql.parse.SemanticException;
import org.apache.hadoop.hive.ql.parse.repl.ReplLogger;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import org.apache.hadoop.hive.ql.plan.ImportTableDesc;
import org.apache.hadoop.hive.ql.plan.LoadMultiFilesDesc;
@@ -76,7 +76,7 @@ public class LoadPartitions {
private final TableContext tableContext;
private final TableEvent event;
private final TaskTracker tracker;
- private final AddPartitionDesc lastReplicatedPartition;
+ private final AlterTableAddPartitionDesc lastReplicatedPartition;
private final ImportTableDesc tableDesc;
private Table table;
@@ -89,7 +89,7 @@ public class LoadPartitions {
public LoadPartitions(Context context, ReplLogger replLogger, TableContext tableContext,
TaskTracker limiter, TableEvent event, String dbNameToLoadIn,
- AddPartitionDesc lastReplicatedPartition) throws HiveException {
+ AlterTableAddPartitionDesc lastReplicatedPartition) throws HiveException {
this.tracker = new TaskTracker(limiter);
this.event = event;
this.context = context;
@@ -126,7 +126,7 @@ public class LoadPartitions {
} else {
// existing
if (table.isPartitioned()) {
- List<AddPartitionDesc> partitionDescs = event.partitionDescriptions(tableDesc);
+ List<AlterTableAddPartitionDesc> partitionDescs = event.partitionDescriptions(tableDesc);
if (!event.replicationSpec().isMetadataOnly() && !partitionDescs.isEmpty()) {
updateReplicationState(initialReplicationState());
if (!forExistingTable(lastReplicatedPartition).hasReplicationState()) {
@@ -155,9 +155,9 @@ public class LoadPartitions {
}
private TaskTracker forNewTable() throws Exception {
- Iterator<AddPartitionDesc> iterator = event.partitionDescriptions(tableDesc).iterator();
+ Iterator<AlterTableAddPartitionDesc> iterator = event.partitionDescriptions(tableDesc).iterator();
while (iterator.hasNext() && tracker.canAddMoreTasks()) {
- AddPartitionDesc currentPartitionDesc = iterator.next();
+ AlterTableAddPartitionDesc currentPartitionDesc = iterator.next();
/*
the currentPartitionDesc cannot be inlined as we need the hasNext() to be evaluated post the
current retrieved lastReplicatedPartition
@@ -167,7 +167,7 @@ public class LoadPartitions {
return tracker;
}
- private void addPartition(boolean hasMorePartitions, AddPartitionDesc addPartitionDesc, Task<?> ptnRootTask)
+ private void addPartition(boolean hasMorePartitions, AlterTableAddPartitionDesc addPartitionDesc, Task<?> ptnRootTask)
throws Exception {
tracker.addTask(tasksForAddPartition(table, addPartitionDesc, ptnRootTask));
if (hasMorePartitions && !tracker.canAddMoreTasks()) {
@@ -180,9 +180,9 @@ public class LoadPartitions {
/**
* returns the root task for adding a partition
*/
- private Task<?> tasksForAddPartition(Table table, AddPartitionDesc addPartitionDesc, Task<?> ptnRootTask)
+ private Task<?> tasksForAddPartition(Table table, AlterTableAddPartitionDesc addPartitionDesc, Task<?> ptnRootTask)
throws MetaException, HiveException {
- AddPartitionDesc.OnePartitionDesc partSpec = addPartitionDesc.getPartition(0);
+ AlterTableAddPartitionDesc.PartitionDesc partSpec = addPartitionDesc.getPartition(0);
Path sourceWarehousePartitionLocation = new Path(partSpec.getLocation());
Path replicaWarehousePartitionLocation = locationOnReplicaWarehouse(table, partSpec);
partSpec.setLocation(replicaWarehousePartitionLocation.toString());
@@ -191,7 +191,7 @@ public class LoadPartitions {
+ partSpec.getLocation());
Task<?> addPartTask = TaskFactory.get(
- new DDLWork(new HashSet<>(), new HashSet<>(), addPartitionDesc),
+ new DDLWork2(new HashSet<>(), new HashSet<>(), addPartitionDesc),
context.hiveConf
);
@@ -273,7 +273,7 @@ public class LoadPartitions {
/**
* This will create the move of partition data from temp path to actual path
*/
- private Task<?> movePartitionTask(Table table, AddPartitionDesc.OnePartitionDesc partSpec, Path tmpPath,
+ private Task<?> movePartitionTask(Table table, AlterTableAddPartitionDesc.PartitionDesc partSpec, Path tmpPath,
LoadFileType loadFileType) {
MoveWork moveWork = new MoveWork(new HashSet<>(), new HashSet<>(), null, null, false);
if (AcidUtils.isTransactionalTable(table)) {
@@ -318,7 +318,7 @@ public class LoadPartitions {
* path will always be a child on target.
*/
- private Path locationOnReplicaWarehouse(Table table, AddPartitionDesc.OnePartitionDesc partSpec)
+ private Path locationOnReplicaWarehouse(Table table, AlterTableAddPartitionDesc.PartitionDesc partSpec)
throws MetaException, HiveException {
String child = Warehouse.makePartPath(partSpec.getPartSpec());
if (tableDesc.isExternal()) {
@@ -345,20 +345,20 @@ public class LoadPartitions {
}
private Task<?> dropPartitionTask(Table table, Map<String, String> partSpec) throws SemanticException {
- Task<DDLWork> dropPtnTask = null;
+ Task<DDLWork2> dropPtnTask = null;
Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecsExpr =
ReplUtils.genPartSpecs(table, Collections.singletonList(partSpec));
if (partSpecsExpr.size() > 0) {
- DropPartitionDesc dropPtnDesc = new DropPartitionDesc(table.getFullyQualifiedName(), partSpecsExpr, true,
- event.replicationSpec());
+ AlterTableDropPartitionDesc dropPtnDesc = new AlterTableDropPartitionDesc(table.getFullyQualifiedName(),
+ partSpecsExpr, true, event.replicationSpec());
dropPtnTask = TaskFactory.get(
- new DDLWork(new HashSet<>(), new HashSet<>(), dropPtnDesc), context.hiveConf
+ new DDLWork2(new HashSet<>(), new HashSet<>(), dropPtnDesc), context.hiveConf
);
}
return dropPtnTask;
}
- private TaskTracker forExistingTable(AddPartitionDesc lastPartitionReplicated) throws Exception {
+ private TaskTracker forExistingTable(AlterTableAddPartitionDesc lastPartitionReplicated) throws Exception {
boolean encounteredTheLastReplicatedPartition = (lastPartitionReplicated == null);
Map<String, String> lastReplicatedPartSpec = null;
if (!encounteredTheLastReplicatedPartition) {
@@ -367,15 +367,15 @@ public class LoadPartitions {
StringUtils.mapToString(lastReplicatedPartSpec));
}
- Iterator<AddPartitionDesc> partitionIterator = event.partitionDescriptions(tableDesc).iterator();
+ Iterator<AlterTableAddPartitionDesc> partitionIterator = event.partitionDescriptions(tableDesc).iterator();
while (!encounteredTheLastReplicatedPartition && partitionIterator.hasNext()) {
- AddPartitionDesc addPartitionDesc = partitionIterator.next();
+ AlterTableAddPartitionDesc addPartitionDesc = partitionIterator.next();
Map<String, String> currentSpec = addPartitionDesc.getPartition(0).getPartSpec();
encounteredTheLastReplicatedPartition = lastReplicatedPartSpec.equals(currentSpec);
}
while (partitionIterator.hasNext() && tracker.canAddMoreTasks()) {
- AddPartitionDesc addPartitionDesc = partitionIterator.next();
+ AlterTableAddPartitionDesc addPartitionDesc = partitionIterator.next();
Map<String, String> partSpec = addPartitionDesc.getPartition(0).getPartSpec();
Task<?> ptnRootTask = null;
ReplLoadOpType loadPtnType = getLoadPartitionType(partSpec);
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
index 27ec7dc..769522d 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/metadata/Hive.java
@@ -112,6 +112,8 @@ import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
import org.apache.hadoop.hive.ql.ErrorMsg;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableDropPartitionDesc;
import org.apache.hadoop.hive.ql.exec.AbstractFileMergeOperator;
import org.apache.hadoop.hive.ql.exec.FunctionRegistry;
import org.apache.hadoop.hive.ql.exec.FunctionTask;
@@ -127,8 +129,6 @@ import org.apache.hadoop.hive.ql.log.PerfLogger;
import org.apache.hadoop.hive.ql.optimizer.calcite.RelOptHiveTable;
import org.apache.hadoop.hive.ql.optimizer.calcite.rules.views.HiveAugmentMaterializationRule;
import org.apache.hadoop.hive.ql.optimizer.listbucketingpruner.ListBucketingPrunerUtils;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
@@ -2992,7 +2992,7 @@ private void constructOneLBLocationMap(FileStatus fSta,
}
}
- public List<Partition> createPartitions(AddPartitionDesc addPartitionDesc) throws HiveException {
+ public List<Partition> createPartitions(AlterTableAddPartitionDesc addPartitionDesc) throws HiveException {
// TODO: catalog name everywhere in this method
Table tbl = getTable(addPartitionDesc.getDbName(), addPartitionDesc.getTableName());
int size = addPartitionDesc.getPartitionCount();
@@ -3086,7 +3086,7 @@ private void constructOneLBLocationMap(FileStatus fSta,
}
public static org.apache.hadoop.hive.metastore.api.Partition convertAddSpecToMetaPartition(
- Table tbl, AddPartitionDesc.OnePartitionDesc addSpec, final HiveConf conf) throws HiveException {
+ Table tbl, AlterTableAddPartitionDesc.PartitionDesc addSpec, final HiveConf conf) throws HiveException {
Path location = addSpec.getLocation() != null
? new Path(tbl.getPath(), addSpec.getLocation()) : null;
if (location != null) {
@@ -3445,7 +3445,7 @@ private void constructOneLBLocationMap(FileStatus fSta,
public List<Partition> dropPartitions(Table table, List<String>partDirNames,
boolean deleteData, boolean ifExists) throws HiveException {
// partitions to be dropped in this batch
- List<DropPartitionDesc.PartSpec> partSpecs = new ArrayList<>(partDirNames.size());
+ List<AlterTableDropPartitionDesc.PartitionDesc> partSpecs = new ArrayList<>(partDirNames.size());
// parts of the partition
String[] parts = null;
@@ -3495,7 +3495,7 @@ private void constructOneLBLocationMap(FileStatus fSta,
}
// Add the expression to partition specification
- partSpecs.add(new DropPartitionDesc.PartSpec(expr, partSpecKey));
+ partSpecs.add(new AlterTableDropPartitionDesc.PartitionDesc(expr, partSpecKey));
// Increment dropKey to get a new key for hash map
++partSpecKey;
@@ -3505,14 +3505,14 @@ private void constructOneLBLocationMap(FileStatus fSta,
return dropPartitions(names[0], names[1], partSpecs, deleteData, ifExists);
}
- public List<Partition> dropPartitions(String tblName, List<DropPartitionDesc.PartSpec> partSpecs,
+ public List<Partition> dropPartitions(String tblName, List<AlterTableDropPartitionDesc.PartitionDesc> partSpecs,
boolean deleteData, boolean ifExists) throws HiveException {
String[] names = Utilities.getDbTableName(tblName);
return dropPartitions(names[0], names[1], partSpecs, deleteData, ifExists);
}
public List<Partition> dropPartitions(String dbName, String tblName,
- List<DropPartitionDesc.PartSpec> partSpecs, boolean deleteData,
+ List<AlterTableDropPartitionDesc.PartitionDesc> partSpecs, boolean deleteData,
boolean ifExists) throws HiveException {
return dropPartitions(dbName, tblName, partSpecs,
PartitionDropOptions.instance()
@@ -3520,19 +3520,20 @@ private void constructOneLBLocationMap(FileStatus fSta,
.ifExists(ifExists));
}
- public List<Partition> dropPartitions(String tblName, List<DropPartitionDesc.PartSpec> partSpecs,
+ public List<Partition> dropPartitions(String tblName, List<AlterTableDropPartitionDesc.PartitionDesc> partSpecs,
PartitionDropOptions dropOptions) throws HiveException {
String[] names = Utilities.getDbTableName(tblName);
return dropPartitions(names[0], names[1], partSpecs, dropOptions);
}
public List<Partition> dropPartitions(String dbName, String tblName,
- List<DropPartitionDesc.PartSpec> partSpecs, PartitionDropOptions dropOptions) throws HiveException {
+ List<AlterTableDropPartitionDesc.PartitionDesc> partSpecs, PartitionDropOptions dropOptions)
+ throws HiveException {
try {
Table tbl = getTable(dbName, tblName);
List<org.apache.hadoop.hive.metastore.utils.ObjectPair<Integer, byte[]>> partExprs =
new ArrayList<>(partSpecs.size());
- for (DropPartitionDesc.PartSpec partSpec : partSpecs) {
+ for (AlterTableDropPartitionDesc.PartitionDesc partSpec : partSpecs) {
partExprs.add(new org.apache.hadoop.hive.metastore.utils.ObjectPair<>(partSpec.getPrefixLength(),
SerializationUtilities.serializeExpressionToKryo(partSpec.getPartSpec())));
}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
index 3bf2a43..99d7f21 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/DDLSemanticAnalyzer.java
@@ -101,6 +101,13 @@ import org.apache.hadoop.hive.ql.ddl.table.lock.LockTableDesc;
import org.apache.hadoop.hive.ql.ddl.table.lock.ShowLocksDesc;
import org.apache.hadoop.hive.ql.ddl.table.lock.UnlockTableDesc;
import org.apache.hadoop.hive.ql.ddl.table.misc.TruncateTableDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAlterPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableDropPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableExchangePartitionsDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableRenamePartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.ShowPartitionsDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc.PartitionDesc;
import org.apache.hadoop.hive.ql.ddl.view.AlterMaterializedViewRewriteDesc;
import org.apache.hadoop.hive.ql.ddl.workloadmanagement.AlterPoolAddTriggerDesc;
import org.apache.hadoop.hive.ql.ddl.workloadmanagement.AlterPoolDropTriggerDesc;
@@ -145,12 +152,8 @@ import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.authorization.AuthorizationParseUtils;
import org.apache.hadoop.hive.ql.parse.authorization.HiveAuthorizationTaskFactory;
import org.apache.hadoop.hive.ql.parse.authorization.HiveAuthorizationTaskFactoryImpl;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc.OnePartitionDesc;
-import org.apache.hadoop.hive.ql.plan.AlterTableAlterPartDesc;
import org.apache.hadoop.hive.ql.plan.AlterTableDesc;
import org.apache.hadoop.hive.ql.plan.AlterTableDesc.AlterTableTypes;
-import org.apache.hadoop.hive.ql.plan.AlterTableExchangePartition;
import org.apache.hadoop.hive.ql.plan.AlterTableSimpleDesc;
import org.apache.hadoop.hive.ql.plan.BasicStatsWork;
import org.apache.hadoop.hive.ql.plan.CacheMetadataDesc;
@@ -158,7 +161,6 @@ import org.apache.hadoop.hive.ql.plan.ColumnStatsUpdateWork;
import org.apache.hadoop.hive.ql.plan.DDLDesc;
import org.apache.hadoop.hive.ql.plan.DDLDesc.DDLDescWithWriteId;
import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeColumnDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeConstantDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeDesc;
@@ -169,10 +171,8 @@ import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
import org.apache.hadoop.hive.ql.plan.MoveWork;
import org.apache.hadoop.hive.ql.plan.MsckDesc;
import org.apache.hadoop.hive.ql.plan.PlanUtils;
-import org.apache.hadoop.hive.ql.plan.RenamePartitionDesc;
import org.apache.hadoop.hive.ql.plan.ShowColumnsDesc;
import org.apache.hadoop.hive.ql.plan.ShowConfDesc;
-import org.apache.hadoop.hive.ql.plan.ShowPartitionsDesc;
import org.apache.hadoop.hive.ql.plan.StatsWork;
import org.apache.hadoop.hive.ql.plan.TableDesc;
import org.apache.hadoop.hive.ql.session.SessionState;
@@ -868,10 +868,9 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
// If any destination partition is present then throw a Semantic Exception.
throw new SemanticException(ErrorMsg.PARTITION_EXISTS.getMsg(destPartitions.toString()));
}
- AlterTableExchangePartition alterTableExchangePartition =
- new AlterTableExchangePartition(sourceTable, destTable, partSpecs);
- rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(),
- alterTableExchangePartition)));
+ AlterTableExchangePartitionsDesc alterTableExchangePartition =
+ new AlterTableExchangePartitionsDesc(sourceTable, destTable, partSpecs);
+ rootTasks.add(TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), alterTableExchangePartition)));
inputs.add(new ReadEntity(sourceTable));
outputs.add(new WriteEntity(destTable, WriteType.DDL_SHARED));
@@ -2617,9 +2616,8 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
showPartsDesc = new ShowPartitionsDesc(tableName, ctx.getResFile(), partSpec);
inputs.add(new ReadEntity(getTable(tableName)));
- rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(),
- showPartsDesc)));
- setFetchTask(createFetchTask(showPartsDesc.getSchema()));
+ rootTasks.add(TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), showPartsDesc)));
+ setFetchTask(createFetchTask(ShowPartitionsDesc.SCHEMA));
}
private void analyzeShowCreateDatabase(ASTNode ast) throws SemanticException {
@@ -3322,13 +3320,12 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
partSpecs.add(oldPartSpec);
partSpecs.add(newPartSpec);
addTablePartsOutputs(tab, partSpecs, WriteEntity.WriteType.DDL_EXCLUSIVE);
- RenamePartitionDesc renamePartitionDesc = new RenamePartitionDesc(
- tblName, oldPartSpec, newPartSpec, null, tab);
+ AlterTableRenamePartitionDesc renamePartitionDesc = new AlterTableRenamePartitionDesc(tblName, oldPartSpec,
+ newPartSpec, null, tab);
if (AcidUtils.isTransactionalTable(tab)) {
setAcidDdlDesc(renamePartitionDesc);
}
- rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(),
- renamePartitionDesc)));
+ rootTasks.add(TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), renamePartitionDesc)));
}
private void analyzeAlterTableBucketNum(ASTNode ast, String tblName,
@@ -3420,9 +3417,9 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
addTableDropPartsOutputs(tab, partSpecs.values(), !ifExists);
- DropPartitionDesc dropTblDesc =
- new DropPartitionDesc(getDotName(qualified), partSpecs, mustPurge, replicationSpec);
- rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(), dropTblDesc)));
+ AlterTableDropPartitionDesc dropTblDesc =
+ new AlterTableDropPartitionDesc(getDotName(qualified), partSpecs, mustPurge, replicationSpec);
+ rootTasks.add(TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), dropTblDesc)));
}
private void analyzeAlterTablePartColType(String[] qualified, ASTNode ast)
@@ -3467,14 +3464,13 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
throw new SemanticException(ErrorMsg.INVALID_COLUMN.getMsg(newCol.getName()));
}
- AlterTableAlterPartDesc alterTblAlterPartDesc =
- new AlterTableAlterPartDesc(getDotName(qualified), newCol);
+ AlterTableAlterPartitionDesc alterTblAlterPartDesc =
+ new AlterTableAlterPartitionDesc(getDotName(qualified), newCol);
if (AcidUtils.isTransactionalTable(tab)) {
setAcidDdlDesc(alterTblAlterPartDesc);
}
- rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(),
- alterTblAlterPartDesc)));
+ rootTasks.add(TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), alterTblAlterPartDesc)));
}
/**
@@ -3513,8 +3509,8 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
String currentLocation = null;
Map<String, String> currentPart = null;
// Parser has done some verification, so the order of tokens doesn't need to be verified here.
- AddPartitionDesc addPartitionDesc =
- new AddPartitionDesc(tab.getDbName(), tab.getTableName(), ifNotExists);
+ AlterTableAddPartitionDesc addPartitionDesc =
+ new AlterTableAddPartitionDesc(tab.getDbName(), tab.getTableName(), ifNotExists);
for (int num = start; num < numCh; num++) {
ASTNode child = (ASTNode) ast.getChild(num);
switch (child.getToken().getType()) {
@@ -3546,7 +3542,7 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
if (this.conf.getBoolVar(HiveConf.ConfVars.HIVESTATSAUTOGATHER)) {
for (int index = 0; index < addPartitionDesc.getPartitionCount(); index++) {
- OnePartitionDesc desc = addPartitionDesc.getPartition(index);
+ PartitionDesc desc = addPartitionDesc.getPartition(index);
if (desc.getLocation() == null) {
if (desc.getPartParams() == null) {
desc.setPartParams(new HashMap<String, String>());
@@ -3562,8 +3558,8 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
return;
}
- Task<DDLWork> ddlTask =
- TaskFactory.get(new DDLWork(getInputs(), getOutputs(), addPartitionDesc));
+ Task<DDLWork2> ddlTask =
+ TaskFactory.get(new DDLWork2(getInputs(), getOutputs(), addPartitionDesc));
rootTasks.add(ddlTask);
handleTransactionalTable(tab, addPartitionDesc, ddlTask);
@@ -3577,7 +3573,7 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
cmd.append(" WHERE ");
boolean firstOr = true;
for (int i = 0; i < addPartitionDesc.getPartitionCount(); ++i) {
- AddPartitionDesc.OnePartitionDesc partitionDesc = addPartitionDesc.getPartition(i);
+ AlterTableAddPartitionDesc.PartitionDesc partitionDesc = addPartitionDesc.getPartition(i);
if (firstOr) {
firstOr = false;
} else {
@@ -3614,7 +3610,7 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
* Add partition for Transactional tables needs to add (copy/rename) the data so that it lands
* in a delta_x_x/ folder in the partition dir.
*/
- private void handleTransactionalTable(Table tab, AddPartitionDesc addPartitionDesc,
+ private void handleTransactionalTable(Table tab, AlterTableAddPartitionDesc addPartitionDesc,
Task ddlTask) throws SemanticException {
if(!AcidUtils.isTransactionalTable(tab)) {
return;
@@ -3623,7 +3619,7 @@ public class DDLSemanticAnalyzer extends BaseSemanticAnalyzer {
int stmtId = 0;
for (int index = 0; index < addPartitionDesc.getPartitionCount(); index++) {
- OnePartitionDesc desc = addPartitionDesc.getPartition(index);
+ PartitionDesc desc = addPartitionDesc.getPartition(index);
if (desc.getLocation() != null) {
AcidUtils.validateAcidPartitionLocation(desc.getLocation(), conf);
if(addPartitionDesc.isIfNotExists()) {
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
index 38d9940..4225b7b 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/ImportSemanticAnalyzer.java
@@ -39,6 +39,7 @@ import org.apache.hadoop.hive.metastore.txn.TxnUtils;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.ddl.DDLWork2;
import org.apache.hadoop.hive.ql.ddl.table.creation.DropTableDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.hive.ql.exec.ReplCopyTask;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
@@ -55,10 +56,8 @@ import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.repl.DumpType;
import org.apache.hadoop.hive.ql.parse.repl.load.MetaData;
import org.apache.hadoop.hive.ql.parse.repl.load.UpdatedMetaDataTracker;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
import org.apache.hadoop.hive.ql.plan.CopyWork;
import org.apache.hadoop.hive.ql.plan.ImportTableDesc;
-import org.apache.hadoop.hive.ql.plan.DDLWork;
import org.apache.hadoop.hive.ql.plan.LoadTableDesc;
import org.apache.hadoop.hive.ql.plan.LoadMultiFilesDesc;
import org.apache.hadoop.hive.ql.plan.LoadTableDesc.LoadFileType;
@@ -327,11 +326,11 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
tblDesc.setTableName(parsedTableName);
}
- List<AddPartitionDesc> partitionDescs = new ArrayList<>();
+ List<AlterTableAddPartitionDesc> partitionDescs = new ArrayList<>();
Iterable<Partition> partitions = rv.getPartitions();
for (Partition partition : partitions) {
// TODO: this should ideally not create AddPartitionDesc per partition
- AddPartitionDesc partsDesc =
+ AlterTableAddPartitionDesc partsDesc =
getBaseAddPartitionDescFromPartition(fromPath, dbname, tblDesc, partition,
replicationSpec, x.getConf());
partitionDescs.add(partsDesc);
@@ -341,9 +340,9 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
// The import specification asked for only a particular partition to be loaded
// We load only that, and ignore all the others.
boolean found = false;
- for (Iterator<AddPartitionDesc> partnIter = partitionDescs
+ for (Iterator<AlterTableAddPartitionDesc> partnIter = partitionDescs
.listIterator(); partnIter.hasNext(); ) {
- AddPartitionDesc addPartitionDesc = partnIter.next();
+ AlterTableAddPartitionDesc addPartitionDesc = partnIter.next();
if (!found && addPartitionDesc.getPartition(0).getPartSpec().equals(parsedPartSpec)) {
found = true;
} else {
@@ -363,7 +362,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
throw new SemanticException(ErrorMsg.NEED_TABLE_SPECIFICATION.getMsg());
} else {
x.getConf().set("import.destination.table", tblDesc.getTableName());
- for (AddPartitionDesc addPartitionDesc : partitionDescs) {
+ for (AlterTableAddPartitionDesc addPartitionDesc : partitionDescs) {
addPartitionDesc.setTableName(tblDesc.getTableName());
}
}
@@ -411,14 +410,14 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
return tableExists;
}
- private static AddPartitionDesc getBaseAddPartitionDescFromPartition(
+ private static AlterTableAddPartitionDesc getBaseAddPartitionDescFromPartition(
Path fromPath, String dbName, ImportTableDesc tblDesc, Partition partition,
ReplicationSpec replicationSpec, HiveConf conf)
throws MetaException, SemanticException {
- AddPartitionDesc partsDesc = new AddPartitionDesc(dbName, tblDesc.getTableName(),
+ AlterTableAddPartitionDesc partsDesc = new AlterTableAddPartitionDesc(dbName, tblDesc.getTableName(),
EximUtil.makePartSpec(tblDesc.getPartCols(), partition.getValues()),
partition.getSd().getLocation(), partition.getParameters());
- AddPartitionDesc.OnePartitionDesc partDesc = partsDesc.getPartition(0);
+ AlterTableAddPartitionDesc.PartitionDesc partDesc = partsDesc.getPartition(0);
partDesc.setInputFormat(partition.getSd().getInputFormat());
partDesc.setOutputFormat(partition.getSd().getOutputFormat());
partDesc.setNumBuckets(partition.getSd().getNumBuckets());
@@ -565,28 +564,28 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
}
private static Task<? extends Serializable> alterSinglePartition(
- ImportTableDesc tblDesc, Table table, Warehouse wh, AddPartitionDesc addPartitionDesc,
+ ImportTableDesc tblDesc, Table table, Warehouse wh, AlterTableAddPartitionDesc addPartitionDesc,
ReplicationSpec replicationSpec, org.apache.hadoop.hive.ql.metadata.Partition ptn,
EximUtil.SemanticAnalyzerWrapperContext x) throws MetaException, IOException, HiveException {
addPartitionDesc.setReplaceMode(true);
if ((replicationSpec != null) && (replicationSpec.isInReplicationScope())) {
addPartitionDesc.setReplicationSpec(replicationSpec);
}
- AddPartitionDesc.OnePartitionDesc partSpec = addPartitionDesc.getPartition(0);
+ AlterTableAddPartitionDesc.PartitionDesc partSpec = addPartitionDesc.getPartition(0);
if (ptn == null) {
fixLocationInPartSpec(tblDesc, table, wh, replicationSpec, partSpec, x);
} else if (!externalTablePartition(tblDesc, replicationSpec)) {
partSpec.setLocation(ptn.getLocation()); // use existing location
}
- return TaskFactory.get(new DDLWork(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
+ return TaskFactory.get(new DDLWork2(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
}
private static Task<?> addSinglePartition(ImportTableDesc tblDesc,
- Table table, Warehouse wh, AddPartitionDesc addPartitionDesc,
+ Table table, Warehouse wh, AlterTableAddPartitionDesc addPartitionDesc,
ReplicationSpec replicationSpec,
EximUtil.SemanticAnalyzerWrapperContext x, Long writeId, int stmtId)
throws MetaException, IOException, HiveException {
- AddPartitionDesc.OnePartitionDesc partSpec = addPartitionDesc.getPartition(0);
+ AlterTableAddPartitionDesc.PartitionDesc partSpec = addPartitionDesc.getPartition(0);
boolean isAutoPurge = false;
boolean needRecycle = false;
boolean copyToMigratedTxnTable = replicationSpec.isMigratingToTxnTable();
@@ -598,7 +597,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
// addPartitionDesc already has the right partition location
@SuppressWarnings("unchecked")
Task<?> addPartTask = TaskFactory.get(
- new DDLWork(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
+ new DDLWork2(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
return addPartTask;
} else {
String srcLocation = partSpec.getLocation();
@@ -658,7 +657,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
// the partition/s to be already added or altered by previous events. So no need to
// create add partition event again.
addPartTask = TaskFactory.get(
- new DDLWork(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
+ new DDLWork2(x.getInputs(), x.getOutputs(), addPartitionDesc), x.getConf());
}
MoveWork moveWork = new MoveWork(x.getInputs(), x.getOutputs(),
@@ -729,7 +728,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
* Helper method to set location properly in partSpec
*/
private static void fixLocationInPartSpec(ImportTableDesc tblDesc, Table table,
- Warehouse wh, ReplicationSpec replicationSpec, AddPartitionDesc.OnePartitionDesc partSpec,
+ Warehouse wh, ReplicationSpec replicationSpec, AlterTableAddPartitionDesc.PartitionDesc partSpec,
EximUtil.SemanticAnalyzerWrapperContext x) throws MetaException, HiveException, IOException {
if (externalTablePartition(tblDesc, replicationSpec)) {
/*
@@ -1030,7 +1029,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
* @param wh
*/
private static void createRegularImportTasks(
- ImportTableDesc tblDesc, List<AddPartitionDesc> partitionDescs, boolean isPartSpecSet,
+ ImportTableDesc tblDesc, List<AlterTableAddPartitionDesc> partitionDescs, boolean isPartSpecSet,
ReplicationSpec replicationSpec, Table table, URI fromURI, FileSystem fs, Warehouse wh,
EximUtil.SemanticAnalyzerWrapperContext x, Long writeId, int stmtId)
throws HiveException, IOException, MetaException {
@@ -1039,7 +1038,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
if (table.isPartitioned()) {
x.getLOG().debug("table partitioned");
- for (AddPartitionDesc addPartitionDesc : partitionDescs) {
+ for (AlterTableAddPartitionDesc addPartitionDesc : partitionDescs) {
Map<String, String> partSpec = addPartitionDesc.getPartition(0).getPartSpec();
org.apache.hadoop.hive.ql.metadata.Partition ptn = null;
if ((ptn = x.getHive().getPartition(table, partSpec, false)) == null) {
@@ -1073,7 +1072,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
x.getOutputs().add(new WriteEntity(parentDb, WriteEntity.WriteType.DDL_SHARED));
if (isPartitioned(tblDesc)) {
- for (AddPartitionDesc addPartitionDesc : partitionDescs) {
+ for (AlterTableAddPartitionDesc addPartitionDesc : partitionDescs) {
t.addDependentTask(addSinglePartition(tblDesc, table, wh, addPartitionDesc,
replicationSpec, x, writeId, stmtId));
}
@@ -1122,7 +1121,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
*/
private static void createReplImportTasks(
ImportTableDesc tblDesc,
- List<AddPartitionDesc> partitionDescs,
+ List<AlterTableAddPartitionDesc> partitionDescs,
ReplicationSpec replicationSpec, boolean waitOnPrecursor,
Table table, URI fromURI, Warehouse wh,
EximUtil.SemanticAnalyzerWrapperContext x, Long writeId, int stmtId,
@@ -1226,7 +1225,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
List<Task<?>> dependentTasks = null;
if (isPartitioned(tblDesc)) {
dependentTasks = new ArrayList<>(partitionDescs.size());
- for (AddPartitionDesc addPartitionDesc : partitionDescs) {
+ for (AlterTableAddPartitionDesc addPartitionDesc : partitionDescs) {
addPartitionDesc.setReplicationSpec(replicationSpec);
if (!replicationSpec.isMetadataOnly()) {
dependentTasks.add(addSinglePartition(tblDesc, table, wh, addPartitionDesc,
@@ -1289,7 +1288,7 @@ public class ImportSemanticAnalyzer extends BaseSemanticAnalyzer {
// Table existed, and is okay to replicate into, not dropping and re-creating.
if (isPartitioned(tblDesc)) {
x.getLOG().debug("table partitioned");
- for (AddPartitionDesc addPartitionDesc : partitionDescs) {
+ for (AlterTableAddPartitionDesc addPartitionDesc : partitionDescs) {
addPartitionDesc.setReplicationSpec(replicationSpec);
Map<String, String> partSpec = addPartitionDesc.getPartition(0).getPartSpec();
org.apache.hadoop.hive.ql.metadata.Partition ptn = null;
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/DropPartitionHandler.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/DropPartitionHandler.java
index 5e88b6e..98a4b71 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/DropPartitionHandler.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/DropPartitionHandler.java
@@ -18,13 +18,13 @@
package org.apache.hadoop.hive.ql.parse.repl.load.message;
import org.apache.hadoop.hive.metastore.messaging.DropPartitionMessage;
+import org.apache.hadoop.hive.ql.ddl.DDLWork2;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableDropPartitionDesc;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
import org.apache.hadoop.hive.ql.metadata.Table;
import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.DropPartitionDesc;
import org.apache.hadoop.hive.ql.plan.ExprNodeGenericFuncDesc;
import java.io.Serializable;
@@ -43,10 +43,10 @@ public class DropPartitionHandler extends AbstractMessageHandler {
Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecs =
ReplUtils.genPartSpecs(new Table(msg.getTableObj()), msg.getPartitions());
if (partSpecs.size() > 0) {
- DropPartitionDesc dropPtnDesc = new DropPartitionDesc(actualDbName + "." + actualTblName, partSpecs, true,
- context.eventOnlyReplicationSpec());
- Task<DDLWork> dropPtnTask = TaskFactory.get(
- new DDLWork(readEntitySet, writeEntitySet, dropPtnDesc), context.hiveConf
+ AlterTableDropPartitionDesc dropPtnDesc = new AlterTableDropPartitionDesc(actualDbName + "." + actualTblName,
+ partSpecs, true, context.eventOnlyReplicationSpec());
+ Task<DDLWork2> dropPtnTask = TaskFactory.get(
+ new DDLWork2(readEntitySet, writeEntitySet, dropPtnDesc), context.hiveConf
);
context.log.debug("Added drop ptn task : {}:{},{}", dropPtnTask.getId(),
dropPtnDesc.getTableName(), msg.getPartitions());
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/RenamePartitionHandler.java b/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/RenamePartitionHandler.java
index 9c66210..2c30641 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/RenamePartitionHandler.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/repl/load/message/RenamePartitionHandler.java
@@ -20,13 +20,13 @@ package org.apache.hadoop.hive.ql.parse.repl.load.message;
import org.apache.hadoop.hive.metastore.api.FieldSchema;
import org.apache.hadoop.hive.metastore.api.Table;
import org.apache.hadoop.hive.metastore.messaging.AlterPartitionMessage;
+import org.apache.hadoop.hive.ql.ddl.DDLWork2;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableRenamePartitionDesc;
import org.apache.hadoop.hive.ql.exec.Task;
import org.apache.hadoop.hive.ql.exec.TaskFactory;
import org.apache.hadoop.hive.ql.exec.repl.util.ReplUtils;
import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
import org.apache.hadoop.hive.ql.parse.SemanticException;
-import org.apache.hadoop.hive.ql.plan.DDLWork;
-import org.apache.hadoop.hive.ql.plan.RenamePartitionDesc;
import java.io.Serializable;
import java.util.Iterator;
@@ -60,11 +60,11 @@ public class RenamePartitionHandler extends AbstractMessageHandler {
replicationSpec.setMigratingToTxnTable();
}
- RenamePartitionDesc renamePtnDesc = new RenamePartitionDesc(
+ AlterTableRenamePartitionDesc renamePtnDesc = new AlterTableRenamePartitionDesc(
tableName, oldPartSpec, newPartSpec, replicationSpec, null);
renamePtnDesc.setWriteId(msg.getWriteId());
- Task<DDLWork> renamePtnTask = TaskFactory.get(
- new DDLWork(readEntitySet, writeEntitySet, renamePtnDesc), context.hiveConf);
+ Task<DDLWork2> renamePtnTask = TaskFactory.get(
+ new DDLWork2(readEntitySet, writeEntitySet, renamePtnDesc), context.hiveConf);
context.log.debug("Added rename ptn task : {}:{}->{}",
renamePtnTask.getId(), oldPartSpec, newPartSpec);
updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, actualTblName, newPartSpec);
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableAlterPartDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableAlterPartDesc.java
deleted file mode 100644
index 652c007..0000000
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/AlterTableAlterPartDesc.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.hadoop.hive.ql.plan;
-
-import org.apache.hadoop.hive.metastore.api.FieldSchema;
-
-public class AlterTableAlterPartDesc extends DDLDesc implements DDLDesc.DDLDescWithWriteId {
- private String fqTableName;
- private FieldSchema partKeySpec;
- private long writeId;
-
- public AlterTableAlterPartDesc() {
- }
-
- /**
- * @param fqTableName
- * table containing the partition
- * @param partKeySpec
- */
- public AlterTableAlterPartDesc(String fqTableName, FieldSchema partKeySpec) {
- super();
- this.fqTableName = fqTableName;
- this.partKeySpec = partKeySpec;
- }
-
- public String getTableName() {
- return fqTableName;
- }
-
- public void setTableName(String tableName) {
- this.fqTableName = tableName;
- }
-
- public FieldSchema getPartKeySpec() {
- return partKeySpec;
- }
-
- public void setPartKeySpec(FieldSchema partKeySpec) {
- this.partKeySpec = partKeySpec;
- }
-
- @Override
- public void setWriteId(long writeId) {
- this.writeId = writeId;
- }
-
- @Override
- public String getFullTableName() {
- return fqTableName;
- }
-
- @Override
- public boolean mayNeedWriteId() {
- return true; // Checked before setting as the acid desc.
- }
-}
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/DDLWork.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/DDLWork.java
index 0505e07..6cd84bb 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/DDLWork.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/plan/DDLWork.java
@@ -34,16 +34,10 @@ public class DDLWork implements Serializable {
// TODO: this can probably be replaced with much less code via dynamic dispatch and/or templates.
private InsertCommitHookDesc insertCommitHookDesc;
- private DropPartitionDesc dropPartitionDesc;
private AlterTableDesc alterTblDesc;
private ShowColumnsDesc showColumnsDesc;
- private ShowPartitionsDesc showPartsDesc;
- private AddPartitionDesc addPartitionDesc;
- private RenamePartitionDesc renamePartitionDesc;
private AlterTableSimpleDesc alterTblSimpleDesc;
private MsckDesc msckDesc;
- private AlterTableAlterPartDesc alterTableAlterPartDesc;
- private AlterTableExchangePartition alterTableExchangePartition;
private ShowConfDesc showConfDesc;
@@ -86,13 +80,6 @@ public class DDLWork implements Serializable {
this.alterTblDesc = alterTblDesc;
}
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- DropPartitionDesc dropPartitionDesc) {
- this(inputs, outputs);
-
- this.dropPartitionDesc = dropPartitionDesc;
- }
-
/**
* @param showColumnsDesc
*/
@@ -104,38 +91,6 @@ public class DDLWork implements Serializable {
}
/**
- * @param showPartsDesc
- */
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- ShowPartitionsDesc showPartsDesc) {
- this(inputs, outputs);
-
- this.showPartsDesc = showPartsDesc;
- }
-
- /**
- * @param addPartitionDesc
- * information about the partitions we want to add.
- */
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- AddPartitionDesc addPartitionDesc) {
- this(inputs, outputs);
-
- this.addPartitionDesc = addPartitionDesc;
- }
-
- /**
- * @param renamePartitionDesc
- * information about the partitions we want to add.
- */
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- RenamePartitionDesc renamePartitionDesc) {
- this(inputs, outputs);
-
- this.renamePartitionDesc = renamePartitionDesc;
- }
-
- /**
* @param inputs
* @param outputs
* @param simpleDesc
@@ -161,18 +116,6 @@ public class DDLWork implements Serializable {
}
public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- AlterTableAlterPartDesc alterPartDesc) {
- this(inputs, outputs);
- this.alterTableAlterPartDesc = alterPartDesc;
- }
-
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
- AlterTableExchangePartition alterTableExchangePartition) {
- this(inputs, outputs);
- this.alterTableExchangePartition = alterTableExchangePartition;
- }
-
- public DDLWork(HashSet<ReadEntity> inputs, HashSet<WriteEntity> outputs,
CacheMetadataDesc cacheMetadataDesc) {
this(inputs, outputs);
this.cacheMetadataDesc = cacheMetadataDesc;
@@ -192,14 +135,6 @@ public class DDLWork implements Serializable {
}
/**
- * @return the dropTblDesc
- */
- @Explain(displayName = "Drop Partition Operator", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
- public DropPartitionDesc getDropPartitionDesc() {
- return dropPartitionDesc;
- }
-
- /**
* @return the alterTblDesc
*/
@Explain(displayName = "Alter Table Operator", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
@@ -216,29 +151,6 @@ public class DDLWork implements Serializable {
}
/**
- * @return the showPartsDesc
- */
- @Explain(displayName = "Show Partitions Operator", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
- public ShowPartitionsDesc getShowPartsDesc() {
- return showPartsDesc;
- }
-
- /**
- * @return information about the partitions we want to add.
- */
- @Explain(displayName = "Add Partition Operator", explainLevels = { Level.USER, Level.DEFAULT, Level.EXTENDED })
- public AddPartitionDesc getAddPartitionDesc() {
- return addPartitionDesc;
- }
-
- /**
- * @return information about the partitions we want to rename.
- */
- public RenamePartitionDesc getRenamePartitionDesc() {
- return renamePartitionDesc;
- }
-
- /**
* @return information about the table/partitions we want to alter.
*/
public AlterTableSimpleDesc getAlterTblSimpleDesc() {
@@ -276,20 +188,6 @@ public class DDLWork implements Serializable {
}
/**
- * @return information about the partitions we want to change.
- */
- public AlterTableAlterPartDesc getAlterTableAlterPartDesc() {
- return alterTableAlterPartDesc;
- }
-
- /**
- * @return information about the table partition to be exchanged
- */
- public AlterTableExchangePartition getAlterTableExchangePartition() {
- return this.alterTableExchangePartition;
- }
-
- /**
* @return information about the metadata to be cached
*/
public CacheMetadataDesc getCacheMetadataDesc() {
diff --git a/ql/src/java/org/apache/hadoop/hive/ql/plan/RenamePartitionDesc.java b/ql/src/java/org/apache/hadoop/hive/ql/plan/RenamePartitionDesc.java
deleted file mode 100644
index b4edbfe..0000000
--- a/ql/src/java/org/apache/hadoop/hive/ql/plan/RenamePartitionDesc.java
+++ /dev/null
@@ -1,141 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one
- * or more contributor license agreements. See the NOTICE file
- * distributed with this work for additional information
- * regarding copyright ownership. The ASF licenses this file
- * to you under the Apache License, Version 2.0 (the
- * "License"); you may not use this file except in compliance
- * with the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.apache.hadoop.hive.ql.plan;
-
-import org.apache.hadoop.hive.ql.metadata.Table;
-import org.apache.hadoop.hive.ql.parse.ReplicationSpec;
-import org.apache.hadoop.hive.ql.plan.DDLDesc.DDLDescWithWriteId;
-
-import java.io.Serializable;
-import java.util.LinkedHashMap;
-import java.util.Map;
-
-/**
- * Contains the information needed to rename a partition.
- */
-public class RenamePartitionDesc extends DDLDesc implements Serializable, DDLDescWithWriteId {
-
- private static final long serialVersionUID = 1L;
-
- private String tableName;
- private String location;
- private LinkedHashMap<String, String> oldPartSpec;
- private LinkedHashMap<String, String> newPartSpec;
- private ReplicationSpec replicationSpec;
- private String fqTableName;
- private long writeId;
-
- /**
- * For serialization only.
- */
- public RenamePartitionDesc() {
- }
-
- /**
- * @param tableName
- * table to add to.
- * @param oldPartSpec
- * old partition specification.
- * @param newPartSpec
- * new partition specification.
- * @param table
- */
- public RenamePartitionDesc(String tableName, Map<String, String> oldPartSpec,
- Map<String, String> newPartSpec, ReplicationSpec replicationSpec, Table table) {
- this.tableName = tableName;
- this.oldPartSpec = new LinkedHashMap<String,String>(oldPartSpec);
- this.newPartSpec = new LinkedHashMap<String,String>(newPartSpec);
- this.replicationSpec = replicationSpec;
- this.fqTableName = table != null ? (table.getDbName() + "." + table.getTableName()) : tableName;
- }
-
- /**
- * @return the table we're going to add the partitions to.
- */
- public String getTableName() {
- return tableName;
- }
-
- /**
- * @return location of partition in relation to table
- */
- public String getLocation() {
- return location;
- }
-
- /**
- * @param location
- * location of partition in relation to table
- */
- public void setLocation(String location) {
- this.location = location;
- }
-
- /**
- * @return old partition specification.
- */
- public LinkedHashMap<String, String> getOldPartSpec() {
- return oldPartSpec;
- }
-
- /**
- * @param partSpec
- * partition specification
- */
- public void setOldPartSpec(LinkedHashMap<String, String> partSpec) {
- this.oldPartSpec = partSpec;
- }
-
- /**
- * @return new partition specification.
- */
- public LinkedHashMap<String, String> getNewPartSpec() {
- return newPartSpec;
- }
-
- /**
- * @param partSpec
- * partition specification
- */
- public void setNewPartSpec(LinkedHashMap<String, String> partSpec) {
- this.newPartSpec = partSpec;
- }
-
- /**
- * @return what kind of replication scope this rename is running under.
- * This can result in a "RENAME IF NEWER THAN" kind of semantic
- */
- public ReplicationSpec getReplicationSpec() { return this.replicationSpec; }
-
- @Override
- public void setWriteId(long writeId) {
- this.writeId = writeId;
- }
-
- public long getWriteId() { return writeId; }
-
- @Override
- public String getFullTableName() {
- return fqTableName;
- }
-
- @Override
- public boolean mayNeedWriteId() {
- return true; // The check is done when setting this as the ACID DDLDesc.
- }
-}
diff --git a/ql/src/test/queries/clientpositive/alter_partition_change_col.q b/ql/src/test/queries/clientpositive/alter_partition_change_col.q
index c207731..6f1f110 100644
--- a/ql/src/test/queries/clientpositive/alter_partition_change_col.q
+++ b/ql/src/test/queries/clientpositive/alter_partition_change_col.q
@@ -34,6 +34,7 @@ select * from alter_partition_change_col1 where p1='abc';
select * from alter_partition_change_col1 where p1='__HIVE_DEFAULT_PARTITION__';
-- change the comment on a partition column without changing type or renaming it
+explain alter table alter_partition_change_col1 partition column (p1 string comment 'Changed comment for p1');
alter table alter_partition_change_col1 partition column (p1 string comment 'Changed comment for p1');
describe alter_partition_change_col1;
diff --git a/ql/src/test/queries/clientpositive/alter_rename_partition.q b/ql/src/test/queries/clientpositive/alter_rename_partition.q
index b6f6ccc..59008ee 100644
--- a/ql/src/test/queries/clientpositive/alter_rename_partition.q
+++ b/ql/src/test/queries/clientpositive/alter_rename_partition.q
@@ -33,6 +33,7 @@ CREATE TABLE alter_rename_partition (col1 STRING) PARTITIONED BY (pcol1 STRING,
INSERT OVERWRITE TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') SELECT col1 FROM alter_rename_partition_src ;
SELECT * FROM alter_rename_partition WHERE pcol1='old_part1:' AND pcol2='old_part2:';
+EXPLAIN ALTER TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') RENAME TO PARTITION (pCol1='new_part1:', pcol2='new_part2:');
ALTER TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') RENAME TO PARTITION (pCol1='new_part1:', pcol2='new_part2:');
SHOW PARTITIONS alter_rename_partition;
SELECT * FROM alter_rename_partition WHERE pcol1='old_part1:' and pcol2='old_part2:';
diff --git a/ql/src/test/queries/clientpositive/drop_partitions_filter.q b/ql/src/test/queries/clientpositive/drop_partitions_filter.q
index 5862753..c402a3b 100644
--- a/ql/src/test/queries/clientpositive/drop_partitions_filter.q
+++ b/ql/src/test/queries/clientpositive/drop_partitions_filter.q
@@ -1,6 +1,7 @@
create table ptestfilter_n1 (a string, b int) partitioned by (c string, d string);
describe ptestfilter_n1;
+explain alter table ptestfilter_n1 add partition (c='US', d=1);
alter table ptestfilter_n1 add partition (c='US', d=1);
alter table ptestfilter_n1 add partition (c='US', d=2);
alter table ptestFilter_n1 add partition (c='Uganda', d=2);
@@ -12,7 +13,9 @@ alter table ptestfilter_n1 add partition (c='India', d=3);
alter table ptestfilter_n1 add partition (c='France', d=4);
show partitions ptestfilter_n1;
+explain alter table ptestfilter_n1 drop partition (c='US', d<'2');
alter table ptestfilter_n1 drop partition (c='US', d<'2');
+explain show partitions ptestfilter_n1;
show partitions ptestfilter_n1;
alter table ptestfilter_n1 drop partition (c>='US', d<='2');
@@ -21,6 +24,8 @@ show partitions ptestfilter_n1;
alter table ptestfilter_n1 drop partition (c >'India');
show partitions ptestfilter_n1;
+explain alter table ptestfilter_n1 drop partition (c >='India'),
+ partition (c='Greece', d='2');
alter table ptestfilter_n1 drop partition (c >='India'),
partition (c='Greece', d='2');
show partitions ptestfilter_n1;
diff --git a/ql/src/test/queries/clientpositive/exchgpartition2lel.q b/ql/src/test/queries/clientpositive/exchgpartition2lel.q
index 567ff8a..63d3c80 100644
--- a/ql/src/test/queries/clientpositive/exchgpartition2lel.q
+++ b/ql/src/test/queries/clientpositive/exchgpartition2lel.q
@@ -27,6 +27,7 @@ ALTER TABLE t4_n7 EXCHANGE PARTITION (d1 = 1, d2 = 1) WITH TABLE t3_n15;
SELECT * FROM t3_n15;
SELECT * FROM t4_n7;
+EXPLAIN ALTER TABLE t6_n2 EXCHANGE PARTITION (d1 = 1, d2 = 1, d3 = 1) WITH TABLE t5_n3;
ALTER TABLE t6_n2 EXCHANGE PARTITION (d1 = 1, d2 = 1, d3 = 1) WITH TABLE t5_n3;
SELECT * FROM t5_n3;
SELECT * FROM t6_n2;
diff --git a/ql/src/test/queries/clientpositive/show_partitions.q b/ql/src/test/queries/clientpositive/show_partitions.q
index d22c483..f919db8 100644
--- a/ql/src/test/queries/clientpositive/show_partitions.q
+++ b/ql/src/test/queries/clientpositive/show_partitions.q
@@ -20,7 +20,9 @@ ALTER TABLE srcpart ADD PARTITION (ds='4', hr='4');
ALTER TABLE srcpart ADD PARTITION (ds='4', hr='5');
-- from db1 to default db
+EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(hr='11');
SHOW PARTITIONS default.srcpart PARTITION(hr='11');
+EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(ds='2008-04-08', hr='12');
SHOW PARTITIONS default.srcpart PARTITION(ds='2008-04-08', hr='12');
-- from db1 to db1
@@ -30,4 +32,4 @@ SHOW PARTITIONS srcpart PARTITION(ds='3', hr='3');
use default;
-- from default to db1
SHOW PARTITIONS db1.srcpart PARTITION(ds='4');
-SHOW PARTITIONS db1.srcpart PARTITION(ds='3', hr='3');
\ No newline at end of file
+SHOW PARTITIONS db1.srcpart PARTITION(ds='3', hr='3');
diff --git a/ql/src/test/results/clientnegative/add_partition_with_whitelist.q.out b/ql/src/test/results/clientnegative/add_partition_with_whitelist.q.out
index 95da219..a744a94 100644
--- a/ql/src/test/results/clientnegative/add_partition_with_whitelist.q.out
+++ b/ql/src/test/results/clientnegative/add_partition_with_whitelist.q.out
@@ -15,4 +15,4 @@ POSTHOOK: Input: default@part_whitelist_test
PREHOOK: query: ALTER TABLE part_whitelist_test ADD PARTITION (ds='1,2,3,4')
PREHOOK: type: ALTERTABLE_ADDPARTS
PREHOOK: Output: default@part_whitelist_test
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:Partition value '1,2,3,4' contains a character not matched by whitelist pattern '[\\x20-\\x7E&&[^,]]*'. (configure with metastore.partition.name.whitelist.pattern))
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. MetaException(message:Partition value '1,2,3,4' contains a character not matched by whitelist pattern '[\\x20-\\x7E&&[^,]]*'. (configure with metastore.partition.name.whitelist.pattern))
diff --git a/ql/src/test/results/clientnegative/addpart1.q.out b/ql/src/test/results/clientnegative/addpart1.q.out
index e1255bc..61fbc57 100644
--- a/ql/src/test/results/clientnegative/addpart1.q.out
+++ b/ql/src/test/results/clientnegative/addpart1.q.out
@@ -23,4 +23,4 @@ b=f/c=s
PREHOOK: query: alter table addpart1 add partition (b='f', c='')
PREHOOK: type: ALTERTABLE_ADDPARTS
PREHOOK: Output: default@addpart1
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. partition spec is invalid; field c does not exist or is empty
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. partition spec is invalid; field c does not exist or is empty
diff --git a/ql/src/test/results/clientnegative/alter_partition_with_whitelist.q.out b/ql/src/test/results/clientnegative/alter_partition_with_whitelist.q.out
index ae265eb..4049cc7 100644
--- a/ql/src/test/results/clientnegative/alter_partition_with_whitelist.q.out
+++ b/ql/src/test/results/clientnegative/alter_partition_with_whitelist.q.out
@@ -23,4 +23,4 @@ PREHOOK: query: ALTER TABLE part_whitelist_test PARTITION (ds='1') rename to par
PREHOOK: type: ALTERTABLE_RENAMEPART
PREHOOK: Input: default@part_whitelist_test
PREHOOK: Output: default@part_whitelist_test@ds=1
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to rename partition. Partition value '1,2,3' contains a character not matched by whitelist pattern '[\\x20-\\x7E&&[^,]]*'. (configure with metastore.partition.name.whitelist.pattern)
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. Unable to rename partition. Partition value '1,2,3' contains a character not matched by whitelist pattern '[\\x20-\\x7E&&[^,]]*'. (configure with metastore.partition.name.whitelist.pattern)
diff --git a/ql/src/test/results/clientnegative/alter_rename_partition_failure.q.out b/ql/src/test/results/clientnegative/alter_rename_partition_failure.q.out
index 486ab8c..0dddbc1 100644
--- a/ql/src/test/results/clientnegative/alter_rename_partition_failure.q.out
+++ b/ql/src/test/results/clientnegative/alter_rename_partition_failure.q.out
@@ -34,4 +34,4 @@ POSTHOOK: Lineage: alter_rename_partition PARTITION(pcol1=old_part1,pcol2=old_pa
PREHOOK: query: alter table alter_rename_partition partition (pCol1='nonexist_part1', pcol2='nonexist_part2') rename to partition (pCol1='new_part1', pcol2='new_part2')
PREHOOK: type: ALTERTABLE_RENAMEPART
PREHOOK: Input: default@alter_rename_partition
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Rename partition: source partition [pcol1=nonexist_part1/pcol2=nonexist_part2] does not exist.
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. Rename partition: source partition [pcol1=nonexist_part1/pcol2=nonexist_part2] does not exist.
diff --git a/ql/src/test/results/clientnegative/alter_rename_partition_failure2.q.out b/ql/src/test/results/clientnegative/alter_rename_partition_failure2.q.out
index acb66ac..566ac6f 100644
--- a/ql/src/test/results/clientnegative/alter_rename_partition_failure2.q.out
+++ b/ql/src/test/results/clientnegative/alter_rename_partition_failure2.q.out
@@ -35,4 +35,4 @@ PREHOOK: query: alter table alter_rename_partition partition (pCol1='old_part1:'
PREHOOK: type: ALTERTABLE_RENAMEPART
PREHOOK: Input: default@alter_rename_partition
PREHOOK: Output: default@alter_rename_partition@pcol1=old_part1%3A/pcol2=old_part2%3A
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. Unable to rename partition. Partition already exists:default.alter_rename_partition.[old_part1:, old_part2:]
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. Unable to rename partition. Partition already exists:default.alter_rename_partition.[old_part1:, old_part2:]
diff --git a/ql/src/test/results/clientnegative/exchange_partition.q.out b/ql/src/test/results/clientnegative/exchange_partition.q.out
index bfdf413..42ca82b 100644
--- a/ql/src/test/results/clientnegative/exchange_partition.q.out
+++ b/ql/src/test/results/clientnegative/exchange_partition.q.out
@@ -53,4 +53,4 @@ PREHOOK: query: ALTER TABLE ex_table1 EXCHANGE PARTITION (part='part1') WITH TAB
PREHOOK: type: ALTERTABLE_EXCHANGEPARTITION
PREHOOK: Input: default@ex_table2
PREHOOK: Output: default@ex_table1
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. MetaException(message:Got exception: java.io.IOException Cannot rename the source path. The destination path already exists.)
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. MetaException(message:Got exception: java.io.IOException Cannot rename the source path. The destination path already exists.)
diff --git a/ql/src/test/results/clientnegative/external2.q.out b/ql/src/test/results/clientnegative/external2.q.out
index 05ddc28..88a3bb8 100644
--- a/ql/src/test/results/clientnegative/external2.q.out
+++ b/ql/src/test/results/clientnegative/external2.q.out
@@ -10,4 +10,4 @@ POSTHOOK: Output: default@external2
PREHOOK: type: ALTERTABLE_ADDPARTS
#### A masked pattern was here ####
PREHOOK: Output: default@external2
-FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.exec.DDLTask. org.apache.hadoop.fs.UnsupportedFileSystemException: No FileSystem for scheme "invalidscheme"
+FAILED: Execution Error, return code 1 from org.apache.hadoop.hive.ql.ddl.DDLTask2. org.apache.hadoop.fs.UnsupportedFileSystemException: No FileSystem for scheme "invalidscheme"
diff --git a/ql/src/test/results/clientpositive/add_part_multiple.q.out b/ql/src/test/results/clientpositive/add_part_multiple.q.out
index 7631c4d..81454f7 100644
--- a/ql/src/test/results/clientpositive/add_part_multiple.q.out
+++ b/ql/src/test/results/clientpositive/add_part_multiple.q.out
@@ -29,9 +29,9 @@ STAGE DEPENDENCIES:
STAGE PLANS:
Stage: Stage-0
- Add Partition Operator:
+ Add Partition
#### A masked pattern was here ####
- Spec: {ds=2010-01-01}, {ds=2010-02-01}, {ds=2010-03-01}, {ds=2010-04-01}
+ Spec: {ds=2010-01-01}, {ds=2010-02-01}, {ds=2010-03-01}, {ds=2010-04-01}
PREHOOK: query: ALTER TABLE add_part_test_n1 ADD IF NOT EXISTS
PARTITION (ds='2010-01-01') location 'A'
diff --git a/ql/src/test/results/clientpositive/alter_partition_change_col.q.out b/ql/src/test/results/clientpositive/alter_partition_change_col.q.out
index d330026..9a5ac43 100644
--- a/ql/src/test/results/clientpositive/alter_partition_change_col.q.out
+++ b/ql/src/test/results/clientpositive/alter_partition_change_col.q.out
@@ -253,6 +253,22 @@ Snow 56.0000 __HIVE_DEFAULT_PARTITION__ 123
Tom -12.0000 __HIVE_DEFAULT_PARTITION__ 123
Tom 19.0000 __HIVE_DEFAULT_PARTITION__ 123
Tom 235.0000 __HIVE_DEFAULT_PARTITION__ 123
+PREHOOK: query: explain alter table alter_partition_change_col1 partition column (p1 string comment 'Changed comment for p1')
+PREHOOK: type: ALTERTABLE_PARTCOLTYPE
+PREHOOK: Input: default@alter_partition_change_col1
+POSTHOOK: query: explain alter table alter_partition_change_col1 partition column (p1 string comment 'Changed comment for p1')
+POSTHOOK: type: ALTERTABLE_PARTCOLTYPE
+POSTHOOK: Input: default@alter_partition_change_col1
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Alter Partition
+ partition key name: p1
+ partition key type: string
+ table: default.alter_partition_change_col1
+
PREHOOK: query: alter table alter_partition_change_col1 partition column (p1 string comment 'Changed comment for p1')
PREHOOK: type: ALTERTABLE_PARTCOLTYPE
PREHOOK: Input: default@alter_partition_change_col1
diff --git a/ql/src/test/results/clientpositive/alter_rename_partition.q.out b/ql/src/test/results/clientpositive/alter_rename_partition.q.out
index fc7d750..884a321 100644
--- a/ql/src/test/results/clientpositive/alter_rename_partition.q.out
+++ b/ql/src/test/results/clientpositive/alter_rename_partition.q.out
@@ -179,6 +179,28 @@ POSTHOOK: Input: alter_rename_partition_db@alter_rename_partition@pcol1=old_part
4 old_part1: old_part2:
5 old_part1: old_part2:
6 old_part1: old_part2:
+PREHOOK: query: EXPLAIN ALTER TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') RENAME TO PARTITION (pCol1='new_part1:', pcol2='new_part2:')
+PREHOOK: type: ALTERTABLE_RENAMEPART
+PREHOOK: Input: alter_rename_partition_db@alter_rename_partition
+PREHOOK: Output: alter_rename_partition_db@alter_rename_partition@pcol1=old_part1%3A/pcol2=old_part2%3A
+POSTHOOK: query: EXPLAIN ALTER TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') RENAME TO PARTITION (pCol1='new_part1:', pcol2='new_part2:')
+POSTHOOK: type: ALTERTABLE_RENAMEPART
+POSTHOOK: Input: alter_rename_partition_db@alter_rename_partition
+POSTHOOK: Output: alter_rename_partition_db@alter_rename_partition@pcol1=old_part1%3A/pcol2=old_part2%3A
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Rename Partition
+ new partitions:
+ pcol1 new_part1:
+ pcol2 new_part2:
+ old partitions:
+ pcol1 old_part1:
+ pcol2 old_part2:
+ table: alter_rename_partition_db.alter_rename_partition
+
PREHOOK: query: ALTER TABLE alter_rename_partition PARTITION (pCol1='old_part1:', pcol2='old_part2:') RENAME TO PARTITION (pCol1='new_part1:', pcol2='new_part2:')
PREHOOK: type: ALTERTABLE_RENAMEPART
PREHOOK: Input: alter_rename_partition_db@alter_rename_partition
diff --git a/ql/src/test/results/clientpositive/drop_deleted_partitions.q.out b/ql/src/test/results/clientpositive/drop_deleted_partitions.q.out
index e2c4443..bc2e19e 100644
--- a/ql/src/test/results/clientpositive/drop_deleted_partitions.q.out
+++ b/ql/src/test/results/clientpositive/drop_deleted_partitions.q.out
@@ -42,9 +42,8 @@ STAGE DEPENDENCIES:
STAGE PLANS:
Stage: Stage-0
- Drop Partition Operator:
- Drop Partition
- table: dmp.mp
+ Drop Partition
+ table: dmp.mp
PREHOOK: query: alter table dmp.mp drop partition (b='1')
PREHOOK: type: ALTERTABLE_DROPPARTS
diff --git a/ql/src/test/results/clientpositive/drop_multi_partitions.q.out b/ql/src/test/results/clientpositive/drop_multi_partitions.q.out
index 53978e8..559aca1 100644
--- a/ql/src/test/results/clientpositive/drop_multi_partitions.q.out
+++ b/ql/src/test/results/clientpositive/drop_multi_partitions.q.out
@@ -57,9 +57,8 @@ STAGE DEPENDENCIES:
STAGE PLANS:
Stage: Stage-0
- Drop Partition Operator:
- Drop Partition
- table: dmp.mp_n0
+ Drop Partition
+ table: dmp.mp_n0
PREHOOK: query: alter table dmp.mp_n0 drop partition (b='1')
PREHOOK: type: ALTERTABLE_DROPPARTS
diff --git a/ql/src/test/results/clientpositive/drop_partitions_filter.q.out b/ql/src/test/results/clientpositive/drop_partitions_filter.q.out
index 2cbc05d..457fa0b 100644
--- a/ql/src/test/results/clientpositive/drop_partitions_filter.q.out
+++ b/ql/src/test/results/clientpositive/drop_partitions_filter.q.out
@@ -21,6 +21,21 @@ d string
# col_name data_type comment
c string
d string
+PREHOOK: query: explain alter table ptestfilter_n1 add partition (c='US', d=1)
+PREHOOK: type: ALTERTABLE_ADDPARTS
+PREHOOK: Output: default@ptestfilter_n1
+POSTHOOK: query: explain alter table ptestfilter_n1 add partition (c='US', d=1)
+POSTHOOK: type: ALTERTABLE_ADDPARTS
+POSTHOOK: Output: default@ptestfilter_n1
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Add Partition
+#### A masked pattern was here ####
+ Spec: {c=US, d=1}
+
PREHOOK: query: alter table ptestfilter_n1 add partition (c='US', d=1)
PREHOOK: type: ALTERTABLE_ADDPARTS
PREHOOK: Output: default@ptestfilter_n1
@@ -99,6 +114,22 @@ c=Russia/d=3
c=US/d=1
c=US/d=2
c=Uganda/d=2
+PREHOOK: query: explain alter table ptestfilter_n1 drop partition (c='US', d<'2')
+PREHOOK: type: ALTERTABLE_DROPPARTS
+PREHOOK: Input: default@ptestfilter_n1
+PREHOOK: Output: default@ptestfilter_n1@c=US/d=1
+POSTHOOK: query: explain alter table ptestfilter_n1 drop partition (c='US', d<'2')
+POSTHOOK: type: ALTERTABLE_DROPPARTS
+POSTHOOK: Input: default@ptestfilter_n1
+POSTHOOK: Output: default@ptestfilter_n1@c=US/d=1
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Drop Partition
+ table: default.ptestfilter_n1
+
PREHOOK: query: alter table ptestfilter_n1 drop partition (c='US', d<'2')
PREHOOK: type: ALTERTABLE_DROPPARTS
PREHOOK: Input: default@ptestfilter_n1
@@ -107,6 +138,27 @@ POSTHOOK: query: alter table ptestfilter_n1 drop partition (c='US', d<'2')
POSTHOOK: type: ALTERTABLE_DROPPARTS
POSTHOOK: Input: default@ptestfilter_n1
POSTHOOK: Output: default@ptestfilter_n1@c=US/d=1
+PREHOOK: query: explain show partitions ptestfilter_n1
+PREHOOK: type: SHOWPARTITIONS
+PREHOOK: Input: default@ptestfilter_n1
+POSTHOOK: query: explain show partitions ptestfilter_n1
+POSTHOOK: type: SHOWPARTITIONS
+POSTHOOK: Input: default@ptestfilter_n1
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+ Stage-1 depends on stages: Stage-0
+
+STAGE PLANS:
+ Stage: Stage-0
+ Show Partitions
+ table: ptestfilter_n1
+
+ Stage: Stage-1
+ Fetch Operator
+ limit: -1
+ Processor Tree:
+ ListSink
+
PREHOOK: query: show partitions ptestfilter_n1
PREHOOK: type: SHOWPARTITIONS
PREHOOK: Input: default@ptestfilter_n1
@@ -162,6 +214,26 @@ c=France/d=4
c=Germany/d=2
c=Greece/d=2
c=India/d=3
+PREHOOK: query: explain alter table ptestfilter_n1 drop partition (c >='India'),
+ partition (c='Greece', d='2')
+PREHOOK: type: ALTERTABLE_DROPPARTS
+PREHOOK: Input: default@ptestfilter_n1
+PREHOOK: Output: default@ptestfilter_n1@c=Greece/d=2
+PREHOOK: Output: default@ptestfilter_n1@c=India/d=3
+POSTHOOK: query: explain alter table ptestfilter_n1 drop partition (c >='India'),
+ partition (c='Greece', d='2')
+POSTHOOK: type: ALTERTABLE_DROPPARTS
+POSTHOOK: Input: default@ptestfilter_n1
+POSTHOOK: Output: default@ptestfilter_n1@c=Greece/d=2
+POSTHOOK: Output: default@ptestfilter_n1@c=India/d=3
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Drop Partition
+ table: default.ptestfilter_n1
+
PREHOOK: query: alter table ptestfilter_n1 drop partition (c >='India'),
partition (c='Greece', d='2')
PREHOOK: type: ALTERTABLE_DROPPARTS
diff --git a/ql/src/test/results/clientpositive/llap/exchgpartition2lel.q.out b/ql/src/test/results/clientpositive/llap/exchgpartition2lel.q.out
index 2ec3e1a..45e6b0a 100644
--- a/ql/src/test/results/clientpositive/llap/exchgpartition2lel.q.out
+++ b/ql/src/test/results/clientpositive/llap/exchgpartition2lel.q.out
@@ -171,6 +171,25 @@ POSTHOOK: Input: default@t4_n7
POSTHOOK: Input: default@t4_n7@d1=1/d2=1
#### A masked pattern was here ####
100 1 1
+PREHOOK: query: EXPLAIN ALTER TABLE t6_n2 EXCHANGE PARTITION (d1 = 1, d2 = 1, d3 = 1) WITH TABLE t5_n3
+PREHOOK: type: ALTERTABLE_EXCHANGEPARTITION
+PREHOOK: Input: default@t5_n3
+PREHOOK: Output: default@t6_n2
+POSTHOOK: query: EXPLAIN ALTER TABLE t6_n2 EXCHANGE PARTITION (d1 = 1, d2 = 1, d3 = 1) WITH TABLE t5_n3
+POSTHOOK: type: ALTERTABLE_EXCHANGEPARTITION
+POSTHOOK: Input: default@t5_n3
+POSTHOOK: Output: default@t6_n2
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+
+STAGE PLANS:
+ Stage: Stage-0
+ Exchange Partitions
+ partitions:
+ d1 1
+ d2 1
+ d3 1
+
PREHOOK: query: ALTER TABLE t6_n2 EXCHANGE PARTITION (d1 = 1, d2 = 1, d3 = 1) WITH TABLE t5_n3
PREHOOK: type: ALTERTABLE_EXCHANGEPARTITION
PREHOOK: Input: default@t5_n3
diff --git a/ql/src/test/results/clientpositive/show_partitions.q.out b/ql/src/test/results/clientpositive/show_partitions.q.out
index 8b7473a..0a73374 100644
--- a/ql/src/test/results/clientpositive/show_partitions.q.out
+++ b/ql/src/test/results/clientpositive/show_partitions.q.out
@@ -115,6 +115,29 @@ POSTHOOK: query: ALTER TABLE srcpart ADD PARTITION (ds='4', hr='5')
POSTHOOK: type: ALTERTABLE_ADDPARTS
POSTHOOK: Output: db1@srcpart
POSTHOOK: Output: db1@srcpart@ds=4/hr=5
+PREHOOK: query: EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(hr='11')
+PREHOOK: type: SHOWPARTITIONS
+PREHOOK: Input: default@srcpart
+POSTHOOK: query: EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(hr='11')
+POSTHOOK: type: SHOWPARTITIONS
+POSTHOOK: Input: default@srcpart
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+ Stage-1 depends on stages: Stage-0
+
+STAGE PLANS:
+ Stage: Stage-0
+ Show Partitions
+ partSpec:
+ hr 11
+ table: default.srcpart
+
+ Stage: Stage-1
+ Fetch Operator
+ limit: -1
+ Processor Tree:
+ ListSink
+
PREHOOK: query: SHOW PARTITIONS default.srcpart PARTITION(hr='11')
PREHOOK: type: SHOWPARTITIONS
PREHOOK: Input: default@srcpart
@@ -123,6 +146,30 @@ POSTHOOK: type: SHOWPARTITIONS
POSTHOOK: Input: default@srcpart
ds=2008-04-08/hr=11
ds=2008-04-09/hr=11
+PREHOOK: query: EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(ds='2008-04-08', hr='12')
+PREHOOK: type: SHOWPARTITIONS
+PREHOOK: Input: default@srcpart
+POSTHOOK: query: EXPLAIN SHOW PARTITIONS default.srcpart PARTITION(ds='2008-04-08', hr='12')
+POSTHOOK: type: SHOWPARTITIONS
+POSTHOOK: Input: default@srcpart
+STAGE DEPENDENCIES:
+ Stage-0 is a root stage
+ Stage-1 depends on stages: Stage-0
+
+STAGE PLANS:
+ Stage: Stage-0
+ Show Partitions
+ partSpec:
+ ds 2008-04-08
+ hr 12
+ table: default.srcpart
+
+ Stage: Stage-1
+ Fetch Operator
+ limit: -1
+ Processor Tree:
+ ListSink
+
PREHOOK: query: SHOW PARTITIONS default.srcpart PARTITION(ds='2008-04-08', hr='12')
PREHOOK: type: SHOWPARTITIONS
PREHOOK: Input: default@srcpart
diff --git a/ql/src/test/results/clientpositive/showparts.q.out b/ql/src/test/results/clientpositive/showparts.q.out
index ddb44b6..662b7a2 100644
--- a/ql/src/test/results/clientpositive/showparts.q.out
+++ b/ql/src/test/results/clientpositive/showparts.q.out
@@ -12,9 +12,8 @@ STAGE DEPENDENCIES:
STAGE PLANS:
Stage: Stage-0
- Show Partitions Operator:
- Show Partitions
- table: srcpart
+ Show Partitions
+ table: srcpart
Stage: Stage-1
Fetch Operator
diff --git a/ql/src/test/results/clientpositive/spark/add_part_multiple.q.out b/ql/src/test/results/clientpositive/spark/add_part_multiple.q.out
index 7631c4d..81454f7 100644
--- a/ql/src/test/results/clientpositive/spark/add_part_multiple.q.out
+++ b/ql/src/test/results/clientpositive/spark/add_part_multiple.q.out
@@ -29,9 +29,9 @@ STAGE DEPENDENCIES:
STAGE PLANS:
Stage: Stage-0
- Add Partition Operator:
+ Add Partition
#### A masked pattern was here ####
- Spec: {ds=2010-01-01}, {ds=2010-02-01}, {ds=2010-03-01}, {ds=2010-04-01}
+ Spec: {ds=2010-01-01}, {ds=2010-02-01}, {ds=2010-03-01}, {ds=2010-04-01}
PREHOOK: query: ALTER TABLE add_part_test_n1 ADD IF NOT EXISTS
PARTITION (ds='2010-01-01') location 'A'
diff --git a/streaming/src/java/org/apache/hive/streaming/HiveStreamingConnection.java b/streaming/src/java/org/apache/hive/streaming/HiveStreamingConnection.java
index 6814fe9..f2beafe 100644
--- a/streaming/src/java/org/apache/hive/streaming/HiveStreamingConnection.java
+++ b/streaming/src/java/org/apache/hive/streaming/HiveStreamingConnection.java
@@ -48,7 +48,7 @@ import org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;
import org.apache.hadoop.hive.ql.metadata.Hive;
import org.apache.hadoop.hive.ql.metadata.HiveException;
import org.apache.hadoop.hive.ql.metadata.Table;
-import org.apache.hadoop.hive.ql.plan.AddPartitionDesc;
+import org.apache.hadoop.hive.ql.ddl.table.partition.AlterTableAddPartitionDesc;
import org.apache.hadoop.security.UserGroupInformation;
import org.apache.hive.common.util.ShutdownHookManager;
import org.apache.thrift.TException;
@@ -437,7 +437,7 @@ public class HiveStreamingConnection implements StreamingConnection {
try {
Map<String, String> partSpec = Warehouse.makeSpecFromValues(tableObject.getPartitionKeys(), partitionValues);
- AddPartitionDesc addPartitionDesc = new AddPartitionDesc(database, table, true);
+ AlterTableAddPartitionDesc addPartitionDesc = new AlterTableAddPartitionDesc(database, table, true);
partName = Warehouse.makePartName(tableObject.getPartitionKeys(), partitionValues);
partLocation = new Path(tableObject.getDataLocation(), Warehouse.makePartPath(partSpec)).toString();
addPartitionDesc.addPartition(partSpec, partLocation);