pvary commented on code in PR #8907:
URL: https://github.com/apache/iceberg/pull/8907#discussion_r1405917923


##########
hive-metastore/src/main/java/org/apache/iceberg/hive/HiveViewOperations.java:
##########
@@ -0,0 +1,315 @@
+/*
+ * 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.hive;
+
+import java.util.Locale;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicReference;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hive.metastore.IMetaStoreClient;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.iceberg.BaseMetastoreTableOperations;
+import org.apache.iceberg.ClientPool;
+import org.apache.iceberg.TableProperties;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.exceptions.AlreadyExistsException;
+import org.apache.iceberg.exceptions.CommitFailedException;
+import org.apache.iceberg.exceptions.CommitStateUnknownException;
+import org.apache.iceberg.exceptions.NoSuchViewException;
+import org.apache.iceberg.exceptions.ValidationException;
+import org.apache.iceberg.hive.HiveCatalogUtil.CommitStatus;
+import org.apache.iceberg.io.FileIO;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.util.Tasks;
+import org.apache.iceberg.view.BaseViewOperations;
+import org.apache.iceberg.view.ViewMetadata;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/** Hive implementation of Iceberg ViewOperations. */
+final class HiveViewOperations extends BaseViewOperations implements 
HiveOperationsBase {
+  private static final Logger LOG = 
LoggerFactory.getLogger(HiveViewOperations.class);
+
+  private final String fullName;
+  private final String database;
+  private final String viewName;
+  private final FileIO fileIO;
+  private final ClientPool<IMetaStoreClient, TException> metaClients;
+  private final long maxHiveTablePropertySize;
+
+  HiveViewOperations(
+      Configuration conf,
+      ClientPool<IMetaStoreClient, TException> metaClients,
+      FileIO fileIO,
+      String catalogName,
+      TableIdentifier viewIdentifier) {
+    String dbName = viewIdentifier.namespace().level(0);
+    this.metaClients = metaClients;
+    this.fileIO = fileIO;
+    this.fullName = catalogName + "." + dbName + "." + viewIdentifier.name();
+    this.database = dbName;
+    this.viewName = viewIdentifier.name();
+    this.maxHiveTablePropertySize =
+        conf.getLong(HIVE_TABLE_PROPERTY_MAX_SIZE, 
HIVE_TABLE_PROPERTY_MAX_SIZE_DEFAULT);
+  }
+
+  @Override
+  public void doRefresh() {
+    String metadataLocation = null;
+    Table table = null;
+
+    try {
+      table = metaClients.run(client -> client.getTable(database, viewName));
+      HiveOperationsBase.validateTableIsIceberg(table, fullName);
+      metadataLocation =
+          
table.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP);
+
+    } catch (NoSuchObjectException e) {
+      if (currentMetadataLocation() != null) {
+        throw new NoSuchViewException("View does not exist: %s.%s", database, 
viewName);
+      }
+    } catch (TException e) {
+      String errMsg =
+          String.format("Failed to get view info from metastore %s.%s", 
database, viewName);
+      throw new RuntimeException(errMsg, e);
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new RuntimeException("Interrupted during refresh", e);
+    }
+
+    if (table != null && 
!table.getTableType().equalsIgnoreCase(TableType.VIRTUAL_VIEW.name())) {
+      disableRefresh();
+    } else {
+      refreshFromMetadataLocation(metadataLocation);
+    }
+  }
+
+  @SuppressWarnings("checkstyle:CyclomaticComplexity")
+  @Override
+  public void doCommit(ViewMetadata base, ViewMetadata metadata) {
+    boolean newView = base == null;
+    String newMetadataLocation = writeNewMetadataIfRequired(metadata);
+    boolean updateHiveView = false;
+    CommitStatus commitStatus = CommitStatus.FAILURE;
+
+    try {
+      Optional<Table> hmsTable =
+          HiveCatalogUtil.loadHmsTableIfPresent(metaClients, database, 
viewName);
+      Table view;
+
+      if (hmsTable.isPresent()) {
+        view = hmsTable.get();
+
+        // If we try to create the view but the metadata location is already 
set, then we had a
+        // concurrent commit
+        if 
(!view.getTableType().equalsIgnoreCase(TableType.VIRTUAL_VIEW.name())) {
+          throw new AlreadyExistsException(
+              "Table with same name already exists: %s.%s", database, 
viewName);
+        }
+
+        if (newView
+            && 
view.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP)
+                != null) {
+          throw new AlreadyExistsException("View already exists: %s.%s", 
database, viewName);
+        }
+
+        updateHiveView = true;
+        LOG.debug("Committing existing view: {}", fullName);
+      } else {
+        view =
+            newHmsTable(
+                metadata
+                    .properties()
+                    .getOrDefault(HiveCatalog.HMS_TABLE_OWNER, 
HiveHadoopUtil.currentUser()));
+        LOG.debug("Committing new view: {}", fullName);
+      }
+
+      view.setSd(
+          HiveOperationsBase.storageDescriptor(
+              metadata.schema(), metadata.location(), false)); // set to 
pickup any schema changes
+
+      String metadataLocation =
+          
view.getParameters().get(BaseMetastoreTableOperations.METADATA_LOCATION_PROP);
+      String baseMetadataLocation = base != null ? base.metadataFileLocation() 
: null;
+
+      if (!Objects.equals(baseMetadataLocation, metadataLocation)) {
+        throw new CommitFailedException(
+            "Base metadata location '%s' is not same as the current view 
metadata location '%s' for %s.%s",
+            baseMetadataLocation, metadataLocation, database, viewName);
+      }
+
+      setHmsTableParameters(newMetadataLocation, view, metadata);
+
+      try {
+        persistTable(view, updateHiveView, baseMetadataLocation);
+        commitStatus = CommitStatus.SUCCESS;
+      } catch (org.apache.hadoop.hive.metastore.api.AlreadyExistsException e) {
+        HiveCatalogUtil.matchAndThrowExistenceTypeException(view);
+      } catch (InvalidObjectException e) {
+        throw new ValidationException(e, "Invalid Hive object for %s.%s", 
database, viewName);
+      } catch (CommitFailedException | CommitStateUnknownException e) {
+        throw e;
+      } catch (Throwable e) {
+        if (e.getMessage()
+            .contains(
+                "The view has been modified. The parameter value for key '"
+                    + BaseMetastoreTableOperations.METADATA_LOCATION_PROP
+                    + "' is")) {
+          throw new CommitFailedException(
+              e, "The view %s.%s has been modified concurrently", database, 
viewName);
+        }
+
+        LOG.error(
+            "Cannot tell if commit to {}.{} succeeded, attempting to reconnect 
and check.",
+            database,
+            viewName,
+            e);
+
+        commitStatus = checkCommitStatus(newMetadataLocation);
+
+        switch (commitStatus) {
+          case SUCCESS:
+            break;
+          case FAILURE:
+            throw e;
+          case UNKNOWN:
+            throw new CommitStateUnknownException(e);
+        }
+      }
+    } catch (TException e) {
+      throw new RuntimeException(
+          String.format("Metastore operation failed for %s.%s", database, 
viewName), e);
+
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      throw new RuntimeException("Interrupted during commit", e);
+
+    } catch (LockException e) {
+      throw new CommitFailedException(e);
+    } finally {
+      HiveOperationsBase.cleanupMetadata(fileIO, commitStatus.name(), 
newMetadataLocation);
+    }
+
+    LOG.info(
+        "Committed to view {} with the new metadata location {}", fullName, 
newMetadataLocation);
+  }
+
+  private CommitStatus checkCommitStatus(String newMetadataLocation) {

Review Comment:
   What is the difference between this method, and the 
`BaseMetastoreTableOperations.checkCommitStatus`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to