You are viewing a plain text version of this content. The canonical link for it is here.
Posted to gitbox@hive.apache.org by "dengzhhu653 (via GitHub)" <gi...@apache.org> on 2026/01/14 11:05:59 UTC

[PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

dengzhhu653 opened a new pull request, #6269:
URL: https://github.com/apache/hive/pull/6269

   <!--
   Thanks for sending a pull request!  Here are some tips for you:
     1. If this is your first time, please read our contributor guidelines: https://cwiki.apache.org/confluence/display/Hive/HowToContribute
     2. Ensure that you have created an issue on the Hive project JIRA: https://issues.apache.org/jira/projects/HIVE/summary
     3. Ensure you have added or run the appropriate tests for your PR: 
     4. If the PR is unfinished, add '[WIP]' in your PR title, e.g., '[WIP]HIVE-XXXXX:  Your PR title ...'.
     5. Be sure to keep the PR description updated to reflect all changes.
     6. Please write your PR title to summarize what this PR proposes.
     7. If possible, provide a concise example to reproduce the issue for a faster review.
   
   -->
   
   ### What changes were proposed in this pull request?
   <!--
   Please clarify what changes you are proposing. The purpose of this section is to outline the changes and how this PR fixes the issue. 
   If possible, please consider writing useful notes for better and faster reviews in your PR. See the examples below.
     1. If you refactor some codes with changing classes, showing the class hierarchy will help reviewers.
     2. If you fix some SQL features, you can provide some references of other DBMSes.
     3. If there is design documentation, please add the link.
     4. If there is a discussion in the mailing list, please add the link.
   -->
   
   
   ### Why are the changes needed?
   <!--
   Please clarify why the changes are needed. For instance,
     1. If you propose a new API, clarify the use case for a new API.
     2. If you fix a bug, you can clarify why it is a bug.
   -->
   
   
   ### Does this PR introduce _any_ user-facing change?
   <!--
   Note that it means *any* user-facing change including all aspects such as the documentation fix.
   If yes, please clarify the previous behavior and the change this PR proposes - provide the console output, description, screenshot and/or a reproducable example to show the behavior difference if possible.
   If possible, please also clarify if this is a user-facing change compared to the released Hive versions or within the unreleased branches such as master.
   If no, write 'No'.
   -->
   
   ### How was this patch tested?
   <!--
   If tests were added, say they were added here. Please make sure to add some test cases that check the changes thoroughly including negative and positive cases if possible.
   If it was tested in a way different from regular unit tests, please clarify how you tested step by step, ideally copy and paste-able, so that other reviewers can test and check, and descendants can verify in the future.
   If tests were not added, please describe why they were not added and/or why it was difficult to add.
   -->
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2739434674


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Thanks for the comments.
   The reason is it's not easy to make it as a static method, I'm agree with the reuse, filed HIVE-29407 with the optimization



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2702950263


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/AbstractRequestHandler.java:
##########
@@ -107,45 +108,49 @@ public abstract class AbstractOperationHandler<T extends TBase, A extends Abstra
   protected final String id;
   private long timeout;
 
-  private AbstractOperationHandler(String id) {
+  private AbstractRequestHandler(String id) {
     this.id = id;
   }
 
-  AbstractOperationHandler(IHMSHandler handler, boolean async, T request) {
-    this.id = UUID.randomUUID().toString();
+  AbstractRequestHandler(IHMSHandler handler, boolean async, T request) {
+    this.id = UUID.randomUUID() + "-" + ID_GEN.incrementAndGet();
     this.handler = handler;
     this.request = request;
     this.async = async;
     this.timeout = MetastoreConf.getBoolVar(handler.getConf(), HIVE_IN_TEST) ? 10 : 5000;
-    final Timer.Context timerContext;
-    if (getHandlerAlias() != null) {
-      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getHandlerAlias());
-      timerContext = timer != null ? timer.time() : null;
-    } else {
-      timerContext = null;
-    }
 
     if (async) {
-      OPID_TO_HANDLER.put(id, this);
+      ID_TO_HANDLER.put(id, this);
       this.executor = Executors.newFixedThreadPool(1, r -> {
         Thread thread = new Thread(r);
         thread.setDaemon(true);
-        thread.setName("OperationHandler[" + id + "]");
+        thread.setName("RequestHandler[" + id + "]");
         return thread;
       });
     } else {
       this.executor = MoreExecutors.newDirectExecutorService();
     }
+    this.future = executeRequest();
+  }
+
+  private Future<Result> executeRequest() {
+    Timer.Context timerContext;
+    if (StringUtils.isNotEmpty(getMetricAlias())) {
+      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getMetricAlias());

Review Comment:
   it just a simple call, no reflection here



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/AbstractRequestHandler.java:
##########
@@ -107,45 +108,49 @@ public abstract class AbstractOperationHandler<T extends TBase, A extends Abstra
   protected final String id;
   private long timeout;
 
-  private AbstractOperationHandler(String id) {
+  private AbstractRequestHandler(String id) {
     this.id = id;
   }
 
-  AbstractOperationHandler(IHMSHandler handler, boolean async, T request) {
-    this.id = UUID.randomUUID().toString();
+  AbstractRequestHandler(IHMSHandler handler, boolean async, T request) {
+    this.id = UUID.randomUUID() + "-" + ID_GEN.incrementAndGet();
     this.handler = handler;
     this.request = request;
     this.async = async;
     this.timeout = MetastoreConf.getBoolVar(handler.getConf(), HIVE_IN_TEST) ? 10 : 5000;
-    final Timer.Context timerContext;
-    if (getHandlerAlias() != null) {
-      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getHandlerAlias());
-      timerContext = timer != null ? timer.time() : null;
-    } else {
-      timerContext = null;
-    }
 
     if (async) {
-      OPID_TO_HANDLER.put(id, this);
+      ID_TO_HANDLER.put(id, this);
       this.executor = Executors.newFixedThreadPool(1, r -> {
         Thread thread = new Thread(r);
         thread.setDaemon(true);
-        thread.setName("OperationHandler[" + id + "]");
+        thread.setName("RequestHandler[" + id + "]");
         return thread;
       });
     } else {
       this.executor = MoreExecutors.newDirectExecutorService();
     }
+    this.future = executeRequest();
+  }
+
+  private Future<Result> executeRequest() {
+    Timer.Context timerContext;
+    if (StringUtils.isNotEmpty(getMetricAlias())) {
+      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getMetricAlias());

Review Comment:
   it's just a simple call, no reflection here



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3758900848

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [31 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2702945307


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/AbstractRequestHandler.java:
##########
@@ -35,65 +37,64 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
 
+import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hive.metastore.IHMSHandler;
-import org.apache.hadoop.hive.metastore.api.AddPartitionsRequest;
 import org.apache.hadoop.hive.metastore.api.AsyncOperationResp;
-import org.apache.hadoop.hive.metastore.api.DropDatabaseRequest;
-import org.apache.hadoop.hive.metastore.api.DropPartitionsRequest;
-import org.apache.hadoop.hive.metastore.api.DropTableRequest;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
 import org.apache.hadoop.hive.metastore.metrics.Metrics;
 import org.apache.hadoop.hive.metastore.metrics.MetricsConstants;
 import org.apache.thrift.TBase;
 import org.apache.thrift.TException;
+import org.reflections.Reflections;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.apache.hadoop.hive.metastore.ExceptionHandler.handleException;
 import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.HIVE_IN_TEST;
-
-public abstract class AbstractOperationHandler<T extends TBase, A extends AbstractOperationHandler.Result> {
-
-  private static final Logger LOG = LoggerFactory.getLogger(AbstractOperationHandler.class);
-  private static final Map<String, AbstractOperationHandler> OPID_TO_HANDLER = new ConcurrentHashMap<>();
-  private static final ScheduledExecutorService OPID_CLEANER = Executors.newScheduledThreadPool(1, r -> {
+import static org.apache.hadoop.hive.metastore.utils.JavaUtils.getField;
+import static org.apache.hadoop.hive.metastore.utils.JavaUtils.newInstance;
+
+public abstract class AbstractRequestHandler<T extends TBase, A extends AbstractRequestHandler.Result> {
+  private static final Logger LOG = LoggerFactory.getLogger(AbstractRequestHandler.class);
+  private static final Map<String, AbstractRequestHandler> ID_TO_HANDLER = new ConcurrentHashMap<>();
+  private static final AtomicLong ID_GEN = new AtomicLong(0);
+  private static final ScheduledExecutorService REQUEST_CLEANER = Executors.newScheduledThreadPool(1, r -> {
     Thread thread = new Thread(r);
     thread.setDaemon(true);
-    thread.setName("OperationHandler-Cleaner");
+    thread.setName("RequestHandler-Cleaner");
     return thread;
   });
 
   private static final Map<Class<? extends TBase>, HandlerFactory> REQ_FACTORIES = new ConcurrentHashMap<>();
   static {
-    REQ_FACTORIES.put(DropTableRequest.class, (base, request) -> {
-      DropTableRequest req = (DropTableRequest) request;
-      AbstractOperationHandler opHandler = ofCache(req.getId(), req.isCancel());
-      if (opHandler == null) {
-        opHandler = new DropTableHandler(base, req);
+    Set<Class<? extends AbstractRequestHandler>> handlerClasses =
+        new Reflections("org.apache.hadoop.hive.metastore.handler").getSubTypesOf(AbstractRequestHandler.class);
+    for (Class<? extends AbstractRequestHandler> clz : handlerClasses) {
+      if (Modifier.isAbstract(clz.getModifiers())) {
+        continue;
       }
-      return opHandler;
-    });
-
-    REQ_FACTORIES.put(DropDatabaseRequest.class, (base, request) -> {
-      DropDatabaseRequest req = (DropDatabaseRequest) request;
-      AbstractOperationHandler opHandler = ofCache(req.getId(), req.isCancel());
-      if (opHandler == null) {
-        opHandler = new DropDatabaseHandler(base, req);
+      RequestHandler handler = clz.getAnnotation(RequestHandler.class);
+      Class<? extends TBase> requestBody;
+      if (handler == null || (requestBody = handler.requestBody()) == null) {
+        continue;

Review Comment:
   ack



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2744405294


##########
standalone-metastore/metastore-server/pom.xml:
##########
@@ -23,6 +23,7 @@
   <name>Hive Metastore Server</name>
   <properties>
     <standalone.metastore.path.to.root>..</standalone.metastore.path.to.root>
+    <reflections.version>0.10.2</reflections.version>

Review Comment:
   will address it in the follow-ups



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3753288170

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [39 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3766304502

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [29 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3749590291

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [25 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "wecharyu (via GitHub)" <gi...@apache.org>.
wecharyu commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2737581987


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/DropDatabaseHandler.java:
##########
@@ -457,12 +457,16 @@ protected void afterExecute(DropDatabaseResult result) throws MetaException, IOE
         }
       }
     } finally {
+      super.afterExecute(result);
+      if (async) {
+        rs.shutdown();

Review Comment:
   Got it.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Try to reuse `HMSHandler#updateTableColumnStatsInternal `.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3760546502

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [31 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2702948572


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/RequestHandler.java:
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.metastore.handler;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.thrift.TBase;
+
+@InterfaceStability.Evolving
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequestHandler {
+  Class<? extends TBase> requestBody();
+  boolean supportAsync() default false;
+  String id() default "getId";
+  String cancel() default "isCancel";

Review Comment:
   when creating the handler, it knows what the request is, and how to get the async id from the request at the definition.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "wecharyu (via GitHub)" <gi...@apache.org>.
wecharyu commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2702549769


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/DropTableHandler.java:
##########
@@ -206,6 +210,10 @@ protected void afterExecute(DropTableResult result) throws MetaException, IOExce
       }
     } finally {
       super.afterExecute(result);
+      if (async) {
+        ms.shutdown();

Review Comment:
   ditto.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/AbstractRequestHandler.java:
##########
@@ -107,45 +108,49 @@ public abstract class AbstractOperationHandler<T extends TBase, A extends Abstra
   protected final String id;
   private long timeout;
 
-  private AbstractOperationHandler(String id) {
+  private AbstractRequestHandler(String id) {
     this.id = id;
   }
 
-  AbstractOperationHandler(IHMSHandler handler, boolean async, T request) {
-    this.id = UUID.randomUUID().toString();
+  AbstractRequestHandler(IHMSHandler handler, boolean async, T request) {
+    this.id = UUID.randomUUID() + "-" + ID_GEN.incrementAndGet();
     this.handler = handler;
     this.request = request;
     this.async = async;
     this.timeout = MetastoreConf.getBoolVar(handler.getConf(), HIVE_IN_TEST) ? 10 : 5000;
-    final Timer.Context timerContext;
-    if (getHandlerAlias() != null) {
-      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getHandlerAlias());
-      timerContext = timer != null ? timer.time() : null;
-    } else {
-      timerContext = null;
-    }
 
     if (async) {
-      OPID_TO_HANDLER.put(id, this);
+      ID_TO_HANDLER.put(id, this);
       this.executor = Executors.newFixedThreadPool(1, r -> {
         Thread thread = new Thread(r);
         thread.setDaemon(true);
-        thread.setName("OperationHandler[" + id + "]");
+        thread.setName("RequestHandler[" + id + "]");
         return thread;
       });
     } else {
       this.executor = MoreExecutors.newDirectExecutorService();
     }
+    this.future = executeRequest();
+  }
+
+  private Future<Result> executeRequest() {
+    Timer.Context timerContext;
+    if (StringUtils.isNotEmpty(getMetricAlias())) {
+      Timer timer = Metrics.getOrCreateTimer(MetricsConstants.API_PREFIX + getMetricAlias());

Review Comment:
   will multi reflection calls affect the performance?



##########
standalone-metastore/metastore-common/src/main/java/org/apache/hadoop/hive/metastore/utils/JavaUtils.java:
##########
@@ -128,6 +128,18 @@ public static <T> void setField(T req, String methodName, Class[] argsCls, Objec
     }
   }
 
+  public static <T> T getField(Object payload, String methodName) {

Review Comment:
   Can we use a common method for both `setField` and `getField` like:
   ```java
   public static <T> T invokeMethod(Object payload, String methodName, Class<?>[] paramTypes, Object... args);
   ```



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/DropDatabaseHandler.java:
##########
@@ -457,12 +457,16 @@ protected void afterExecute(DropDatabaseResult result) throws MetaException, IOE
         }
       }
     } finally {
+      super.afterExecute(result);
+      if (async) {
+        rs.shutdown();

Review Comment:
   why cleanup rs here? it will be cleaned if connection is closed in `HMSHandler.cleanupHandlerContext()`.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/AbstractRequestHandler.java:
##########
@@ -35,65 +37,64 @@
 import java.util.concurrent.TimeUnit;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
 
+import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hive.metastore.IHMSHandler;
-import org.apache.hadoop.hive.metastore.api.AddPartitionsRequest;
 import org.apache.hadoop.hive.metastore.api.AsyncOperationResp;
-import org.apache.hadoop.hive.metastore.api.DropDatabaseRequest;
-import org.apache.hadoop.hive.metastore.api.DropPartitionsRequest;
-import org.apache.hadoop.hive.metastore.api.DropTableRequest;
 import org.apache.hadoop.hive.metastore.api.MetaException;
 import org.apache.hadoop.hive.metastore.conf.MetastoreConf;
 import org.apache.hadoop.hive.metastore.metrics.Metrics;
 import org.apache.hadoop.hive.metastore.metrics.MetricsConstants;
 import org.apache.thrift.TBase;
 import org.apache.thrift.TException;
+import org.reflections.Reflections;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
 import static org.apache.hadoop.hive.metastore.ExceptionHandler.handleException;
 import static org.apache.hadoop.hive.metastore.conf.MetastoreConf.ConfVars.HIVE_IN_TEST;
-
-public abstract class AbstractOperationHandler<T extends TBase, A extends AbstractOperationHandler.Result> {
-
-  private static final Logger LOG = LoggerFactory.getLogger(AbstractOperationHandler.class);
-  private static final Map<String, AbstractOperationHandler> OPID_TO_HANDLER = new ConcurrentHashMap<>();
-  private static final ScheduledExecutorService OPID_CLEANER = Executors.newScheduledThreadPool(1, r -> {
+import static org.apache.hadoop.hive.metastore.utils.JavaUtils.getField;
+import static org.apache.hadoop.hive.metastore.utils.JavaUtils.newInstance;
+
+public abstract class AbstractRequestHandler<T extends TBase, A extends AbstractRequestHandler.Result> {
+  private static final Logger LOG = LoggerFactory.getLogger(AbstractRequestHandler.class);
+  private static final Map<String, AbstractRequestHandler> ID_TO_HANDLER = new ConcurrentHashMap<>();
+  private static final AtomicLong ID_GEN = new AtomicLong(0);
+  private static final ScheduledExecutorService REQUEST_CLEANER = Executors.newScheduledThreadPool(1, r -> {
     Thread thread = new Thread(r);
     thread.setDaemon(true);
-    thread.setName("OperationHandler-Cleaner");
+    thread.setName("RequestHandler-Cleaner");
     return thread;
   });
 
   private static final Map<Class<? extends TBase>, HandlerFactory> REQ_FACTORIES = new ConcurrentHashMap<>();
   static {
-    REQ_FACTORIES.put(DropTableRequest.class, (base, request) -> {
-      DropTableRequest req = (DropTableRequest) request;
-      AbstractOperationHandler opHandler = ofCache(req.getId(), req.isCancel());
-      if (opHandler == null) {
-        opHandler = new DropTableHandler(base, req);
+    Set<Class<? extends AbstractRequestHandler>> handlerClasses =
+        new Reflections("org.apache.hadoop.hive.metastore.handler").getSubTypesOf(AbstractRequestHandler.class);
+    for (Class<? extends AbstractRequestHandler> clz : handlerClasses) {
+      if (Modifier.isAbstract(clz.getModifiers())) {
+        continue;
       }
-      return opHandler;
-    });
-
-    REQ_FACTORIES.put(DropDatabaseRequest.class, (base, request) -> {
-      DropDatabaseRequest req = (DropDatabaseRequest) request;
-      AbstractOperationHandler opHandler = ofCache(req.getId(), req.isCancel());
-      if (opHandler == null) {
-        opHandler = new DropDatabaseHandler(base, req);
+      RequestHandler handler = clz.getAnnotation(RequestHandler.class);
+      Class<? extends TBase> requestBody;
+      if (handler == null || (requestBody = handler.requestBody()) == null) {
+        continue;

Review Comment:
   Can we check this in `validateHandler()`? return request body if exists otherwise throw exception.



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/RequestHandler.java:
##########
@@ -0,0 +1,35 @@
+/*
+ * 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.metastore.handler;
+
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+
+import org.apache.hadoop.classification.InterfaceStability;
+import org.apache.thrift.TBase;
+
+@InterfaceStability.Evolving
+@Retention(RetentionPolicy.RUNTIME)
+public @interface RequestHandler {
+  Class<? extends TBase> requestBody();
+  boolean supportAsync() default false;
+  String id() default "getId";
+  String cancel() default "isCancel";

Review Comment:
   `id` and `cancel` is from request, it seems a little strange to set get such annotations for handler.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2739434674


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Thanks for the comments.
   The reason is it's not easy to make it as a static method, I'm agree with the reuse, filed HIVE-29407 with the optimization



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3768304984

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [41 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.8% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2702951585


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/DropDatabaseHandler.java:
##########
@@ -457,12 +457,16 @@ protected void afterExecute(DropDatabaseResult result) throws MetaException, IOE
         }
       }
     } finally {
+      super.afterExecute(result);
+      if (async) {
+        rs.shutdown();

Review Comment:
   no, if this handler is running in background thread, HMSHandler.cleanupHandlerContext() will just clean the main thread which creates this backed thread.



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2739438328


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Thanks for the comments.
   The reason is it's not easy to make it as a static method, I'm agree with the reuse, filed HIVE-29407 to follow with the optimization



##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Thanks for the comments.
   The reason is it's not easy to make it as a static method, I'm agree with the reuse, filed HIVE-29407 with the optimization



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "saihemanth-cloudera (via GitHub)" <gi...@apache.org>.
saihemanth-cloudera commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2743828713


##########
standalone-metastore/metastore-server/pom.xml:
##########
@@ -23,6 +23,7 @@
   <name>Hive Metastore Server</name>
   <properties>
     <standalone.metastore.path.to.root>..</standalone.metastore.path.to.root>
+    <reflections.version>0.10.2</reflections.version>

Review Comment:
   nit: this could be moved to standalone-metstore/pom.xml



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3821540490

   Thank you @wecharyu, @saihemanth-cloudera  for the review!


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3757402290

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [31 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3767014746

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [29 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3753635343

   cc @wecharyu @saihemanth-cloudera could you take a look if have secs? thank you!


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3754563329

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [50 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.5% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "sonarqubecloud[bot] (via GitHub)" <gi...@apache.org>.
sonarqubecloud[bot] commented on PR #6269:
URL: https://github.com/apache/hive/pull/6269#issuecomment-3755833454

   ## [![Quality Gate Passed](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/checks/QualityGateBadge/qg-passed-20px.png 'Quality Gate Passed')](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269) **Quality Gate passed**  
   Issues  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [31 New issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/accepted-16px.png '') [0 Accepted issues](https://sonarcloud.io/project/issues?id=apache_hive&pullRequest=6269&issueStatuses=ACCEPTED)
   
   Measures  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0 Security Hotspots](https://sonarcloud.io/project/security_hotspots?id=apache_hive&pullRequest=6269&issueStatuses=OPEN,CONFIRMED&sinceLeakPeriod=true)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.0% Coverage on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_coverage&view=list)  
   ![](https://sonarsource.github.io/sonarcloud-github-static-resources/v2/common/passed-16px.png '') [0.6% Duplication on New Code](https://sonarcloud.io/component_measures?id=apache_hive&pullRequest=6269&metric=new_duplicated_lines_density&view=list)  
     
   [See analysis details on SonarQube Cloud](https://sonarcloud.io/dashboard?id=apache_hive&pullRequest=6269)
   
   


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 merged PR #6269:
URL: https://github.com/apache/hive/pull/6269


-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org


Re: [PR] HIVE-29403: Move the truncate table out of HMSHandler [hive]

Posted by "dengzhhu653 (via GitHub)" <gi...@apache.org>.
dengzhhu653 commented on code in PR #6269:
URL: https://github.com/apache/hive/pull/6269#discussion_r2739435740


##########
standalone-metastore/metastore-server/src/main/java/org/apache/hadoop/hive/metastore/handler/CreateTableHandler.java:
##########
@@ -0,0 +1,456 @@
+/*
+ * 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.metastore.handler;
+
+import java.io.IOException;
+import java.util.BitSet;
+import java.util.Collections;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.collections4.CollectionUtils;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.common.TableName;
+import org.apache.hadoop.hive.common.ValidReaderWriteIdList;
+import org.apache.hadoop.hive.common.ValidWriteIdList;
+import org.apache.hadoop.hive.metastore.HMSHandler;
+import org.apache.hadoop.hive.metastore.IHMSHandler;
+import org.apache.hadoop.hive.metastore.IMetaStoreMetadataTransformer;
+import org.apache.hadoop.hive.metastore.MetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.MetaStoreListenerNotifier;
+import org.apache.hadoop.hive.metastore.RawStore;
+import org.apache.hadoop.hive.metastore.ReplChangeManager;
+import org.apache.hadoop.hive.metastore.TableType;
+import org.apache.hadoop.hive.metastore.TransactionalMetaStoreEventListener;
+import org.apache.hadoop.hive.metastore.Warehouse;
+import org.apache.hadoop.hive.metastore.api.AlreadyExistsException;
+import org.apache.hadoop.hive.metastore.api.ColumnStatistics;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsDesc;
+import org.apache.hadoop.hive.metastore.api.ColumnStatisticsObj;
+import org.apache.hadoop.hive.metastore.api.CreateTableRequest;
+import org.apache.hadoop.hive.metastore.api.Database;
+import org.apache.hadoop.hive.metastore.api.EnvironmentContext;
+import org.apache.hadoop.hive.metastore.api.InvalidInputException;
+import org.apache.hadoop.hive.metastore.api.InvalidObjectException;
+import org.apache.hadoop.hive.metastore.api.MetaException;
+import org.apache.hadoop.hive.metastore.api.NoSuchObjectException;
+import org.apache.hadoop.hive.metastore.api.SQLAllTableConstraints;
+import org.apache.hadoop.hive.metastore.api.SkewedInfo;
+import org.apache.hadoop.hive.metastore.api.Table;
+import org.apache.hadoop.hive.metastore.api.hive_metastoreConstants;
+import org.apache.hadoop.hive.metastore.events.AddCheckConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddDefaultConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddForeignKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddNotNullConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.AddPrimaryKeyEvent;
+import org.apache.hadoop.hive.metastore.events.AddUniqueConstraintEvent;
+import org.apache.hadoop.hive.metastore.events.CreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.PreCreateTableEvent;
+import org.apache.hadoop.hive.metastore.events.UpdateTableColumnStatEvent;
+import org.apache.hadoop.hive.metastore.messaging.EventMessage;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils;
+import org.apache.hadoop.hive.metastore.utils.MetaStoreUtils;
+import org.apache.thrift.TException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import static org.apache.hadoop.hive.common.AcidConstants.DELTA_DIGITS;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_PATH_SUFFIX;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE;
+import static org.apache.hadoop.hive.common.AcidConstants.SOFT_DELETE_TABLE_PATTERN;
+import static org.apache.hadoop.hive.metastore.Warehouse.getCatalogQualifiedTableName;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.CTAS_LEGACY_CONFIG;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTAS;
+import static org.apache.hadoop.hive.metastore.api.hive_metastoreConstants.TABLE_IS_CTLT;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.isDbReplicationTarget;
+import static org.apache.hadoop.hive.metastore.utils.MetaStoreUtils.getDefaultCatalog;
+import static org.apache.hadoop.hive.metastore.utils.StringUtils.normalizeIdentifier;
+
+@RequestHandler(requestBody = CreateTableRequest.class)
+public class CreateTableHandler
+    extends AbstractRequestHandler<CreateTableRequest, CreateTableHandler.CreateTableResult> {
+  private static final Logger LOG = LoggerFactory.getLogger(CreateTableHandler.class);
+  private SQLAllTableConstraints constraints;
+  private RawStore rs;
+  private Table tbl;
+  private Database db;
+  private Warehouse wh;
+  private ColumnStatistics colStats;
+  private EnvironmentContext envContext;
+
+  CreateTableHandler(IHMSHandler handler, CreateTableRequest request) {
+    super(handler, false, request);
+  }
+
+  @Override
+  protected CreateTableResult execute() throws TException, IOException {
+    Map<String, String> transactionalListenerResponses = Collections.emptyMap();
+    Path tblPath = null;
+    boolean success = false, madeDir = false;
+    boolean isReplicated;
+    try {
+      rs.openTransaction();
+      db = rs.getDatabase(tbl.getCatName(), tbl.getDbName());
+      isReplicated = isDbReplicationTarget(db);
+
+      ((HMSHandler)handler).firePreEvent(new PreCreateTableEvent(tbl, db, handler));
+
+      if (!TableType.VIRTUAL_VIEW.toString().equals(tbl.getTableType())) {
+        if (tbl.getSd().getLocation() == null
+            || tbl.getSd().getLocation().isEmpty()) {
+          tblPath = wh.getDefaultTablePath(db, tbl.getTableName() + getTableSuffix(tbl),
+              MetaStoreUtils.isExternalTable(tbl));
+        } else {
+          if (!MetaStoreUtils.isExternalTable(tbl) && !MetaStoreUtils.isNonNativeTable(tbl)) {
+            LOG.warn("Location: " + tbl.getSd().getLocation()
+                + " specified for non-external table:" + tbl.getTableName());
+          }
+          tblPath = wh.getDnsPath(new Path(tbl.getSd().getLocation()));
+          // ignore suffix if it's already there (direct-write CTAS)
+          if (!tblPath.getName().matches("(.*)" + SOFT_DELETE_TABLE_PATTERN)) {
+            tblPath = new Path(tblPath + getTableSuffix(tbl));
+          }
+        }
+        tbl.getSd().setLocation(tblPath.toString());
+      }
+
+      if (tblPath != null) {
+        if (!wh.isDir(tblPath)) {
+          if (!wh.mkdirs(tblPath)) {
+            throw new MetaException(tblPath
+                + " is not a directory or unable to create one");
+          }
+          madeDir = true;
+        }
+      }
+
+      MetaStoreServerUtils.updateTableStatsForCreateTable(wh, db, tbl,
+          request.getEnvContext(), handler.getConf(), tblPath, madeDir);
+
+      // set create time
+      long time = System.currentTimeMillis() / 1000;
+      tbl.setCreateTime((int) time);
+      if (tbl.getParameters() == null ||
+          tbl.getParameters().get(hive_metastoreConstants.DDL_TIME) == null) {
+        tbl.putToParameters(hive_metastoreConstants.DDL_TIME, Long.toString(time));
+      }
+      if (CollectionUtils.isEmpty(constraints.getPrimaryKeys())
+          && CollectionUtils.isEmpty(constraints.getForeignKeys())
+          && CollectionUtils.isEmpty(constraints.getUniqueConstraints())
+          && CollectionUtils.isEmpty(constraints.getNotNullConstraints())
+          && CollectionUtils.isEmpty(constraints.getDefaultConstraints())
+          && CollectionUtils.isEmpty(constraints.getCheckConstraints())) {
+        rs.createTable(tbl);
+      } else {
+        // Set constraint name if null before sending to listener
+        constraints = rs.createTableWithConstraints(tbl, constraints);
+      }
+
+      List<TransactionalMetaStoreEventListener> transactionalListeners = handler.getTransactionalListeners();
+      if (!transactionalListeners.isEmpty()) {
+        transactionalListenerResponses = MetaStoreListenerNotifier.notifyEvent(transactionalListeners,
+            EventMessage.EventType.CREATE_TABLE, new CreateTableEvent(tbl, true, handler, isReplicated), envContext);
+        if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_PRIMARYKEY,
+              new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_FOREIGNKEY,
+              new AddForeignKeyEvent(constraints.getForeignKeys(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+              new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+              new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+              new AddCheckConstraintEvent(constraints.getCheckConstraints(), true, handler), envContext);
+        }
+        if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+          MetaStoreListenerNotifier.notifyEvent(transactionalListeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+              new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), true, handler), envContext);
+        }
+      }
+      success = rs.commitTransaction();
+    } finally {
+      if (!success) {
+        rs.rollbackTransaction();
+        if (madeDir) {
+          wh.deleteDir(tblPath, false, ReplChangeManager.shouldEnableCm(db, tbl));
+        }
+      }
+    }
+    return new CreateTableResult(success, transactionalListenerResponses);
+  }
+
+  private String getTableSuffix(Table tbl) {
+    return tbl.isSetTxnId() && tbl.getParameters() != null
+        && Boolean.parseBoolean(tbl.getParameters().get(SOFT_DELETE_TABLE)) ?
+        SOFT_DELETE_PATH_SUFFIX + String.format(DELTA_DIGITS, tbl.getTxnId()) : "";
+  }
+
+  @Override
+  protected void afterExecute(CreateTableResult result) throws TException, IOException {
+    boolean success = result != null && result.success;
+    List<MetaStoreEventListener> listeners = handler.getListeners();
+    if (!listeners.isEmpty()) {
+      boolean isReplicated = isDbReplicationTarget(db);
+      MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.CREATE_TABLE,
+          new CreateTableEvent(tbl, success, handler, isReplicated), envContext,
+          result != null ? result.transactionalListenerResponses : Collections.emptyMap(), rs);
+      if (CollectionUtils.isNotEmpty(constraints.getPrimaryKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_PRIMARYKEY,
+            new AddPrimaryKeyEvent(constraints.getPrimaryKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getForeignKeys())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_FOREIGNKEY,
+            new AddForeignKeyEvent(constraints.getForeignKeys(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getUniqueConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_UNIQUECONSTRAINT,
+            new AddUniqueConstraintEvent(constraints.getUniqueConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getNotNullConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_NOTNULLCONSTRAINT,
+            new AddNotNullConstraintEvent(constraints.getNotNullConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getDefaultConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_DEFAULTCONSTRAINT,
+            new AddDefaultConstraintEvent(constraints.getDefaultConstraints(), success, handler), envContext);
+      }
+      if (CollectionUtils.isNotEmpty(constraints.getCheckConstraints())) {
+        MetaStoreListenerNotifier.notifyEvent(listeners, EventMessage.EventType.ADD_CHECKCONSTRAINT,
+            new AddCheckConstraintEvent(constraints.getCheckConstraints(), success, handler), envContext);
+      }
+    }
+
+    if (success && colStats != null) {
+      // If the table has column statistics, update it into the metastore. We need a valid
+      // writeId list to update column statistics for a transactional table. But during bootstrap
+      // replication, where we use this feature, we do not have a valid writeId list which was
+      // used to update the stats. But we know for sure that the writeId associated with the
+      // stats was valid then (otherwise stats update would have failed on the source). So, craft
+      // a valid transaction list with only that writeId and use it to update the stats.
+      long writeId = tbl.getWriteId();
+      String validWriteIds = null;
+      if (writeId > 0) {
+        ValidWriteIdList validWriteIdList =
+            new ValidReaderWriteIdList(TableName.getDbTable(tbl.getDbName(),
+                tbl.getTableName()),
+                new long[0], new BitSet(), writeId);
+        validWriteIds = validWriteIdList.toString();
+      }
+      updateTableColumnStatsInternal(colStats, validWriteIds, tbl.getWriteId());
+    }
+  }
+
+  private boolean updateTableColumnStatsInternal(ColumnStatistics colStats,

Review Comment:
   Thanks for the comments.
   The reason is it's not easy to make it as a static method, I'm agree with the reuse, filed HIVE-29407 with the optimization



-- 
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: gitbox-unsubscribe@hive.apache.org

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


---------------------------------------------------------------------
To unsubscribe, e-mail: gitbox-unsubscribe@hive.apache.org
For additional commands, e-mail: gitbox-help@hive.apache.org