OjashKush commented on code in PR #20012:
URL: https://github.com/apache/hudi/pull/20012#discussion_r4323350453


##########
hudi-trino/src/test/java/io/trino/plugin/hudi/TestHudiMetadata.java:
##########
@@ -0,0 +1,412 @@
+/*
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package io.trino.plugin.hudi;
+
+import io.trino.filesystem.FileIterator;
+import io.trino.filesystem.Location;
+import io.trino.filesystem.TrinoFileSystem;
+import io.trino.filesystem.TrinoFileSystemFactory;
+import io.trino.filesystem.local.LocalFileSystemFactory;
+import io.trino.metastore.Database;
+import io.trino.metastore.HiveMetastore;
+import io.trino.metastore.Table;
+import io.trino.metastore.TableAlreadyExistsException;
+import io.trino.plugin.hudi.util.HudiSchemaConverter;
+import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ColumnMetadata;
+import io.trino.spi.connector.ConnectorTableMetadata;
+import io.trino.spi.connector.SaveMode;
+import io.trino.spi.connector.SchemaTableName;
+import io.trino.spi.predicate.TupleDomain;
+import io.trino.spi.security.PrincipalType;
+import io.trino.spi.type.TypeManager;
+import org.apache.hudi.common.model.HoodieTableType;
+import org.apache.hudi.common.schema.HoodieSchema;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+import java.io.IOException;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Proxy;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.OptionalLong;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.function.UnaryOperator;
+
+import static com.google.common.base.Throwables.getCausalChain;
+import static 
com.google.common.util.concurrent.MoreExecutors.newDirectExecutorService;
+import static io.trino.plugin.hive.HiveMetadata.TRINO_QUERY_ID_NAME;
+import static io.trino.plugin.hive.TableType.EXTERNAL_TABLE;
+import static io.trino.plugin.hudi.HudiTableProperties.TABLE_TYPE_PROPERTY;
+import static io.trino.spi.type.BigintType.BIGINT;
+import static io.trino.testing.TestingConnectorSession.SESSION;
+import static org.apache.hudi.common.model.HoodieTableType.MERGE_ON_READ;
+import static org.apache.hudi.common.util.ConfigUtils.IS_QUERY_AS_RO_TABLE;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatCode;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+final class TestHudiMetadata
+{
+    @TempDir
+    private Path temporaryDirectory;
+
+    @Test
+    void testCreateTableRaceDoesNotDeleteWinningTableMetadata()
+    {
+        CreateRace race = 
createRace(TestHudiMetadata::asTableCreatedByAnotherQuery, false);
+
+        assertThatThrownBy(() -> race.metadata().createTable(SESSION, 
race.tableMetadata(), SaveMode.FAIL))
+                .isInstanceOf(TableAlreadyExistsException.class);
+
+        assertThat(race.winningTable().get()).isNotNull();
+        assertThat(metadataExists(race, race.winningTable().get()))
+                .isTrue();
+    }
+
+    @Test
+    void 
testCreateTableRetryRecognizesCommittedTableAfterLocationNormalization()
+    {
+        CreateRace race = createRace(table -> Table.builder(table)
+                .withStorage(storage -> storage.setLocation(
+                        table.getStorage().getLocation().replace("local:///", 
"local:/")))
+                .build(), false);
+
+        assertThatCode(() -> race.metadata().createTable(SESSION, 
race.tableMetadata(), SaveMode.FAIL))
+                .doesNotThrowAnyException();
+
+        assertThat(race.attemptedTable().get()).isNotNull();
+        assertThat(race.attemptedTable().get().getParameters())
+                .containsEntry(TRINO_QUERY_ID_NAME, SESSION.getQueryId())
+                .containsEntry(HudiMetadata.TRINO_MANAGED_TABLE_PARAMETER, 
"true");
+        assertThat(metadataExists(race, race.attemptedTable().get()))
+                .isTrue();
+    }
+
+    @Test
+    void testCreateTableRacePreservesMetadataWhenWinnerUsesDifferentLocation()
+    {
+        CreateRace race = createRace(table -> Table.builder(table)
+                .setParameter(TRINO_QUERY_ID_NAME, "another_query")
+                .withStorage(storage -> 
storage.setLocation("local:///other_table"))
+                .build(), false);
+
+        assertThatThrownBy(() -> race.metadata().createTable(SESSION, 
race.tableMetadata(), SaveMode.FAIL))
+                .isInstanceOf(TableAlreadyExistsException.class);
+
+        assertThat(race.attemptedTable().get()).isNotNull();
+        assertThat(race.winningTable().get()).isNotNull();
+        assertThat(race.winningTable().get().getStorage().getLocation())
+                
.isNotEqualTo(race.attemptedTable().get().getStorage().getLocation());
+        assertThat(metadataExists(race, race.attemptedTable().get()))
+                .isTrue();
+    }
+
+    @Test
+    void testCreateTableRacePreservesMetadataWhenWinnerLookupFails()
+    {
+        CreateRace race = 
createRace(TestHudiMetadata::asTableCreatedByAnotherQuery, true);
+
+        assertThatThrownBy(() -> race.metadata().createTable(SESSION, 
race.tableMetadata(), SaveMode.FAIL))
+                .isInstanceOf(TableAlreadyExistsException.class)
+                .satisfies(failure -> 
assertThat(failure.getSuppressed()).hasSize(1));
+
+        assertThat(race.attemptedTable().get()).isNotNull();
+        assertThat(metadataExists(race, race.attemptedTable().get()))
+                .isTrue();
+    }
+
+    @Test
+    void testCreateTableFailureCleansMetadataWhenNoTableWasRegistered()
+    {
+        CreateRace race = createRace(UnaryOperator.identity(), false, false);
+
+        assertThatThrownBy(() -> race.metadata().createTable(SESSION, 
race.tableMetadata(), SaveMode.FAIL))
+                .isInstanceOf(TableAlreadyExistsException.class);
+
+        assertThat(race.attemptedTable().get()).isNotNull();
+        assertThat(race.winningTable().get()).isNull();
+        assertThat(metadataExists(race, race.attemptedTable().get()))
+                .isFalse();
+    }
+
+    @Test
+    void testCreateTableInitializationConflictPreservesExistingMetadata()
+    {
+        SchemaTableName tableName = new SchemaTableName("test_schema", 
"concurrent_create");
+        ConnectorTableMetadata tableMetadata = createTableMetadata(tableName);
+        String basePath = "local:///test_schema/concurrent_create";
+        LocalFileSystemFactory localFileSystemFactory = new 
LocalFileSystemFactory(temporaryDirectory);
+        TrinoFileSystem localFileSystem = 
localFileSystemFactory.create(SESSION);
+        HoodieSchema tableSchema = 
HudiSchemaConverter.toTableSchema(tableMetadata.getColumns(), 
tableName.getTableName());
+        AtomicBoolean winnerInitialized = new AtomicBoolean();
+        TrinoFileSystem racingFileSystem = (TrinoFileSystem) 
Proxy.newProxyInstance(
+                TrinoFileSystem.class.getClassLoader(),
+                new Class<?>[] {TrinoFileSystem.class},
+                (proxy, method, arguments) -> {
+                    if (method.getName().equals("listFiles") && 
winnerInitialized.compareAndSet(false, true)) {
+                        HudiTableInitializer.initializeTable(localFileSystem, 
basePath, tableMetadata, tableSchema);
+                        return FileIterator.empty();
+                    }
+                    try {
+                        return method.invoke(localFileSystem, arguments);
+                    }
+                    catch (InvocationTargetException e) {
+                        throw e.getCause();
+                    }
+                });
+        TrinoFileSystemFactory racingFileSystemFactory = identity -> 
racingFileSystem;
+        HiveMetastore metastore = (HiveMetastore) Proxy.newProxyInstance(
+                HiveMetastore.class.getClassLoader(),
+                new Class<?>[] {HiveMetastore.class},
+                (proxy, method, arguments) -> switch (method.getName()) {
+                    case "getDatabase" -> Optional.of(Database.builder()
+                            .setDatabaseName(tableName.getSchemaName())
+                            .setLocation(Optional.of("local:///test_schema"))
+                            .setOwnerName(Optional.of("public"))
+                            .setOwnerType(Optional.of(PrincipalType.ROLE))
+                            .build());
+                    case "getTable" -> Optional.empty();
+                    default -> throw new AssertionError("Unexpected metastore 
call: " + method);
+                });
+        HudiMetadata metadata = new HudiMetadata(
+                metastore,
+                racingFileSystemFactory,
+                unusedTypeManager(),
+                newDirectExecutorService());
+
+        assertThatThrownBy(() -> metadata.createTable(SESSION, tableMetadata, 
SaveMode.FAIL))
+                .isInstanceOf(TrinoException.class)
+                .satisfies(failure -> assertThat(getCausalChain(failure))
+                        
.anyMatch(FileAlreadyExistsException.class::isInstance));
+
+        assertThat(winnerInitialized).isTrue();
+        assertThat(HudiUtil.hudiMetadataExists(localFileSystem, 
Location.of(basePath)))
+                .isTrue();
+    }
+
+    @Test
+    void testDropTreatsExternalTableTypeAsSufficientToPreserveStorage()
+    {
+        SchemaTableName tableName = new SchemaTableName("test_schema", 
"external_by_type");
+        ConnectorTableMetadata tableMetadata = createTableMetadata(tableName);
+        String basePath = "local:///test_schema/external_by_type";
+        LocalFileSystemFactory fileSystemFactory = new 
LocalFileSystemFactory(temporaryDirectory);
+        TrinoFileSystem fileSystem = fileSystemFactory.create(SESSION);
+        HoodieSchema tableSchema = HudiSchemaConverter.toTableSchema(
+                tableMetadata.getColumns(), tableName.getTableName());
+        HudiTableInitializer.initializeTable(fileSystem, basePath, 
tableMetadata, tableSchema);
+
+        Table table = Table.builder(HudiMetastoreTables.buildTable(
+                        tableName,
+                        basePath,
+                        HoodieTableType.COPY_ON_WRITE,
+                        tableSchema,
+                        List.of(),
+                        false,
+                        Optional.empty(),
+                        Optional.empty()))
+                // Some metastores use only the type signal for external 
tables.
+                .setTableType(EXTERNAL_TABLE.name())

Review Comment:
   I added the ownership marker to the external-table fixture and a separate 
unmarked MANAGED_TABLE case. The new test checks that DROP passes 
deleteData=false and preserves both the data file and .hoodie. Could you take 
another look?



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to