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

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


The following commit(s) were added to refs/heads/master by this push:
     new 14e744bb7f8 [fix](iceberg) Allow REST table drops without purging 
files (#70967)
14e744bb7f8 is described below

commit 14e744bb7f88bcc6697ece8984b54ad008f11c48
Author: Gabriel <[email protected]>
AuthorDate: Tue Dec 1 10:00:26 2026 +0800

    [fix](iceberg) Allow REST table drops without purging files (#70967)
    
    ### Background
    
    Iceberg REST catalogs can either unregister a table or also delete its
    data and metadata files. Doris currently requests file deletion on every
    table drop, including table drops performed by `DROP DATABASE FORCE`. A
    REST service can forbid purge requests while allowing tables to be
    unregistered.
    
    ### What problem does this PR solve?
    
    Issue Number: None
    Related PR: #43441 (introduced always-purge table drops)
    PR Type: Bugfix
    
    Problem Summary:
    
    `DROP TABLE` fails against REST services that reject purge requests,
    with no way to request unregister-only behavior. Add the REST catalog
    property `iceberg.rest.drop-with-purge-enabled`, configurable through
    CREATE/ALTER CATALOG and defaulting to `true`. Setting it to `false`
    also covers the table cascade of `DROP DATABASE FORCE`; most of this
    diff tests both modes and checks physical file retention. Existing users
    retain the current behavior unless they disable purge.
    
    ```sql
    ALTER CATALOG rest_catalog SET PROPERTIES (
        "iceberg.rest.drop-with-purge-enabled" = "false"
    );
    DROP TABLE rest_catalog.db.events;
    ```
    
    ### Details
    
    - **Change map:** 34 changed production lines bind, validate and apply
    the option; 401 test lines cover REST requests, compatibility, errors
    and physical objects; 21 generated expectation lines record SQL results.
    - **Frequency:** Always when a REST service rejects
    `purgeRequested=true`; reproduced with a local REST server returning
    HTTP 403.
    - **Root cause:** `IcebergConnectorMetadata.dropTable` and the force
    path in `dropDatabase` unconditionally pass `true` to
    `catalogOps.dropTable`, so the Iceberg SDK always requests purge.
    - **Why existing tests missed it:** `IcebergConnectorMetadataDdlTest`
    asserts the existing purge behavior using recording catalog operations.
    The `iceberg_drop_rest_table` and `test_iceberg_drop_db` regressions
    check successful purging and privileges, without an unregister-only mode
    or a server rejecting purge. The new tests check the actual REST query
    and retained data, metadata, manifests and manifest lists.
    - **Fix:** Resolve the option at DROP time for REST catalogs, and pass
    the same value through direct and cascaded table drops. Invalid booleans
    are rejected during CREATE/ALTER validation, without adding validation
    to replay binding. The regression reclaims previous-run files only from
    its three namespace prefixes before creating new tables, with
    multi-batch and neighboring-prefix coverage; current-run files remain
    available for debugging.
    - **Other paths and branches:** Both table-drop routes are fixed here;
    view drops and non-REST semantics remain unchanged. In particular,
    HadoopCatalog may delete its directory even with `purge=false`. Local
    snapshots of branches 3.1, 4.0, 4.1 and 4.2 have the same hardcoded
    purge behavior in the legacy metadata implementation and need an adapted
    backport. The always-purge table behavior was introduced by #43441; this
    PR preserves that default.
    - **Configs and defaults:** `iceberg.rest.drop-with-purge-enabled=true`
    by default. ALTER CATALOG changes subsequent drops without an FE
    restart. With `false`, REST drops unregister tables and leave their
    files in storage.
    - **Behavior change:** Only REST catalogs explicitly setting the option
    to `false` change their drop behavior. SQL FORCE retains its existing
    cascade meaning.
    
    ### Testing
    
    - Before the fix, four of six initial `IcebergRestDropPurgeTest` cases
    failed, including the HTTP 403 reproduction. All seven final cases pass,
    including failure propagation and non-REST compatibility.
    - Focused local unit run: 70 tests passed across the REST property, DDL
    and new DROP suites.
    - Broader Iceberg connector package run: 2,063 tests, zero
    failures/errors, ten existing skips; the metastore tests also pass.
    - Local regression `test_iceberg_rest_drop_purge_option` passes with the
    current FE build and REST/MinIO fixture, checking default/explicit
    purge, unregister-only table/database drops, ALTER validation and exact
    object presence. The cleanup assertion fails before implementation;
    three consecutive final runs pass. Independent S3 snapshots show 15
    retained objects after each run and zero old keys surviving the next
    run.
    - A live Polaris deployment was not used.
    
    ### 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.
    
    ### Check List (For Author)
    
    - Behavior changed: Yes (see Details)
    - Does this need documentation: Yes (add the property to the Iceberg
    REST catalog configuration documentation after the option naming is
    reviewed)
    - Pre-submission status: Partially verified: live Polaris integration
    was not run
    
    ### AI Disclosure
    
    - Tool: Codex (GPT-6)
    - Generated: implementation, unit and regression tests, and this
    description
    - Human review: Not stated by the author; the agent completed a local
    self-review before committing.
    - Prompts: Asked to fix REST DROP behavior on master with sufficient
    unit and regression coverage, and to complete local review and resolve
    findings before submitting code. Then requested fixing the remaining
    review finding and reviewing the updated PR again.
---
 .../iceberg/IcebergConnectorMetadata.java          |  18 +-
 .../iceberg/IcebergRestDropPurgeTest.java          | 180 +++++++++++++++++++
 .../iceberg/RecordingIcebergCatalogOps.java        |   4 +
 .../rest/IcebergRestMetaStoreProperties.java       |  16 ++
 .../rest/IcebergRestMetaStorePropertiesTest.java   |  22 +++
 .../test_iceberg_rest_drop_purge_option.out        |  21 +++
 .../test_iceberg_rest_drop_purge_option.groovy     | 195 +++++++++++++++++++++
 7 files changed, 451 insertions(+), 5 deletions(-)

diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorMetadata.java
 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorMetadata.java
index a54e8b996e4..f0b3f895d86 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorMetadata.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/main/java/org/apache/doris/connector/iceberg/IcebergConnectorMetadata.java
@@ -19,6 +19,7 @@ package org.apache.doris.connector.iceberg;
 
 import org.apache.doris.connector.cache.ConnectorMetadataCache;
 import org.apache.doris.connector.cache.ConnectorTableKey;
+import 
org.apache.doris.connector.metastore.iceberg.rest.IcebergRestMetaStoreProperties;
 import org.apache.doris.connector.spi.ConnectorColumn;
 import org.apache.doris.connector.spi.ConnectorContext;
 import org.apache.doris.connector.spi.ConnectorDatabaseMetadata;
@@ -1079,7 +1080,7 @@ public class IcebergConnectorMetadata implements 
ConnectorMetadata {
 
     /**
      * Drops an iceberg namespace, mirroring legacy {@code 
IcebergMetadataOps.performDropDb}. With
-     * {@code force} the contained tables are dropped (purged) first so a 
non-empty namespace can be removed;
+     * {@code force} the contained tables are dropped first, respecting the 
REST catalog's purge option;
      * the namespace location is captured BEFORE the drop and its empty 
directory shell pruned afterwards
      * (HMS only). Existence / IF EXISTS is resolved upstream by {@code 
PluginDrivenExternalCatalog.dropDb}, so
      * {@code ifExists} is accepted for SPI parity but not re-checked here.
@@ -1097,8 +1098,9 @@ public class IcebergConnectorMetadata implements 
ConnectorMetadata {
                     location = isHmsCatalog()
                             ? catalogOps.loadNamespaceLocation(dbName) : 
Optional.empty();
                     if (force) {
+                        boolean purge = shouldPurgeOnDrop();
                         for (String table : catalogOps.listTableNames(dbName)) 
{
-                            catalogOps.dropTable(dbName, table, true);
+                            catalogOps.dropTable(dbName, table, purge);
                         }
                         // Cascade the views too, mirroring legacy 
IcebergMetadataOps.performDropDb: iceberg
                         // VIEWS live in their own namespace (listTableNames 
subtracts them), so without this the
@@ -1311,8 +1313,8 @@ public class IcebergConnectorMetadata implements 
ConnectorMetadata {
 
     /**
      * Drops an iceberg table, mirroring legacy {@code 
IcebergMetadataOps.performDropTable}: the table location
-     * is captured BEFORE the drop (HMS only), the table is dropped with 
{@code purge=true} (iceberg deletes the
-     * data + metadata files), then the empty directory shell is pruned. 
{@code PluginDrivenExternalCatalog}
+     * is captured BEFORE the drop (HMS only), then the table is dropped and 
the empty directory shell pruned.
+     * REST catalogs can opt out of purging the data and metadata files. 
{@code PluginDrivenExternalCatalog}
      * has already resolved the handle / IF EXISTS upstream.
      *
      * <p>This handles TABLES only: a DROP on an iceberg view is routed to 
{@link #dropView} by
@@ -1328,7 +1330,7 @@ public class IcebergConnectorMetadata implements 
ConnectorMetadata {
                 Optional<String> location = isHmsCatalog()
                         ? catalogOps.loadTableLocation(iceHandle.getDbName(), 
iceHandle.getTableName())
                         : Optional.empty();
-                catalogOps.dropTable(iceHandle.getDbName(), 
iceHandle.getTableName(), true);
+                catalogOps.dropTable(iceHandle.getDbName(), 
iceHandle.getTableName(), shouldPurgeOnDrop());
                 return location;
             });
         } catch (Exception e) {
@@ -1339,6 +1341,12 @@ public class IcebergConnectorMetadata implements 
ConnectorMetadata {
                 storage().cleanupEmptyManagedLocation(location, 
IcebergSchemaBuilder.tableLocationChildDirs()));
     }
 
+    private boolean shouldPurgeOnDrop() {
+        // REST can unregister without deleting files; HadoopCatalog may 
delete its directory even with purge=false.
+        return !IcebergCatalogProperties.TYPE_REST.equals(catalogType())
+                || 
IcebergRestMetaStoreProperties.of(properties).isDropWithPurgeEnabled();
+    }
+
     /**
      * Renames a table, mirroring legacy {@code 
IcebergMetadataOps.renameTableImpl}: a thin seam delegation
      * ({@code catalog.renameTable}) inside the auth context. {@code newName} 
is the rename target's name in
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergRestDropPurgeTest.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergRestDropPurgeTest.java
new file mode 100644
index 00000000000..51bb6a9c4c2
--- /dev/null
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/IcebergRestDropPurgeTest.java
@@ -0,0 +1,180 @@
+// 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.connector.iceberg;
+
+import 
org.apache.doris.connector.iceberg.IcebergCatalogOps.CatalogBackedIcebergCatalogOps;
+import org.apache.doris.connector.spi.DorisConnectorException;
+
+import com.sun.net.httpserver.HttpServer;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.rest.RESTCatalog;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.net.InetSocketAddress;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.CopyOnWriteArrayList;
+
+class IcebergRestDropPurgeTest {
+    private static final String PURGE_PROPERTY = 
"iceberg.rest.drop-with-purge-enabled";
+
+    @Test
+    void restDropCanUnregisterWithoutPurging() {
+        RecordingIcebergCatalogOps ops = new RecordingIcebergCatalogOps();
+        RecordingConnectorContext context = new RecordingConnectorContext();
+        metadata(ops, context, "rest", "false").dropTable(null, new 
IcebergTableHandle("db", "t"));
+        Assertions.assertEquals(List.of("dropTable:db.t:purge=false"), 
ops.log);
+        Assertions.assertFalse(ops.lastDropPurge);
+        Assertions.assertTrue(context.cleanedLocations.isEmpty());
+        Assertions.assertEquals(1, context.authCount);
+    }
+
+    @Test
+    void restDropStillPurgesByDefaultAndWhenExplicitlyEnabled() {
+        for (String enabled : Arrays.asList(null, "true")) {
+            RecordingIcebergCatalogOps ops = new RecordingIcebergCatalogOps();
+            metadata(ops, new RecordingConnectorContext(), "rest", enabled)
+                    .dropTable(null, new IcebergTableHandle("db", "t"));
+            Assertions.assertEquals(List.of("dropTable:db.t:purge=true"), 
ops.log);
+        }
+    }
+
+    @Test
+    void forceDropUnregistersEveryTableAndStillDropsViews() {
+        RecordingIcebergCatalogOps ops = new RecordingIcebergCatalogOps();
+        ops.tables = List.of("t1", "t2");
+        ops.views = List.of("v");
+        RecordingConnectorContext context = new RecordingConnectorContext();
+        metadata(ops, context, "rest", "false").dropDatabase(null, "db", 
false, true);
+        Assertions.assertEquals(List.of("listTableNames:db", 
"dropTable:db.t1:purge=false",
+                "dropTable:db.t2:purge=false", "listViewNames:db", 
"dropView:db.v", "dropDatabase:db"), ops.log);
+        Assertions.assertTrue(context.cleanedLocations.isEmpty());
+        Assertions.assertEquals(1, context.authCount);
+    }
+
+    @Test
+    void restOptionDoesNotChangeOtherCatalogDropSemantics() {
+        for (String flavor : List.of("hms", "hadoop", "jdbc", "glue", "dlf", 
"s3tables")) {
+            RecordingIcebergCatalogOps ops = new RecordingIcebergCatalogOps();
+            metadata(ops, new RecordingConnectorContext(), flavor, "false")
+                    .dropTable(null, new IcebergTableHandle("db", "t"));
+            Assertions.assertTrue(ops.lastDropPurge, flavor);
+            ops.tables = List.of("t1", "t2");
+            ops.log.clear();
+            metadata(ops, new RecordingConnectorContext(), flavor, "false")
+                    .dropDatabase(null, "db", false, true);
+            
Assertions.assertTrue(ops.log.contains("dropTable:db.t1:purge=true"), flavor);
+            
Assertions.assertTrue(ops.log.contains("dropTable:db.t2:purge=true"), flavor);
+        }
+    }
+
+    @Test
+    void rejectsInvalidBooleanDuringCatalogStatementValidation() {
+        for (String invalid : List.of("", "yes", "0", " false ")) {
+            Map<String, String> raw = properties("rest", invalid);
+            IllegalArgumentException error = 
Assertions.assertThrows(IllegalArgumentException.class,
+                    () -> 
IcebergCatalogProperties.of(raw).checkCreateTimeOnlyRules());
+            Assertions.assertTrue(error.getMessage().contains(PURGE_PROPERTY), 
error.getMessage());
+            // Binding during replay does not run newly introduced 
statement-time validation.
+            Assertions.assertDoesNotThrow(() -> 
IcebergCatalogProperties.of(raw));
+        }
+        for (String valid : List.of("true", "false", "TRUE", "FALSE")) {
+            Assertions.assertDoesNotThrow(() -> 
IcebergCatalogProperties.of(properties("rest", valid))
+                    .checkCreateTimeOnlyRules());
+        }
+    }
+
+    @Test
+    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 = new RESTCatalog()) {
+            catalog.initialize("test", Map.of(CatalogProperties.URI,
+                    "http://127.0.0.1:"; + server.getAddress().getPort()));
+            CatalogBackedIcebergCatalogOps ops = new 
CatalogBackedIcebergCatalogOps(catalog);
+            RecordingConnectorContext context = new 
RecordingConnectorContext();
+            DorisConnectorException error = 
Assertions.assertThrows(DorisConnectorException.class,
+                    () -> metadata(ops, context, "rest", null).dropTable(null, 
new IcebergTableHandle("db", "t")));
+            Assertions.assertTrue(error.getMessage().contains("purge 
disabled"), error.getMessage());
+            Assertions.assertDoesNotThrow(() -> metadata(ops, context, "rest", 
"false")
+                    .dropTable(null, new IcebergTableHandle("db", "t")));
+            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);
+        }
+    }
+
+    @Test
+    void failedTableUnregisterStopsTheForceCascade() {
+        RecordingIcebergCatalogOps ops = new RecordingIcebergCatalogOps();
+        ops.tables = List.of("t1", "t2");
+        ops.dropTableFailure = new IllegalStateException("unregister 
rejected");
+        DorisConnectorException error = 
Assertions.assertThrows(DorisConnectorException.class,
+                () -> metadata(ops, new RecordingConnectorContext(), "rest", 
"false")
+                        .dropDatabase(null, "db", false, true));
+        Assertions.assertTrue(error.getMessage().contains("unregister 
rejected"), error.getMessage());
+        Assertions.assertEquals(List.of("listTableNames:db", 
"dropTable:db.t1:purge=false"), ops.log);
+    }
+
+    private static Map<String, String> properties(String flavor, String 
enabled) {
+        Map<String, String> raw = new HashMap<>();
+        raw.put(IcebergCatalogProperties.ICEBERG_CATALOG_TYPE, flavor);
+        if (enabled != null) {
+            raw.put(PURGE_PROPERTY, enabled);
+        }
+        return raw;
+    }
+
+    private static IcebergConnectorMetadata metadata(IcebergCatalogOps ops, 
RecordingConnectorContext context,
+            String flavor, String enabled) {
+        return new IcebergConnectorMetadata(ops, 
IcebergCatalogProperties.of(properties(flavor, enabled)), context);
+    }
+}
diff --git 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/RecordingIcebergCatalogOps.java
 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/RecordingIcebergCatalogOps.java
index 10511483f8e..ec3d5234c05 100644
--- 
a/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/RecordingIcebergCatalogOps.java
+++ 
b/fe/fe-connector/fe-connector-iceberg/src/test/java/org/apache/doris/connector/iceberg/RecordingIcebergCatalogOps.java
@@ -113,6 +113,7 @@ final class RecordingIcebergCatalogOps implements 
IcebergCatalogOps {
     String lastDropTableDb;
     String lastDropTableName;
     boolean lastDropPurge;
+    RuntimeException dropTableFailure;
     String lastRenameTableDb;
     String lastRenameTableOld;
     String lastRenameTableNew;
@@ -280,6 +281,9 @@ final class RecordingIcebergCatalogOps implements 
IcebergCatalogOps {
         lastDropTableDb = dbName;
         lastDropTableName = tableName;
         lastDropPurge = purge;
+        if (dropTableFailure != null) {
+            throw dropTableFailure;
+        }
     }
 
     @Override
diff --git 
a/fe/fe-connector/fe-connector-metastore-iceberg/src/main/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStoreProperties.java
 
b/fe/fe-connector/fe-connector-metastore-iceberg/src/main/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStoreProperties.java
index 0ce340e90b3..cea358600f2 100644
--- 
a/fe/fe-connector/fe-connector-metastore-iceberg/src/main/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStoreProperties.java
+++ 
b/fe/fe-connector/fe-connector-metastore-iceberg/src/main/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStoreProperties.java
@@ -50,6 +50,8 @@ import java.util.Map;
  */
 public final class IcebergRestMetaStoreProperties extends 
AbstractMetaStoreProperties {
 
+    public static final String DROP_WITH_PURGE_ENABLED = 
"iceberg.rest.drop-with-purge-enabled";
+
     private static final String ICEBERG_REST_ROLE_ARN = 
"iceberg.rest.role_arn";
     private static final String ICEBERG_REST_EXTERNAL_ID = 
"iceberg.rest.external-id";
 
@@ -75,6 +77,11 @@ public final class IcebergRestMetaStoreProperties extends 
AbstractMetaStorePrope
             description = "Ask the rest catalog service to vend per-table 
storage credentials.")
     private boolean vendedCredentialsEnabled;
 
+    @ConnectorProperty(names = {DROP_WITH_PURGE_ENABLED}, required = false,
+            description = "Whether REST table drops request file deletion, 
including DROP DATABASE FORCE. "
+                    + "Default: true.")
+    private boolean dropWithPurgeEnabled = true;
+
     // Kept as Strings, not ints: the values are handed to the iceberg SDK 
verbatim, and a catalog that was
     // created with an unparseable one is live today -- binding them as 
numbers would make it unbuildable.
     @ConnectorProperty(names = {"iceberg.rest.connection-timeout-ms"}, 
required = false,
@@ -206,6 +213,10 @@ public final class IcebergRestMetaStoreProperties extends 
AbstractMetaStorePrope
         return vendedCredentialsEnabled;
     }
 
+    public boolean isDropWithPurgeEnabled() {
+        return dropWithPurgeEnabled;
+    }
+
     public String getConnectionTimeoutMs() {
         return connectionTimeoutMs;
     }
@@ -352,6 +363,11 @@ public final class IcebergRestMetaStoreProperties extends 
AbstractMetaStorePrope
         rules.requireTogether(new String[] {accessKeyId, secretAccessKey},
                 "iceberg.rest.access-key-id and iceberg.rest.secret-access-key 
must be set together");
         rules.validate();
+        String dropWithPurge = raw.get(DROP_WITH_PURGE_ENABLED);
+        if (dropWithPurge != null && !"true".equalsIgnoreCase(dropWithPurge)
+                && !"false".equalsIgnoreCase(dropWithPurge)) {
+            throw new IllegalArgumentException(DROP_WITH_PURGE_ENABLED + " 
must be true or false");
+        }
     }
 
     /**
diff --git 
a/fe/fe-connector/fe-connector-metastore-iceberg/src/test/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStorePropertiesTest.java
 
b/fe/fe-connector/fe-connector-metastore-iceberg/src/test/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStorePropertiesTest.java
index 3b4d3d40be6..3bd07d4d681 100644
--- 
a/fe/fe-connector/fe-connector-metastore-iceberg/src/test/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStorePropertiesTest.java
+++ 
b/fe/fe-connector/fe-connector-metastore-iceberg/src/test/java/org/apache/doris/connector/metastore/iceberg/rest/IcebergRestMetaStorePropertiesTest.java
@@ -57,6 +57,28 @@ public class IcebergRestMetaStorePropertiesTest {
                 .contains("uri"), "The shared URI alias must retain 
value-aware catalog masking");
     }
 
+    @Test
+    public void dropWithPurgeDefaultsToTrueAndBindsExplicitValues() {
+        
Assertions.assertTrue(IcebergRestMetaStoreProperties.of(raw()).isDropWithPurgeEnabled());
+        for (String value : new String[] {"true", "TRUE", "false", "FALSE"}) {
+            Map<String, String> properties = 
raw("iceberg.rest.drop-with-purge-enabled", value);
+            IcebergRestMetaStoreProperties bound = 
IcebergRestMetaStoreProperties.of(properties);
+            bound.validate();
+            Assertions.assertEquals(Boolean.parseBoolean(value), 
bound.isDropWithPurgeEnabled());
+            Assertions.assertEquals(value, 
bound.matchedProperties().get("iceberg.rest.drop-with-purge-enabled"));
+        }
+    }
+
+    @Test
+    public void dropWithPurgeValidatesOnlyAtStatementTime() {
+        for (String value : new String[] {"", "yes", "0", " false "}) {
+            Map<String, String> properties = 
raw("iceberg.rest.drop-with-purge-enabled", value);
+            Assertions.assertDoesNotThrow(() -> 
IcebergRestMetaStoreProperties.of(properties));
+            Assertions.assertEquals("iceberg.rest.drop-with-purge-enabled must 
be true or false",
+                    validateError(properties));
+        }
+    }
+
     private static Map<String, String> raw(String... kv) {
         Map<String, String> m = new HashMap<>();
         for (int i = 0; i < kv.length; i += 2) {
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