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

yiguolei pushed a commit to branch branch-4.1
in repository https://gitbox.apache.org/repos/asf/doris.git


The following commit(s) were added to refs/heads/branch-4.1 by this push:
     new e805958fdc3 [fix](iceberg) [branch-4.1] Allow REST table drops without 
purging files (#71010)
e805958fdc3 is described below

commit e805958fdc3d4ba7de7c0b9d2145eca4f69b1b11
Author: Gabriel <[email protected]>
AuthorDate: Tue Dec 1 11:23:24 2026 +0800

    [fix](iceberg) [branch-4.1] Allow REST table drops without purging files 
(#71010)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: apache/doris#70967
    PR Type: Bugfix
    
    Adapt apache/doris#70967 at `08e925bb3af62d6bea8563ee5cbc251f16e0b078`
    (including both commits) to `branch-4.1`.
    
    Iceberg REST services can reject purge requests while allowing tables to
    be unregistered. Add `iceberg.rest.drop-with-purge-enabled`, defaulting
    to `true`. Setting it to `false` unregisters tables while retaining
    their data and metadata files, including table drops performed by `DROP
    DATABASE FORCE`.
    
    ### Details
    
    - Adapt the connector-based implementation to the release branch's
    `IcebergRestProperties`, `IcebergExternalCatalog` and
    `IcebergMetadataOps` APIs.
    - Validate the boolean on CREATE/ALTER statements without adding
    validation to replay property binding.
    - Apply the REST-only choice in the shared table-drop path used by
    direct DROP and forced database cascades. Preserve view drops, error
    propagation and non-REST behavior.
    - Carry over both regression commits, including physical object checks
    and cleanup of previous-run retained objects. Adapt unit coverage to the
    legacy metadata interfaces.
    
    ### Testing
    
    - Repository `run-fe-ut.sh` compiles the target FE and passes 114 tests
    across the DROP, REST property and legacy metadata suites; 3
    pre-existing disabled integration tests are skipped. Zero failures or
    errors.
    - Baseline tests reproduced the always-purge REST request, HTTP 403 and
    missing boolean validation before the fix. The adapted DROP suite passes
    all eight tests afterward.
    - FE Checkstyle, Groovy syntax, diff whitespace checks (allowing
    generated result EOF separators), full diff self-review and
    sensitive-information checks pass.
    - Both regression file blobs match the source PR's final revision
    exactly, including its repeated-run object cleanup.
    - SQL integration regression and live Polaris were not rerun on this
    target branch; that coverage remains for CI.
    
    ### Release note
    
    Allow Iceberg REST catalogs to unregister tables without deleting their
    files by setting `iceberg.rest.drop-with-purge-enabled=false`. The
    option also applies to `DROP DATABASE FORCE` and defaults to `true` for
    compatibility.
---
 .../datasource/iceberg/IcebergExternalCatalog.java |   8 +
 .../datasource/iceberg/IcebergMetadataOps.java     |  10 +-
 .../property/metastore/IcebergRestProperties.java  |   8 +
 .../iceberg/IcebergRestDropPurgeTest.java          | 236 +++++++++++++++++++++
 .../test_iceberg_rest_drop_purge_option.out        |  21 ++
 .../test_iceberg_rest_drop_purge_option.groovy     | 195 +++++++++++++++++
 6 files changed, 477 insertions(+), 1 deletion(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
index 2918085e6fa..0e9a22d5418 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalCatalog.java
@@ -36,6 +36,7 @@ import org.apache.doris.datasource.SessionContext;
 import org.apache.doris.datasource.metacache.CacheSpec;
 import org.apache.doris.datasource.operations.ExternalMetadataOperations;
 import 
org.apache.doris.datasource.property.metastore.AbstractIcebergProperties;
+import org.apache.doris.datasource.property.metastore.IcebergRestProperties;
 import org.apache.doris.datasource.property.metastore.MetastoreProperties;
 import org.apache.doris.datasource.property.storage.StorageProperties;
 import org.apache.doris.foundation.security.JdbcDriverUrlSecurity;
@@ -128,6 +129,13 @@ public abstract class IcebergExternalCatalog extends 
ExternalCatalog {
     @Override
     protected void checkProperties(CatalogProperty property) throws 
DdlException {
         super.checkProperties(property);
+        if 
(ICEBERG_REST.equalsIgnoreCase(property.getOrDefault(ICEBERG_CATALOG_TYPE, 
""))) {
+            // Validate statements only; replay binding must keep accepting 
persisted properties.
+            String purge = 
property.getOrDefault(IcebergRestProperties.DROP_WITH_PURGE_ENABLED, null);
+            if (purge != null && !"true".equalsIgnoreCase(purge) && 
!"false".equalsIgnoreCase(purge)) {
+                throw new 
DdlException(IcebergRestProperties.DROP_WITH_PURGE_ENABLED + " must be true or 
false");
+            }
+        }
         
CacheSpec.checkBooleanProperty(property.getOrDefault(ICEBERG_TABLE_CACHE_ENABLE,
 null),
                 ICEBERG_TABLE_CACHE_ENABLE);
         
CacheSpec.checkLongProperty(property.getOrDefault(ICEBERG_TABLE_CACHE_TTL_SECOND,
 null),
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
index 3af3e027054..6b0c86c1b49 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergMetadataOps.java
@@ -487,7 +487,15 @@ public class IcebergMetadataOps implements 
ExternalMetadataOps {
                 ErrorReport.reportDdlException(ErrorCode.ERR_UNKNOWN_TABLE, 
remoteTblName, remoteDbName);
             }
         }
-        catalog.dropTable(getTableIdentifier(remoteDbName, remoteTblName), 
true);
+        catalog.dropTable(getTableIdentifier(remoteDbName, remoteTblName), 
shouldPurgeOnDrop());
+    }
+
+    private boolean shouldPurgeOnDrop() {
+        // REST can unregister without deleting files; HadoopCatalog may 
delete its directory even with purge=false.
+        Map<String, String> properties = catalogProperties;
+        return !IcebergExternalCatalog.ICEBERG_REST.equalsIgnoreCase(
+                properties.get(IcebergExternalCatalog.ICEBERG_CATALOG_TYPE))
+                || 
Boolean.parseBoolean(properties.getOrDefault(IcebergRestProperties.DROP_WITH_PURGE_ENABLED,
 "true"));
     }
 
     public void renameTableImpl(String dbName, String tblName, String 
newTblName) throws DdlException {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
index 2c065d0f33b..1ee9fadeb62 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/property/metastore/IcebergRestProperties.java
@@ -43,6 +43,8 @@ import java.util.Map;
 
 public class IcebergRestProperties extends AbstractIcebergProperties {
 
+    public static final String DROP_WITH_PURGE_ENABLED = 
"iceberg.rest.drop-with-purge-enabled";
+
     // REST catalog property constants
     private static final String PREFIX_PROPERTY = "prefix";
     private static final String VENDED_CREDENTIALS_HEADER = 
"header.X-Iceberg-Access-Delegation";
@@ -54,6 +56,12 @@ public class IcebergRestProperties extends 
AbstractIcebergProperties {
     private S3Properties s3Properties;
     private OSSProperties ossProperties;
 
+    @Getter
+    @ConnectorProperty(names = {DROP_WITH_PURGE_ENABLED},
+            required = false,
+            description = "Delete table data and metadata files when dropping 
an Iceberg REST table. Default: true.")
+    private boolean icebergRestDropWithPurgeEnabled = true;
+
     @Getter
     @ConnectorProperty(names = {"iceberg.rest.uri", "uri"},
             description = "The uri of the iceberg rest catalog service.")
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
new file mode 100644
index 00000000000..a13adc93657
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergRestDropPurgeTest.java
@@ -0,0 +1,236 @@
+// 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.doris.datasource.iceberg;
+
+import org.apache.doris.common.DdlException;
+import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
+import org.apache.doris.datasource.CatalogProperty;
+import org.apache.doris.datasource.ExternalDatabase;
+import org.apache.doris.datasource.ExternalTable;
+import org.apache.doris.datasource.property.metastore.IcebergRestProperties;
+import org.apache.doris.datasource.property.metastore.MetastoreProperties;
+
+import com.sun.net.httpserver.HttpServer;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.catalog.Catalog;
+import org.apache.iceberg.catalog.Namespace;
+import org.apache.iceberg.catalog.SupportsNamespaces;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.catalog.ViewCatalog;
+import org.apache.iceberg.rest.RESTCatalog;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.InOrder;
+import org.mockito.Mockito;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+public class IcebergRestDropPurgeTest {
+    private static final String PURGE_PROPERTY = 
"iceberg.rest.drop-with-purge-enabled";
+    private static final Namespace DB = Namespace.of("db");
+    private static final TableIdentifier FIRST = TableIdentifier.of(DB, "t1");
+    private static final TableIdentifier SECOND = TableIdentifier.of(DB, "t2");
+
+    @Test
+    public void restDropCanUnregisterWithoutPurging() throws Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        fixture.ops.dropTableImpl(fixture.table, false);
+        Mockito.verify(fixture.catalog).dropTable(FIRST, false);
+    }
+
+    @Test
+    public void restDropStillPurgesByDefaultAndWhenExplicitlyEnabled() throws 
Exception {
+        for (String enabled : Arrays.asList(null, "true", "TRUE")) {
+            Fixture fixture = new Fixture("rest", enabled);
+            fixture.ops.dropTableImpl(fixture.table, false);
+            fixture.ops.dropDbImpl("db", false, true);
+            Mockito.verify(fixture.catalog, Mockito.times(2)).dropTable(FIRST, 
true);
+            Mockito.verify(fixture.catalog).dropTable(SECOND, true);
+        }
+    }
+
+    @Test
+    public void forceDropUnregistersEveryTableAndStillDropsViews() throws 
Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        ViewCatalog views = (ViewCatalog) fixture.catalog;
+        TableIdentifier view = TableIdentifier.of(DB, "v");
+        
Mockito.when(views.listViews(DB)).thenReturn(Collections.singletonList(view));
+        fixture.ops.dropDbImpl("db", false, true);
+        InOrder order = Mockito.inOrder(fixture.catalog);
+        order.verify(fixture.catalog).dropTable(FIRST, false);
+        order.verify(fixture.catalog).dropTable(SECOND, false);
+        order.verify(views).dropView(view);
+        order.verify((SupportsNamespaces) fixture.catalog).dropNamespace(DB);
+    }
+
+    @Test
+    public void restOptionDoesNotChangeOtherCatalogDropSemantics() throws 
Exception {
+        for (String flavor : Arrays.asList("hms", "hadoop", "jdbc", "glue", 
"dlf", "s3tables")) {
+            Fixture fixture = new Fixture(flavor, "false");
+            fixture.ops.dropTableImpl(fixture.table, false);
+            fixture.ops.dropDbImpl("db", false, true);
+            Mockito.verify(fixture.catalog, Mockito.times(2)).dropTable(FIRST, 
true);
+            Mockito.verify(fixture.catalog).dropTable(SECOND, true);
+        }
+    }
+
+    @Test
+    public void rejectsInvalidBooleanDuringCreateAndAlterValidation() {
+        for (String invalid : Arrays.asList("", "yes", "0", " false ")) {
+            Map<String, String> raw = properties("rest", invalid);
+            IcebergRestExternalCatalog catalog = new 
IcebergRestExternalCatalog(1L, "rest", null, raw, "");
+            DdlException error = Assertions.assertThrows(DdlException.class, 
catalog::checkProperties);
+            Assertions.assertEquals(PURGE_PROPERTY + " must be true or false", 
error.getDetailMessage());
+            // The normal ALTER fallback temporarily publishes candidate 
properties before validation.
+            Map<String, String> updated = properties("rest", invalid);
+            IcebergRestExternalCatalog altered = new 
IcebergRestExternalCatalog(2L, "altered", null,
+                    properties("rest", "true"), "");
+            DdlException alterError = 
Assertions.assertThrows(DdlException.class, () -> {
+                if 
(!altered.validatePropertiesBeforeUpdate(altered.getProperties(), updated)) {
+                    altered.getCatalogProperty().modifyCatalogProps(updated);
+                    altered.checkProperties();
+                }
+            });
+            Assertions.assertEquals(PURGE_PROPERTY + " must be true or false", 
alterError.getDetailMessage());
+        }
+    }
+
+    @Test
+    public void validBooleansBindWithoutChangingSdkProperties() throws 
Exception {
+        for (String valid : Arrays.asList("true", "false", "TRUE", "FALSE")) {
+            IcebergRestProperties bound = (IcebergRestProperties) 
MetastoreProperties.create(properties("rest", valid));
+            Assertions.assertEquals(Boolean.parseBoolean(valid), 
bound.isIcebergRestDropWithPurgeEnabled());
+            
Assertions.assertFalse(bound.getIcebergRestCatalogProperties().containsKey(PURGE_PROPERTY));
+        }
+        // Replay binding must not introduce new statement-time validation.
+        Assertions.assertDoesNotThrow(() -> 
MetastoreProperties.create(properties("rest", "invalid")));
+    }
+
+    @Test
+    public void failedTableUnregisterStopsTheForceCascade() throws Exception {
+        Fixture fixture = new Fixture("rest", "false");
+        Mockito.when(fixture.catalog.dropTable(FIRST, false))
+                .thenThrow(new IllegalStateException("unregister rejected"));
+        DdlException error = Assertions.assertThrows(DdlException.class,
+                () -> fixture.ops.dropDbImpl("db", false, true));
+        Assertions.assertTrue(error.getMessage().contains("unregister 
rejected"), error.getMessage());
+        Mockito.verify(fixture.catalog, 
Mockito.never()).dropTable(Mockito.eq(SECOND), Mockito.anyBoolean());
+        Mockito.verify((SupportsNamespaces) fixture.catalog, 
Mockito.never()).dropNamespace(DB);
+    }
+
+    @Test
+    public void restServerThatRejectsPurgeAcceptsMetadataOnlyDrop() throws 
Exception {
+        List<String> queries = new CopyOnWriteArrayList<>();
+        HttpServer server = HttpServer.create(new 
InetSocketAddress("127.0.0.1", 0), 0);
+        server.createContext("/", exchange -> {
+            try {
+                exchange.getResponseHeaders().set("Content-Type", 
"application/json");
+                if ("GET".equals(exchange.getRequestMethod())) {
+                    byte[] config = 
"{\"defaults\":{},\"overrides\":{}}".getBytes(StandardCharsets.UTF_8);
+                    exchange.sendResponseHeaders(200, config.length);
+                    exchange.getResponseBody().write(config);
+                } else if ("DELETE".equals(exchange.getRequestMethod())) {
+                    String query = exchange.getRequestURI().getRawQuery();
+                    queries.add(query);
+                    if (query != null && 
query.contains("purgeRequested=true")) {
+                        byte[] error = ("{\"error\":{\"message\":\"purge 
disabled\","
+                                + 
"\"type\":\"ForbiddenException\",\"code\":403}}")
+                                .getBytes(StandardCharsets.UTF_8);
+                        exchange.sendResponseHeaders(403, error.length);
+                        exchange.getResponseBody().write(error);
+                    } else {
+                        exchange.sendResponseHeaders(204, -1);
+                    }
+                } else {
+                    exchange.sendResponseHeaders(405, -1);
+                }
+            } finally {
+                exchange.close();
+            }
+        });
+        server.start();
+        try (RESTCatalog catalog = Mockito.spy(new RESTCatalog())) {
+            catalog.initialize("test", 
Collections.singletonMap(CatalogProperties.URI,
+                    "http://127.0.0.1:"; + server.getAddress().getPort()));
+            
Mockito.doReturn(true).when(catalog).tableExists(Mockito.any(TableIdentifier.class));
+            
Mockito.doReturn(false).when(catalog).viewExists(Mockito.any(TableIdentifier.class));
+            Fixture defaultDrop = new Fixture("rest", null, catalog);
+            DdlException error = Assertions.assertThrows(DdlException.class,
+                    () -> defaultDrop.ops.dropTableImpl(defaultDrop.table, 
false));
+            Assertions.assertTrue(error.getMessage().contains("purge 
disabled"), error.getMessage());
+            Fixture metadataOnly = new Fixture("rest", "false", catalog);
+            metadataOnly.ops.dropTableImpl(metadataOnly.table, false);
+            Assertions.assertEquals(2, queries.size());
+            Assertions.assertEquals("purgeRequested=true", queries.get(0));
+            Assertions.assertNull(queries.get(1), "metadata-only REST drop 
must omit purgeRequested");
+        } finally {
+            server.stop(0);
+        }
+    }
+
+    private static Map<String, String> properties(String flavor, String 
enabled) {
+        Map<String, String> raw = new HashMap<>();
+        raw.put("type", "iceberg");
+        raw.put(IcebergExternalCatalog.ICEBERG_CATALOG_TYPE, flavor);
+        raw.put("iceberg.rest.uri", "http://127.0.0.1:8181";);
+        if (enabled != null) {
+            raw.put(PURGE_PROPERTY, enabled);
+        }
+        return raw;
+    }
+
+    private static class Fixture {
+        private final Catalog catalog;
+        private final IcebergMetadataOps ops;
+        private final ExternalTable table = Mockito.mock(ExternalTable.class);
+
+        Fixture(String flavor, String enabled) {
+            this(flavor, enabled, Mockito.mock(Catalog.class,
+                    
Mockito.withSettings().extraInterfaces(SupportsNamespaces.class, 
ViewCatalog.class)));
+            
Mockito.when(catalog.tableExists(Mockito.any(TableIdentifier.class))).thenReturn(true);
+            
Mockito.when(catalog.listTables(DB)).thenReturn(Arrays.asList(FIRST, SECOND));
+        }
+
+        Fixture(String flavor, String enabled, Catalog catalog) {
+            this.catalog = catalog;
+            Map<String, String> raw = properties(flavor, enabled);
+            IcebergExternalCatalog doris = 
Mockito.mock(IcebergExternalCatalog.class);
+            Mockito.when(doris.getProperties()).thenReturn(raw);
+            Mockito.when(doris.getCatalogProperty()).thenReturn(new 
CatalogProperty(null, raw));
+            Mockito.when(doris.getExecutionAuthenticator()).thenReturn(new 
ExecutionAuthenticator() {
+            });
+            ExternalDatabase db = Mockito.mock(ExternalDatabase.class);
+            Mockito.when(db.getRemoteName()).thenReturn("db");
+            Mockito.when(db.getFullName()).thenReturn("db");
+            Mockito.when(doris.getDbNullable("db")).thenReturn(db);
+            
Mockito.doReturn(db).when(doris).getDbForCatalogOperation(Mockito.any(), 
Mockito.eq("db"));
+            ops = new IcebergMetadataOps(doris, catalog);
+            Mockito.when(doris.getMetadataOps()).thenReturn(ops);
+            Mockito.when(table.getRemoteDbName()).thenReturn("db");
+            Mockito.when(table.getRemoteName()).thenReturn("t1");
+            Mockito.when(table.getName()).thenReturn("t1");
+        }
+    }
+}
diff --git 
a/regression-test/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
new file mode 100644
index 00000000000..ee579fecce2
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.out
@@ -0,0 +1,21 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !default_rows --
+1
+2
+
+-- !default_unregistered --
+
+-- !kept_rows --
+3
+4
+
+-- !kept_unregistered --
+
+-- !namespace_unregistered --
+
+-- !enabled_rows --
+5
+
+-- !purged_namespace_unregistered --
+
+-- !enabled_unregistered --
diff --git 
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
new file mode 100644
index 00000000000..8b98f8258d8
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_rest_drop_purge_option.groovy
@@ -0,0 +1,195 @@
+// 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.
+
+import com.amazonaws.auth.AWSStaticCredentialsProvider
+import com.amazonaws.auth.BasicAWSCredentials
+import com.amazonaws.client.builder.AwsClientBuilder.EndpointConfiguration
+import com.amazonaws.services.s3.AmazonS3ClientBuilder
+import com.amazonaws.services.s3.model.DeleteObjectsRequest
+import com.amazonaws.services.s3.model.ListObjectsV2Request
+
+suite("test_iceberg_rest_drop_purge_option", 
"p0,external,iceberg,external_docker,external_docker_iceberg,nonConcurrent") {
+    if 
(!"true".equalsIgnoreCase(context.config.otherConfigs.get("enableIcebergTest")))
 {
+        logger.info("disable iceberg test")
+        return
+    }
+    String host = context.config.otherConfigs.get("externalEnvIp")
+    String restPort = context.config.otherConfigs.get("iceberg_rest_uri_port")
+    String minioPort = context.config.otherConfigs.get("iceberg_minio_port")
+    String endpoint = "http://${host}:${minioPort}";
+
+    sql "drop catalog if exists iceberg_rest_drop_purge_option"
+    sql """create catalog iceberg_rest_drop_purge_option properties (
+        "type" = "iceberg",
+        "iceberg.catalog.type" = "rest",
+        "uri" = "http://${host}:${restPort}";,
+        "s3.endpoint" = "${endpoint}",
+        "s3.access_key" = "admin",
+        "s3.secret_key" = "password",
+        "s3.region" = "us-east-1",
+        "use_path_style" = "true"
+    )"""
+    sql "switch iceberg_rest_drop_purge_option"
+    sql "drop database if exists rest_drop_purge_db force"
+    sql "drop database if exists rest_drop_purge_cascade_db force"
+    sql "drop database if exists rest_drop_purge_enabled_cascade_db force"
+    sql "create database rest_drop_purge_db"
+    sql "use rest_drop_purge_db"
+
+    def client = AmazonS3ClientBuilder.standard()
+            .withEndpointConfiguration(new EndpointConfiguration(endpoint, 
"us-east-1"))
+            .withPathStyleAccessEnabled(true)
+            .withCredentials(new AWSStaticCredentialsProvider(new 
BasicAWSCredentials("admin", "password")))
+            .build()
+    try {
+        List<String> cleanupPrefixes = [
+                "wh/rest_drop_purge_db/",
+                "wh/rest_drop_purge_cascade_db/",
+                "wh/rest_drop_purge_enabled_cascade_db/"
+        ]
+        // Three stale markers and two-entry pages exercise multi-batch 
cleanup on every run.
+        cleanupPrefixes.each { String prefix ->
+            (0..<3).each { int index ->
+                client.putObject("warehouse", 
"${prefix}cleanup-stale-${index}".toString(), "stale")
+            }
+        }
+        String neighborKey = "wh/rest_drop_purge_db_neighbor/cleanup-sentinel"
+        client.putObject("warehouse", neighborKey, "keep")
+        // SQL cannot discover files after unregister-only drops. Reclaim only 
this suite's previous runs,
+        // leaving current-run retained files available for debugging until 
the next invocation.
+        cleanupPrefixes.each { String prefix ->
+            while (true) {
+                def objects = client.listObjectsV2(new ListObjectsV2Request()
+                        
.withBucketName("warehouse").withPrefix(prefix).withMaxKeys(2)).objectSummaries
+                if (objects.isEmpty()) {
+                    break
+                }
+                // Re-list the first page after deletion instead of reusing an 
opaque continuation token.
+                client.deleteObjects(new 
DeleteObjectsRequest("warehouse").withKeys(objects.collect {
+                    new DeleteObjectsRequest.KeyVersion(it.key)
+                }))
+            }
+        }
+        cleanupPrefixes.each { String prefix ->
+            assertTrue(client.listObjectsV2("warehouse", 
prefix).objectSummaries.isEmpty(),
+                    "Previous-run objects remain under ${prefix}")
+        }
+        assertTrue(client.doesObjectExist("warehouse", neighborKey))
+        client.deleteObject("warehouse", neighborKey)
+
+        def captureObjects = { String table ->
+            def data = sql "select file_path from `${table}\$files` where 
content = 0"
+            def metadata = sql "select file from 
`${table}\$metadata_log_entries`"
+            assertTrue(!data.isEmpty(), "The table must have data files")
+            assertTrue(!metadata.isEmpty(), "The table must have metadata 
files")
+            def manifests = sql "select path from `${table}\$manifests`"
+            def snapshots = sql "select manifest_list from 
`${table}\$snapshots`"
+            assertTrue(!manifests.isEmpty(), "The table must have manifest 
files")
+            assertTrue(!snapshots.isEmpty(), "The table must have manifest 
lists")
+            def objects = (data + metadata + manifests + snapshots).collect { 
it[0].toString() }.unique()
+            objects.each { String object ->
+                URI uri = new URI(object)
+                assertTrue(uri.host == "warehouse" && cleanupPrefixes.any { 
uri.path.startsWith("/${it}") },
+                        "Table object is outside this suite's cleanup 
prefixes: ${object}")
+            }
+            return objects
+        }
+        def checkObjects = { List<String> objects, boolean present ->
+            objects.each { String object ->
+                URI uri = new URI(object)
+                assertTrue(uri.scheme in ["s3", "s3a", "s3n"], "Unexpected 
object URI: ${object}")
+                assertTrue(client.doesObjectExist(uri.host, 
uri.path.substring(1)) == present,
+                        "Unexpected object presence: ${object}, expected 
${present}")
+            }
+        }
+
+        sql "create table purge_default (id int)"
+        sql "insert into purge_default values (1), (2)"
+        qt_default_rows "select id from purge_default order by id"
+        def defaultObjects = captureObjects("purge_default")
+        checkObjects(defaultObjects, true)
+        sql "drop table purge_default"
+        checkObjects(defaultObjects, false)
+        qt_default_unregistered "show tables like 'purge_default'"
+
+        sql """alter catalog iceberg_rest_drop_purge_option set properties (
+            "iceberg.rest.drop-with-purge-enabled" = "false")"""
+        sql "use iceberg_rest_drop_purge_option.rest_drop_purge_db"
+        sql "create table keep_table (id int)"
+        sql "insert into keep_table values (3), (4)"
+        qt_kept_rows "select id from keep_table order by id"
+        def keptObjects = captureObjects("keep_table")
+        checkObjects(keptObjects, true)
+        sql "drop table keep_table"
+        checkObjects(keptObjects, true)
+        qt_kept_unregistered "show tables like 'keep_table'"
+
+        sql "create database rest_drop_purge_cascade_db"
+        sql "use rest_drop_purge_cascade_db"
+        sql "create table keep_first (id int)"
+        sql "create table keep_second (id int)"
+        sql "insert into keep_first values (10)"
+        sql "insert into keep_second values (20)"
+        def firstObjects = captureObjects("keep_first")
+        def secondObjects = captureObjects("keep_second")
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        sql "use rest_drop_purge_db"
+        sql "drop database rest_drop_purge_cascade_db force"
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        qt_namespace_unregistered "show databases like 
'rest_drop_purge_cascade_db'"
+
+        sql """alter catalog iceberg_rest_drop_purge_option set properties (
+            "iceberg.rest.drop-with-purge-enabled" = "true")"""
+        test {
+            sql """alter catalog iceberg_rest_drop_purge_option set properties 
(
+                "iceberg.rest.drop-with-purge-enabled" = "invalid")"""
+            exception "iceberg.rest.drop-with-purge-enabled must be true or 
false"
+        }
+        sql "use iceberg_rest_drop_purge_option.rest_drop_purge_db"
+        sql "create table purge_enabled (id int)"
+        sql "insert into purge_enabled values (5)"
+        qt_enabled_rows "select id from purge_enabled order by id"
+        def enabledObjects = captureObjects("purge_enabled")
+        checkObjects(enabledObjects, true)
+        sql "drop table purge_enabled"
+        checkObjects(enabledObjects, false)
+        sql "create database rest_drop_purge_enabled_cascade_db"
+        sql "use rest_drop_purge_enabled_cascade_db"
+        sql "create table purge_first (id int)"
+        sql "create table purge_second (id int)"
+        sql "insert into purge_first values (30)"
+        sql "insert into purge_second values (40)"
+        def purgedFirstObjects = captureObjects("purge_first")
+        def purgedSecondObjects = captureObjects("purge_second")
+        checkObjects(purgedFirstObjects, true)
+        checkObjects(purgedSecondObjects, true)
+        sql "use rest_drop_purge_db"
+        sql "drop database rest_drop_purge_enabled_cascade_db force"
+        checkObjects(purgedFirstObjects, false)
+        checkObjects(purgedSecondObjects, false)
+        qt_purged_namespace_unregistered "show databases like 
'rest_drop_purge_enabled_cascade_db'"
+        // Changing the option affects later drops, not objects deliberately 
retained by earlier ones.
+        checkObjects(keptObjects, true)
+        checkObjects(firstObjects, true)
+        checkObjects(secondObjects, true)
+        qt_enabled_unregistered "show tables like 'purge_enabled'"
+    } finally {
+        client.shutdown()
+    }
+}


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to