This is an automated email from the ASF dual-hosted git repository.

ayushsaxena pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git


The following commit(s) were added to refs/heads/master by this push:
     new d806028024a HIVE-27654: Iceberg: Cherry-Pick commit to a branch. 
(#4641). (Ayush Saxena, reviewed by Denys Kuzmenko, zhangbutao)
d806028024a is described below

commit d806028024ac8d2225cac00291fe35ab45e56ade
Author: Ayush Saxena <[email protected]>
AuthorDate: Sat Sep 9 21:39:26 2023 +0530

    HIVE-27654: Iceberg: Cherry-Pick commit to a branch. (#4641). (Ayush 
Saxena, reviewed by Denys Kuzmenko, zhangbutao)
---
 .../iceberg/mr/hive/HiveIcebergStorageHandler.java |   7 +-
 .../apache/iceberg/mr/hive/IcebergTableUtil.java   |   5 +
 .../iceberg/mr/hive/TestHiveIcebergCherryPick.java |  85 +++++++++++++
 .../hadoop/hive/ql/parse/AlterClauseParser.g       |   2 +
 .../apache/hadoop/hive/ql/parse/HiveLexerParent.g  |   1 +
 .../table/execute/AlterTableExecuteAnalyzer.java   | 138 +++++++++++++--------
 .../hive/ql/parse/AlterTableExecuteSpec.java       |  26 +++-
 7 files changed, 210 insertions(+), 54 deletions(-)

diff --git 
a/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java
 
b/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java
index d30370b10e0..06d62b0ef7b 100644
--- 
a/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java
+++ 
b/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/HiveIcebergStorageHandler.java
@@ -800,6 +800,11 @@ public class HiveIcebergStorageHandler implements 
HiveStoragePredicateHandler, H
         IcebergTableUtil.fastForwardBranch(icebergTable, 
fastForwardSpec.getSourceBranch(),
             fastForwardSpec.getTargetBranch());
         break;
+      case CHERRY_PICK:
+        AlterTableExecuteSpec.CherryPickSpec cherryPickSpec =
+            (AlterTableExecuteSpec.CherryPickSpec) 
executeSpec.getOperationParams();
+        IcebergTableUtil.cherryPick(icebergTable, 
cherryPickSpec.getSnapshotId());
+        break;
       default:
         throw new UnsupportedOperationException(
             String.format("Operation type %s is not supported", 
executeSpec.getOperationType().name()));
@@ -1403,7 +1408,7 @@ public class HiveIcebergStorageHandler implements 
HiveStoragePredicateHandler, H
    * Generates {@link JobContext}s for the OutputCommitter for the specific 
table.
    * @param configuration The configuration used for as a base of the JobConf
    * @param tableName The name of the table we are planning to commit
-   * @param overwrite If we have to overwrite the existing table or just add 
the new data
+   * @param branchName the name of the branch
    * @return The generated Optional JobContext list or empty if not presents.
    */
   private List<JobContext> generateJobContext(Configuration configuration, 
String tableName,
diff --git 
a/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/IcebergTableUtil.java
 
b/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/IcebergTableUtil.java
index 6e76d23e771..d225c442db3 100644
--- 
a/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/IcebergTableUtil.java
+++ 
b/iceberg/iceberg-handler/src/main/java/org/apache/iceberg/mr/hive/IcebergTableUtil.java
@@ -253,4 +253,9 @@ public class IcebergTableUtil {
     LOG.debug("Fast Forwarding the iceberg table {} branch {} to {}", 
table.name(), sourceBranch, targetBranch);
     table.manageSnapshots().fastForwardBranch(sourceBranch, 
targetBranch).commit();
   }
+
+  public static void cherryPick(Table table, long snapshotId) {
+    LOG.debug("Cherry-Picking {} to {}", snapshotId, table.name());
+    table.manageSnapshots().cherrypick(snapshotId).commit();
+  }
 }
diff --git 
a/iceberg/iceberg-handler/src/test/java/org/apache/iceberg/mr/hive/TestHiveIcebergCherryPick.java
 
b/iceberg/iceberg-handler/src/test/java/org/apache/iceberg/mr/hive/TestHiveIcebergCherryPick.java
new file mode 100644
index 00000000000..99e2c6d6e2c
--- /dev/null
+++ 
b/iceberg/iceberg-handler/src/test/java/org/apache/iceberg/mr/hive/TestHiveIcebergCherryPick.java
@@ -0,0 +1,85 @@
+/*
+ * 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.iceberg.mr.hive;
+
+import java.io.IOException;
+import java.util.List;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableMap;
+import org.junit.After;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import static org.apache.iceberg.mr.hive.TestTables.TestTableType.HIVE_CATALOG;
+import static org.junit.Assert.assertEquals;
+
+public class TestHiveIcebergCherryPick {
+
+  private TestTables testTables;
+  private TestHiveShell shell;
+  private TemporaryFolder temp = new TemporaryFolder();
+
+  @Before
+  public void before() throws IOException {
+    shell = HiveIcebergStorageHandlerTestUtils.shell();
+    temp.create();
+    testTables = HiveIcebergStorageHandlerTestUtils.testTables(shell, 
HIVE_CATALOG, temp);
+    HiveIcebergStorageHandlerTestUtils.init(shell, testTables, temp, "tez");
+  }
+
+  @After
+  public void after() throws Exception {
+    HiveIcebergStorageHandlerTestUtils.close(shell);
+  }
+
+  @Test
+  public void testCherryPick() {
+    TableIdentifier identifier = TableIdentifier.of("default", 
"testCherryPick");
+    shell.executeStatement(String.format("CREATE EXTERNAL TABLE %s (id INT) 
STORED BY iceberg  %s %s",
+            identifier.name(),
+            testTables.locationForCreateTableSQL(identifier),
+            testTables.propertiesForCreateTableSQL(ImmutableMap.of())));
+
+    shell.executeStatement(String.format("INSERT INTO TABLE %s 
VALUES(1),(2),(3),(4)", identifier.name()));
+
+    org.apache.iceberg.Table icebergTable = testTables.loadTable(identifier);
+    long id1 = icebergTable.currentSnapshot().snapshotId();
+
+    // make 2 new inserts to the main branch
+    shell.executeStatement(String.format("INSERT INTO TABLE %s VALUES(5),(6)", 
identifier.name()));
+    shell.executeStatement(String.format("INSERT INTO TABLE %s VALUES(7),(8)", 
identifier.name()));
+
+    icebergTable.refresh();
+    long id2 = icebergTable.currentSnapshot().snapshotId();
+
+    Assert.assertNotEquals(id1, id2);
+
+    // Rollback the table to the previous state before the previous inserts.
+    shell.executeStatement(
+        "ALTER TABLE default.testCherryPick EXECUTE ROLLBACK (" + id1 + ")");
+    // cherry-pick the last snapshot to test1 branch
+    shell.executeStatement("ALTER TABLE default.testCherryPick EXECUTE 
CHERRY-PICK " + id2);
+
+    List<Object[]> result = shell.executeStatement("SELECT COUNT(*) FROM " + 
identifier.name());
+    assertEquals(6L, result.get(0)[0]);
+  }
+}
diff --git 
a/parser/src/java/org/apache/hadoop/hive/ql/parse/AlterClauseParser.g 
b/parser/src/java/org/apache/hadoop/hive/ql/parse/AlterClauseParser.g
index 2fbba1cbc5b..4cb653fed49 100644
--- a/parser/src/java/org/apache/hadoop/hive/ql/parse/AlterClauseParser.g
+++ b/parser/src/java/org/apache/hadoop/hive/ql/parse/AlterClauseParser.g
@@ -481,6 +481,8 @@ alterStatementSuffixExecute
     -> ^(TOK_ALTERTABLE_EXECUTE KW_SET_CURRENT_SNAPSHOT $snapshotParam)
     | KW_EXECUTE KW_FAST_FORWARD sourceBranch=StringLiteral 
(targetBranch=StringLiteral)?
     -> ^(TOK_ALTERTABLE_EXECUTE KW_FAST_FORWARD $sourceBranch $targetBranch?)
+    | KW_EXECUTE KW_CHERRY_PICK snapshotId=Number
+    -> ^(TOK_ALTERTABLE_EXECUTE KW_CHERRY_PICK $snapshotId)
     ;
 
 alterStatementSuffixDropBranch
diff --git a/parser/src/java/org/apache/hadoop/hive/ql/parse/HiveLexerParent.g 
b/parser/src/java/org/apache/hadoop/hive/ql/parse/HiveLexerParent.g
index 0f7e4e5e96c..883b9774ffb 100644
--- a/parser/src/java/org/apache/hadoop/hive/ql/parse/HiveLexerParent.g
+++ b/parser/src/java/org/apache/hadoop/hive/ql/parse/HiveLexerParent.g
@@ -398,6 +398,7 @@ KW_RETAIN: 'RETAIN';
 KW_RETENTION: 'RETENTION';
 KW_TAG: 'TAG';
 KW_FAST_FORWARD: 'FAST-FORWARD';
+KW_CHERRY_PICK: 'CHERRY-PICK';
 
 // Operators
 // NOTE: if you add a new function/operator, add it to sysFuncNames so that 
describe function _FUNC_ will work.
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/execute/AlterTableExecuteAnalyzer.java
 
b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/execute/AlterTableExecuteAnalyzer.java
index 227253de4b8..81ed88849df 100644
--- 
a/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/execute/AlterTableExecuteAnalyzer.java
+++ 
b/ql/src/java/org/apache/hadoop/hive/ql/ddl/table/execute/AlterTableExecuteAnalyzer.java
@@ -33,6 +33,7 @@ import org.apache.hadoop.hive.ql.metadata.Table;
 import org.apache.hadoop.hive.ql.parse.ASTNode;
 import org.apache.hadoop.hive.ql.parse.HiveParser;
 import org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec;
+import org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.CherryPickSpec;
 import 
org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.ExpireSnapshotsSpec;
 import org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.FastForwardSpec;
 import org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.RollbackSpec;
@@ -44,6 +45,7 @@ import java.time.ZoneId;
 import java.util.Map;
 import java.util.regex.Pattern;
 
+import static 
org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.ExecuteOperationType.CHERRY_PICK;
 import static 
org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.ExecuteOperationType.EXPIRE_SNAPSHOT;
 import static 
org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.ExecuteOperationType.FAST_FORWARD;
 import static 
org.apache.hadoop.hive.ql.parse.AlterTableExecuteSpec.ExecuteOperationType.ROLLBACK;
@@ -72,60 +74,92 @@ public class AlterTableExecuteAnalyzer extends 
AbstractAlterTableAnalyzer {
     validateAlterTableType(table, AlterTableType.EXECUTE, false);
     inputs.add(new ReadEntity(table));
     AlterTableExecuteDesc desc = null;
-    if (HiveParser.KW_ROLLBACK == executeCommandType.getType()) {
-      AlterTableExecuteSpec<AlterTableExecuteSpec.RollbackSpec> spec;
-      // the second child must be the rollback parameter
-      ASTNode child = (ASTNode) command.getChild(1);
-
-      if (child.getType() == HiveParser.StringLiteral) {
-        ZoneId timeZone = SessionState.get() == null ? new 
HiveConf().getLocalTimeZone() : SessionState.get().getConf()
-            .getLocalTimeZone();
-        TimestampTZ time = 
TimestampTZUtil.parse(PlanUtils.stripQuotes(child.getText()), timeZone);
-        spec = new AlterTableExecuteSpec(ROLLBACK, new RollbackSpec(TIME, 
time.toEpochMilli()));
-      } else {
-        spec = new AlterTableExecuteSpec(ROLLBACK, new RollbackSpec(VERSION,
-            Long.valueOf(child.getText())));
-      }
-      desc = new AlterTableExecuteDesc(tableName, partitionSpec, spec);
-    } else if (HiveParser.KW_EXPIRE_SNAPSHOTS == executeCommandType.getType()) 
{
-      AlterTableExecuteSpec<AlterTableExecuteSpec.ExpireSnapshotsSpec> spec;
-      // the second child must be the rollback parameter
-      ASTNode child = (ASTNode) command.getChild(1);
-
-      ZoneId timeZone = SessionState.get() == null ? new 
HiveConf().getLocalTimeZone() : SessionState.get().getConf()
-          .getLocalTimeZone();
-      String childText = PlanUtils.stripQuotes(child.getText().trim());
-      if (EXPIRE_SNAPSHOT_BY_ID_REGEX.matcher(childText).matches()) {
-         spec = new AlterTableExecuteSpec(EXPIRE_SNAPSHOT, new 
ExpireSnapshotsSpec(childText));
-      } else {
-        TimestampTZ time = TimestampTZUtil.parse(childText, timeZone);
-        spec = new AlterTableExecuteSpec(EXPIRE_SNAPSHOT, new 
ExpireSnapshotsSpec(time.toEpochMilli()));
-      }
-      desc = new AlterTableExecuteDesc(tableName, partitionSpec, spec);
-    } else if (HiveParser.KW_SET_CURRENT_SNAPSHOT == 
executeCommandType.getType()) {
-      ASTNode child = (ASTNode) command.getChild(1);
-      AlterTableExecuteSpec<AlterTableExecuteSpec.SetCurrentSnapshotSpec> spec 
=
-          new AlterTableExecuteSpec(SET_CURRENT_SNAPSHOT,
-              new 
AlterTableExecuteSpec.SetCurrentSnapshotSpec(Long.valueOf(child.getText())));
-      desc = new AlterTableExecuteDesc(tableName, partitionSpec, spec);
-    } else if (HiveParser.KW_FAST_FORWARD == executeCommandType.getType()) {
-      String branchName;
-      String targetBranchName;
-      ASTNode child1 = (ASTNode) command.getChild(1);
-      if (command.getChildCount() == 2) {
-        branchName = "main";
-        targetBranchName = PlanUtils.stripQuotes(child1.getText());
-      } else {
-        ASTNode child2 = (ASTNode) command.getChild(2);
-        branchName = PlanUtils.stripQuotes(child1.getText());
-        targetBranchName = PlanUtils.stripQuotes(child2.getText());
-      }
-
-      AlterTableExecuteSpec spec =
-          new AlterTableExecuteSpec(FAST_FORWARD, new 
FastForwardSpec(branchName, targetBranchName));
-      desc = new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+    switch (executeCommandType.getType()) {
+      case HiveParser.KW_ROLLBACK:
+        desc = getRollbackDesc(tableName, partitionSpec, (ASTNode) 
command.getChild(1));
+        break;
+      case HiveParser.KW_EXPIRE_SNAPSHOTS:
+        desc = getExpireSnapshotDesc(tableName, partitionSpec, (ASTNode) 
command.getChild(1));
+        break;
+      case HiveParser.KW_SET_CURRENT_SNAPSHOT:
+        desc = getSetCurrentSnapshotDesc(tableName, partitionSpec, (ASTNode) 
command.getChild(1));
+        break;
+      case HiveParser.KW_FAST_FORWARD:
+        desc = getFastForwardDesc(tableName, partitionSpec, command);
+        break;
+      case HiveParser.KW_CHERRY_PICK:
+        desc = getCherryPickDesc(tableName, partitionSpec, (ASTNode) 
command.getChild(1));
+        break;
     }
 
     rootTasks.add(TaskFactory.get(new DDLWork(getInputs(), getOutputs(), 
desc)));
   }
+
+  private static AlterTableExecuteDesc getCherryPickDesc(TableName tableName, 
Map<String, String> partitionSpec,
+      ASTNode childNode) throws SemanticException {
+    long snapshotId = Long.parseLong(childNode.getText());
+    AlterTableExecuteSpec spec = new AlterTableExecuteSpec(CHERRY_PICK, new 
CherryPickSpec(snapshotId));
+    return new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+  }
+
+  private static AlterTableExecuteDesc getFastForwardDesc(TableName tableName, 
Map<String, String> partitionSpec,
+      ASTNode command) throws SemanticException {
+    String branchName;
+    String targetBranchName;
+    ASTNode child1 = (ASTNode) command.getChild(1);
+    if (command.getChildCount() == 2) {
+      branchName = "main";
+      targetBranchName = PlanUtils.stripQuotes(child1.getText());
+    } else {
+      ASTNode child2 = (ASTNode) command.getChild(2);
+      branchName = PlanUtils.stripQuotes(child1.getText());
+      targetBranchName = PlanUtils.stripQuotes(child2.getText());
+    }
+
+    AlterTableExecuteSpec spec =
+        new AlterTableExecuteSpec(FAST_FORWARD, new 
FastForwardSpec(branchName, targetBranchName));
+    return new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+  }
+
+  private static AlterTableExecuteDesc getSetCurrentSnapshotDesc(TableName 
tableName, Map<String, String> partitionSpec,
+      ASTNode childNode) throws SemanticException {
+    AlterTableExecuteSpec<AlterTableExecuteSpec.SetCurrentSnapshotSpec> spec =
+        new AlterTableExecuteSpec(SET_CURRENT_SNAPSHOT,
+            new 
AlterTableExecuteSpec.SetCurrentSnapshotSpec(Long.valueOf(childNode.getText())));
+    return new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+  }
+
+  private static AlterTableExecuteDesc getExpireSnapshotDesc(TableName 
tableName, Map<String, String> partitionSpec,
+      ASTNode childNode) throws SemanticException {
+    AlterTableExecuteSpec<ExpireSnapshotsSpec> spec;
+    // the second child must be the rollback parameter
+
+    ZoneId timeZone = SessionState.get() == null ?
+        new HiveConf().getLocalTimeZone() :
+        SessionState.get().getConf().getLocalTimeZone();
+    String childText = PlanUtils.stripQuotes(childNode.getText().trim());
+    if (EXPIRE_SNAPSHOT_BY_ID_REGEX.matcher(childText).matches()) {
+      spec = new AlterTableExecuteSpec(EXPIRE_SNAPSHOT, new 
ExpireSnapshotsSpec(childText));
+    } else {
+      TimestampTZ time = TimestampTZUtil.parse(childText, timeZone);
+      spec = new AlterTableExecuteSpec(EXPIRE_SNAPSHOT, new 
ExpireSnapshotsSpec(time.toEpochMilli()));
+    }
+    return new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+  }
+
+  private static AlterTableExecuteDesc getRollbackDesc(TableName tableName, 
Map<String, String> partitionSpec,
+      ASTNode childNode) throws SemanticException {
+    AlterTableExecuteSpec<RollbackSpec> spec;
+    // the child must be the rollback parameter
+    if (childNode.getType() == HiveParser.StringLiteral) {
+      ZoneId timeZone = SessionState.get() == null ?
+          new HiveConf().getLocalTimeZone() :
+          SessionState.get().getConf().getLocalTimeZone();
+      TimestampTZ time = 
TimestampTZUtil.parse(PlanUtils.stripQuotes(childNode.getText()), timeZone);
+      spec = new AlterTableExecuteSpec(ROLLBACK, new RollbackSpec(TIME, 
time.toEpochMilli()));
+    } else {
+      spec = new AlterTableExecuteSpec(ROLLBACK, new RollbackSpec(VERSION, 
Long.valueOf(childNode.getText())));
+    }
+    return new AlterTableExecuteDesc(tableName, partitionSpec, spec);
+  }
 }
diff --git 
a/ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java 
b/ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java
index 692f73b55f0..fefeb267c29 100644
--- a/ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java
+++ b/ql/src/java/org/apache/hadoop/hive/ql/parse/AlterTableExecuteSpec.java
@@ -37,7 +37,8 @@ public class AlterTableExecuteSpec<T> {
     ROLLBACK,
     EXPIRE_SNAPSHOT,
     SET_CURRENT_SNAPSHOT,
-    FAST_FORWARD
+    FAST_FORWARD,
+    CHERRY_PICK;
   }
 
   private final ExecuteOperationType operationType;
@@ -193,4 +194,27 @@ public class AlterTableExecuteSpec<T> {
           .add("targetBranch", targetBranch).toString();
     }
   }
+
+  /**
+   * Value object class, that stores the cherry-pick operation specific 
parameters.
+   * <ul>
+   *   <li>snapshotId: the snapshotId which needs to be cherry-picked</li>
+   * </ul>
+   */
+  public static class CherryPickSpec {
+    private final long snapshotId;
+
+    public CherryPickSpec(long snapshotId) {
+      this.snapshotId = snapshotId;
+    }
+
+    public long getSnapshotId() {
+      return snapshotId;
+    }
+
+    @Override
+    public String toString() {
+      return MoreObjects.toStringHelper(this).add("snapshotId", 
snapshotId).toString();
+    }
+  }
 }

Reply via email to