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 b3be2180449 [fix](iceberg) Avoid table metadata loads for views on 
branch-4.1 (#70812)
b3be2180449 is described below

commit b3be21804492e1daaf05ef721db24e3b890c7a47
Author: Gabriel <[email protected]>
AuthorDate: Mon Nov 23 21:31:37 2026 +0800

    [fix](iceberg) Avoid table metadata loads for views on branch-4.1 (#70812)
    
    ### What problem does this PR solve?
    
    Related PR: #69836, #69946
    
    Adapt the external-view fixes to `branch-4.1`'s legacy Iceberg
    implementation. Although snapshot loading already skips views, schema
    reads can still fall back to table metadata and fail when a REST catalog
    rejects table requests for view names.
    
    Read view schemas through the authenticated View cache, keyed by view
    UUID, schema ID, and mapping options. Skip table-only partition and
    row-lineage metadata, and reject unsupported view scan parameters
    instead of silently ignoring them. Preserve the branch's existing
    table-generation leases and missing-object lookup repair.
    
    ### Release note
    
    Fix Iceberg view schema reads on catalogs that reject table requests for
    view names, and reject unsupported view scan parameters.
    
    ### Validation
    
    - 229 focused FE unit tests passed across external table/view, schema
    utility, metadata cache, schema display, write-schema context,
    metadata-column, system-table, and statement-snapshot suites; no
    failures, errors, or skips.
    - Before the fix, the selector-rejection test and view schema cases
    reproduced the missing validation and table-endpoint error.
    - FE Checkstyle: zero violations. `git diff --check` passed.
    - No live external catalog integration test was run.
    
    ### Check List (For Author)
    
    - Test
        - [x] Unit Test
    - Behavior changed:
    - [x] Yes. View metadata reads avoid table endpoints, and unsupported
    view scan parameters fail explicitly.
    - Does this need documentation?
        - [x] No.
    
    Co-authored-by: daidai <[email protected]>
---
 .../iceberg/IcebergExternalMetaCache.java          |  30 +++
 .../datasource/iceberg/IcebergExternalTable.java   |  28 ++-
 .../doris/datasource/iceberg/IcebergUtils.java     |   6 +
 .../iceberg/IcebergExternalTableTest.java          |  59 ++++++
 .../iceberg/IcebergExternalViewTest.java           | 211 +++++++++++++++++++++
 5 files changed, 331 insertions(+), 3 deletions(-)

diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
index eaef352f2da..ae82d461729 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalMetaCache.java
@@ -46,6 +46,7 @@ import org.apache.commons.lang3.exception.ExceptionUtils;
 import org.apache.iceberg.ManifestContent;
 import org.apache.iceberg.ManifestFiles;
 import org.apache.iceberg.ManifestReader;
+import org.apache.iceberg.Schema;
 import org.apache.iceberg.Snapshot;
 import org.apache.iceberg.Table;
 import org.apache.iceberg.io.FileIO;
@@ -56,6 +57,7 @@ import org.apache.logging.log4j.Logger;
 import java.io.Closeable;
 import java.io.IOException;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.IdentityHashMap;
 import java.util.List;
 import java.util.Map;
@@ -471,6 +473,34 @@ public class IcebergExternalMetaCache extends 
AbstractExternalMetaCache {
         return viewEntry.get(nameMapping.getCtlId()).get(nameMapping);
     }
 
+    public IcebergSchemaCacheValue 
getIcebergViewSchemaCacheValue(ExternalTable dorisTable, long schemaId) {
+        try {
+            return 
dorisTable.getCatalog().getExecutionAuthenticator().execute(() -> {
+                View view = getIcebergView(dorisTable);
+                Schema viewSchema = schemaId == IcebergUtils.NEWEST_SCHEMA_ID
+                        ? view.schema() : view.schemas().get((int) schemaId);
+                Preconditions.checkNotNull(viewSchema,
+                        "Schema for view %s.%s is null", 
dorisTable.getDbName(), dorisTable.getName());
+                NameMapping nameMapping = dorisTable.getOrBuildNameMapping();
+                boolean enableMappingVarbinary = 
dorisTable.getCatalog().getEnableMappingVarbinary();
+                boolean enableMappingTimestampTz = 
dorisTable.getCatalog().getEnableMappingTimestampTz();
+                // View UUIDs isolate recreated views; mapping options 
identify the schema projection.
+                IcebergSchemaCacheKey key = new IcebergSchemaCacheKey(
+                        nameMapping, "view:" + view.uuid(), 
viewSchema.schemaId(),
+                        enableMappingVarbinary, enableMappingTimestampTz);
+                return (IcebergSchemaCacheValue) 
schemaEntry.get(nameMapping.getCtlId()).get(key, ignored -> {
+                    IcebergSchemaCacheValue value = new 
IcebergSchemaCacheValue(
+                            IcebergUtils.parseSchema(viewSchema, 
enableMappingVarbinary, enableMappingTimestampTz),
+                            Collections.emptyList());
+                    value.validateSchema();
+                    return value;
+                });
+            });
+        } catch (Exception e) {
+            throw new RuntimeException(ExceptionUtils.getRootCauseMessage(e), 
e);
+        }
+    }
+
     public IcebergSchemaCacheValue getIcebergSchemaCacheValue(NameMapping 
nameMapping, long schemaId) {
         IcebergTableCacheValue.Lease statementLease = 
statementLease(nameMapping);
         if (statementLease != null) {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalTable.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalTable.java
index 7399a4901b2..f49b6c75234 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalTable.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergExternalTable.java
@@ -63,6 +63,7 @@ import org.apache.iceberg.view.View;
 import org.apache.iceberg.view.ViewVersion;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -109,6 +110,10 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
     @Override
     public Optional<SchemaCacheValue> getSchemaCacheValue() {
         return withMissingTableRepair(() -> {
+            // An empty view snapshot must not fall back to the table metadata 
cache.
+            if (isView()) {
+                return Optional.of(IcebergUtils.getSchemaCacheValue(this, 
IcebergUtils.NEWEST_SCHEMA_ID));
+            }
             return Optional.of(IcebergUtils.withSnapshotCacheValue(
                     MvccUtil.getSnapshotFromContext(this), this,
                     snapshotValue -> IcebergUtils.getSchemaCacheValue(this, 
snapshotValue)));
@@ -167,11 +172,14 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
 
     @Override
     public Map<String, PartitionItem> 
getAndCopyPartitionItems(Optional<MvccSnapshot> snapshot) {
-        return Maps.newHashMap(IcebergUtils.getIcebergPartitionItems(snapshot, 
this));
+        return Maps.newHashMap(getNameToPartitionItems(snapshot));
     }
 
     @Override
     public Map<String, PartitionItem> 
getNameToPartitionItems(Optional<MvccSnapshot> snapshot) {
+        if (isView()) {
+            return Collections.emptyMap();
+        }
         return IcebergUtils.getIcebergPartitionItems(snapshot, this);
     }
 
@@ -187,6 +195,9 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
 
     @Override
     public List<Column> getPartitionColumns(Optional<MvccSnapshot> snapshot) {
+        if (isView()) {
+            return Collections.emptyList();
+        }
         return IcebergUtils.getIcebergPartitionColumns(snapshot, this);
     }
 
@@ -242,7 +253,9 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
      */
     @Override
     public synchronized boolean isValidRelatedTable() {
-        makeSureInitialized();
+        if (isView()) {
+            return false;
+        }
         if (isValidRelatedTableCached) {
             return isValidRelatedTable;
         }
@@ -262,6 +275,11 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
     public MvccSnapshot loadSnapshot(Optional<TableSnapshot> tableSnapshot, 
Optional<TableScanParams> scanParams) {
         return withMissingTableRepair(() -> {
             if (isView()) {
+                // View expansion cannot apply relation scan parameters to the 
base tables.
+                if (scanParams.isPresent()) {
+                    throw new UnsupportedOperationException(
+                            "view not supported with scan params: @" + 
scanParams.get().getParamType());
+                }
                 return new EmptyMvccSnapshot();
             } else {
                 return new 
IcebergMvccSnapshot(IcebergUtils.getSnapshotCacheValue(
@@ -288,6 +306,10 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
     @Override
     public List<Column> getFullSchema(Optional<MvccSnapshot> snapshot) {
         return withMissingTableRepair(() -> {
+            // Views have no physical row-id or row-lineage metadata.
+            if (isView()) {
+                return new ArrayList<>(IcebergUtils.getIcebergSchema(this, 
snapshot));
+            }
             return IcebergUtils.withSnapshotCacheValue(snapshot, this, 
this::projectFullSchema);
 
         });
@@ -344,7 +366,7 @@ public class IcebergExternalTable extends ExternalTable 
implements MTMVRelatedTa
 
     @Override
     public boolean supportInternalPartitionPruned() {
-        return true;
+        return !isView();
     }
 
     @Override
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
index dc775bb948c..22f571b630c 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/datasource/iceberg/IcebergUtils.java
@@ -2073,6 +2073,9 @@ public class IcebergUtils {
 
     // read schema from iceberg.schema entry
     public static IcebergSchemaCacheValue getSchemaCacheValue(ExternalTable 
dorisTable, long schemaId) {
+        if (dorisTable instanceof IcebergExternalTable && dorisTable.isView()) 
{
+            return 
icebergExternalMetaCache(dorisTable).getIcebergViewSchemaCacheValue(dorisTable, 
schemaId);
+        }
         return icebergExternalMetaCache(dorisTable)
                 
.getIcebergSchemaCacheValue(dorisTable.getOrBuildNameMapping(), schemaId);
     }
@@ -2482,6 +2485,9 @@ public class IcebergUtils {
     }
 
     public static List<Column> getIcebergSchema(ExternalTable dorisTable, 
Optional<MvccSnapshot> snapshot) {
+        if (dorisTable instanceof IcebergExternalTable && dorisTable.isView()) 
{
+            return getSchemaCacheValue(dorisTable, 
NEWEST_SCHEMA_ID).getSchema();
+        }
         return withSnapshotCacheValue(snapshot, dorisTable,
                 cacheValue -> getSchemaCacheValue(dorisTable, 
cacheValue).getSchema());
     }
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalTableTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalTableTest.java
index 9fed78763a8..eef5ca4ddca 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalTableTest.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalTableTest.java
@@ -17,6 +17,7 @@
 
 package org.apache.doris.datasource.iceberg;
 
+import org.apache.doris.analysis.TableScanParams;
 import org.apache.doris.catalog.Column;
 import org.apache.doris.catalog.PartitionItem;
 import org.apache.doris.catalog.PartitionKey;
@@ -26,6 +27,8 @@ import org.apache.doris.common.AnalysisException;
 import org.apache.doris.common.Pair;
 import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
 import org.apache.doris.datasource.metacache.MetaCache;
+import org.apache.doris.datasource.mvcc.EmptyMvccSnapshot;
+import org.apache.doris.datasource.mvcc.MvccSnapshot;
 import org.apache.doris.qe.ConnectContext;
 
 import com.google.common.collect.Lists;
@@ -44,6 +47,8 @@ import org.mockito.Mockito;
 import org.mockito.MockitoAnnotations;
 
 import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
 import java.util.List;
 import java.util.Map;
 import java.util.Optional;
@@ -184,6 +189,60 @@ public class IcebergExternalTableTest {
         }
     }
 
+    @Test
+    public void testViewSnapshotDoesNotLoadTableMetadata() {
+        IcebergExternalTable table = createSpyTable();
+        Mockito.doReturn(true).when(table).isView();
+        MvccSnapshot fence = new EmptyMvccSnapshot();
+        List<MvccSnapshot> snapshots = Arrays.asList(
+                table.loadSnapshot(Optional.empty(), Optional.empty()),
+                table.loadSnapshot(Optional.empty(), Optional.empty(), 
Optional.empty()),
+                table.loadSnapshot(Optional.empty(), Optional.empty(), 
Optional.of(fence)),
+                table.loadLatestSnapshotFence());
+        for (MvccSnapshot snapshot : snapshots) {
+            Assertions.assertInstanceOf(EmptyMvccSnapshot.class, snapshot);
+        }
+        Mockito.verify(table, Mockito.never()).getIcebergTable();
+        Mockito.verify(table, Mockito.never()).getIcebergView();
+    }
+
+    @Test
+    public void testViewSnapshotRejectsScanParams() {
+        IcebergExternalTable table = createSpyTable();
+        Mockito.doReturn(true).when(table).isView();
+        MvccSnapshot fence = new EmptyMvccSnapshot();
+        Map<String, String> incrementalParams = Maps.newHashMap();
+        incrementalParams.put("startSnapshotId", "1");
+        incrementalParams.put("endSnapshotId", "5");
+        List<TableScanParams> selectors = Arrays.asList(
+                new TableScanParams(TableScanParams.BRANCH,
+                        Collections.emptyMap(), 
Collections.singletonList("b1")),
+                new TableScanParams(TableScanParams.BRANCH,
+                        Collections.singletonMap(TableScanParams.PARAMS_NAME, 
"b1"), Collections.emptyList()),
+                new TableScanParams(TableScanParams.TAG,
+                        Collections.emptyMap(), 
Collections.singletonList("t1")),
+                new TableScanParams(TableScanParams.TAG,
+                        Collections.singletonMap(TableScanParams.PARAMS_NAME, 
"t1"), Collections.emptyList()),
+                new TableScanParams(TableScanParams.INCREMENTAL_READ, 
incrementalParams, Collections.emptyList()),
+                new TableScanParams(TableScanParams.OPTIONS,
+                        Collections.singletonMap("scan.snapshot-id", "7"), 
Collections.emptyList()));
+        for (TableScanParams selector : selectors) {
+            List<UnsupportedOperationException> errors = Arrays.asList(
+                    
Assertions.assertThrows(UnsupportedOperationException.class,
+                            () -> table.loadSnapshot(Optional.empty(), 
Optional.of(selector))),
+                    
Assertions.assertThrows(UnsupportedOperationException.class,
+                            () -> table.loadSnapshot(Optional.empty(), 
Optional.of(selector), Optional.empty())),
+                    
Assertions.assertThrows(UnsupportedOperationException.class,
+                            () -> table.loadSnapshot(Optional.empty(), 
Optional.of(selector), Optional.of(fence))));
+            for (UnsupportedOperationException error : errors) {
+                Assertions.assertEquals("view not supported with scan params: 
@" + selector.getParamType(),
+                        error.getMessage());
+            }
+        }
+        Mockito.verify(table, Mockito.never()).getIcebergTable();
+        Mockito.verify(table, Mockito.never()).getIcebergView();
+    }
+
     @Test
     public void testIsSupportedPartitionTable() {
         IcebergExternalDatabase database = new 
IcebergExternalDatabase(mockCatalog, 1L, "2", "2");
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalViewTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalViewTest.java
new file mode 100644
index 00000000000..76ca0fa2966
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/datasource/iceberg/IcebergExternalViewTest.java
@@ -0,0 +1,211 @@
+// 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.catalog.Column;
+import org.apache.doris.catalog.Env;
+import org.apache.doris.catalog.PartitionType;
+import org.apache.doris.catalog.PrimitiveType;
+import org.apache.doris.common.security.authentication.ExecutionAuthenticator;
+import org.apache.doris.datasource.ExternalMetaCacheMgr;
+import org.apache.doris.datasource.mvcc.EmptyMvccSnapshot;
+import org.apache.doris.datasource.mvcc.MvccSnapshot;
+
+import org.apache.commons.lang3.exception.ExceptionUtils;
+import org.apache.iceberg.Schema;
+import org.apache.iceberg.exceptions.BadRequestException;
+import org.apache.iceberg.exceptions.NoSuchViewException;
+import org.apache.iceberg.types.Types;
+import org.apache.iceberg.view.View;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
+import org.mockito.Mockito;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Optional;
+import java.util.UUID;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+
+public class IcebergExternalViewTest {
+    private static final UUID VIEW_UUID = 
UUID.fromString("00000000-0000-0000-0000-000000000001");
+
+    private IcebergExternalTable table;
+    private IcebergExternalMetaCache cache;
+    private View view;
+    private MockedStatic<Env> mockedEnv;
+    private ExecutorService executor;
+
+    @BeforeEach
+    public void setUp() {
+        IcebergExternalCatalog catalog = 
Mockito.mock(IcebergExternalCatalog.class);
+        Mockito.when(catalog.getId()).thenReturn(1L);
+        Mockito.when(catalog.getExecutionAuthenticator()).thenReturn(new 
ExecutionAuthenticator() {});
+        IcebergExternalDatabase database = new 
IcebergExternalDatabase(catalog, 2L, "db", "db");
+        table = Mockito.spy(new IcebergExternalTable(3L, "view1", "view1", 
catalog, database));
+        Mockito.doNothing().when(table).makeSureInitialized();
+        Mockito.doReturn(true).when(table).isView();
+
+        executor = Executors.newSingleThreadExecutor();
+        cache = Mockito.spy(new IcebergExternalMetaCache(executor));
+        cache.initCatalog(1L, Collections.emptyMap());
+        view = Mockito.mock(View.class);
+        Mockito.when(view.uuid()).thenReturn(VIEW_UUID);
+        Mockito.when(view.schema()).thenReturn(new Schema(
+                Types.NestedField.required(1, "id", Types.IntegerType.get()),
+                Types.NestedField.optional(2, "name", 
Types.StringType.get())));
+        Mockito.doReturn(view).when(cache).getIcebergView(table);
+        // A valid view can be rejected by the catalog's table endpoint.
+        
Mockito.doThrow(tableEndpointError()).when(cache).getSnapshotCache(table);
+        Mockito.doThrow(tableEndpointError()).when(cache)
+                .withSnapshotCacheValue(Mockito.eq(table), Mockito.any());
+        
Mockito.doThrow(tableEndpointError()).when(cache).getIcebergTable(table);
+
+        Env env = Mockito.mock(Env.class);
+        ExternalMetaCacheMgr manager = 
Mockito.mock(ExternalMetaCacheMgr.class);
+        Mockito.when(env.getExtMetaCacheMgr()).thenReturn(manager);
+        Mockito.when(manager.iceberg(1L)).thenReturn(cache);
+        mockedEnv = Mockito.mockStatic(Env.class);
+        mockedEnv.when(Env::getCurrentEnv).thenReturn(env);
+    }
+
+    @AfterEach
+    public void tearDown() {
+        mockedEnv.close();
+        executor.shutdownNow();
+    }
+
+    @Test
+    public void testSchemaCacheReadsViewSchema() {
+        IcebergSchemaCacheValue value = (IcebergSchemaCacheValue) 
table.getSchemaCacheValue().get();
+        assertViewSchema(value.getSchema());
+        Assertions.assertTrue(value.getPartitionColumns().isEmpty());
+        Assertions.assertSame(value, table.getSchemaCacheValue().get());
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testFullSchemaDoesNotLoadTableOrAppendTableMetadataColumns() {
+        Mockito.doReturn(true).when(table).needInternalHiddenColumns();
+        assertViewSchema(table.getFullSchema(Optional.of(new 
EmptyMvccSnapshot())));
+        assertViewSchema(table.getFullSchema());
+        Mockito.verify(table, Mockito.never()).getIcebergTable();
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testSchemaUtilityReadsViewSchema() {
+        assertViewSchema(IcebergUtils.getIcebergSchema(table));
+        assertViewSchema(IcebergUtils.getIcebergSchema(table, Optional.of(new 
EmptyMvccSnapshot())));
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testViewHasNoTablePartitions() throws Exception {
+        Optional<MvccSnapshot> snapshot = Optional.of(new EmptyMvccSnapshot());
+        Assertions.assertFalse(table.supportInternalPartitionPruned());
+        Assertions.assertFalse(table.isValidRelatedTable());
+        Assertions.assertEquals(PartitionType.UNPARTITIONED, 
table.getPartitionType(snapshot));
+        Assertions.assertTrue(table.getPartitionColumns(snapshot).isEmpty());
+        
Assertions.assertTrue(table.getPartitionColumnNames(snapshot).isEmpty());
+        
Assertions.assertTrue(table.getNameToPartitionItems(snapshot).isEmpty());
+        
Assertions.assertTrue(table.getAndCopyPartitionItems(snapshot).isEmpty());
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testRefreshedViewSchemaIsReadFromViewCache() {
+        assertViewSchema(table.getFullSchema(Optional.empty()));
+        View refreshedView = Mockito.mock(View.class);
+        Mockito.when(refreshedView.uuid()).thenReturn(VIEW_UUID);
+        Mockito.when(refreshedView.schema()).thenReturn(new Schema(1,
+                Types.NestedField.optional(3, "evolved", 
Types.LongType.get())));
+        Mockito.when(cache.getIcebergView(table)).thenReturn(refreshedView);
+
+        List<Column> columns = table.getFullSchema(Optional.empty());
+        Assertions.assertEquals(1, columns.size());
+        Assertions.assertEquals("evolved", columns.get(0).getName());
+        Assertions.assertEquals(PrimitiveType.BIGINT, 
columns.get(0).getType().getPrimitiveType());
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testRecreatedViewDoesNotReuseOldSchema() {
+        assertViewSchema(table.getFullSchema(Optional.empty()));
+        View recreatedView = Mockito.mock(View.class);
+        
Mockito.when(recreatedView.uuid()).thenReturn(UUID.fromString("00000000-0000-0000-0000-000000000002"));
+        Mockito.when(recreatedView.schema()).thenReturn(new Schema(
+                Types.NestedField.optional(3, "recreated", 
Types.LongType.get())));
+        Mockito.when(cache.getIcebergView(table)).thenReturn(recreatedView);
+
+        List<Column> columns = table.getFullSchema(Optional.empty());
+        Assertions.assertEquals(1, columns.size());
+        Assertions.assertEquals("recreated", columns.get(0).getName());
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testViewSchemaStillRejectsDuplicateColumns() {
+        Mockito.when(view.schema()).thenReturn(new Schema(
+                Types.NestedField.optional(1, "ID", Types.IntegerType.get()),
+                Types.NestedField.optional(2, "id", Types.IntegerType.get())));
+
+        RuntimeException error = 
Assertions.assertThrows(RuntimeException.class, table::getSchemaCacheValue);
+        
Assertions.assertTrue(ExceptionUtils.getRootCauseMessage(error).contains("Duplicate
 column name"));
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testDeletedViewFailureIsNotTreatedAsATable() {
+        Mockito.when(cache.getIcebergView(table)).thenThrow(new 
NoSuchViewException("View was deleted"));
+        RuntimeException error = 
Assertions.assertThrows(RuntimeException.class, table::getSchemaCacheValue);
+        Assertions.assertInstanceOf(NoSuchViewException.class, 
error.getCause());
+        verifyNoTableMetadata();
+    }
+
+    @Test
+    public void testOrdinaryTableMetadataFailureStillPropagates() {
+        Mockito.doReturn(false).when(table).isView();
+        Assertions.assertThrows(BadRequestException.class, 
table::getSchemaCacheValue);
+        Mockito.verify(cache).withSnapshotCacheValue(Mockito.eq(table), 
Mockito.any());
+        Mockito.verify(cache, Mockito.never()).getIcebergView(table);
+    }
+
+    private void verifyNoTableMetadata() {
+        Mockito.verify(cache, Mockito.never()).getSnapshotCache(table);
+        Mockito.verify(cache, 
Mockito.never()).withSnapshotCacheValue(Mockito.eq(table), Mockito.any());
+        Mockito.verify(cache, Mockito.never()).getIcebergTable(table);
+        Mockito.verify(cache, Mockito.never()).getTableCacheValue(table);
+    }
+
+    private static void assertViewSchema(List<Column> columns) {
+        Assertions.assertEquals(2, columns.size());
+        Assertions.assertEquals("id", columns.get(0).getName());
+        Assertions.assertEquals(PrimitiveType.INT, 
columns.get(0).getType().getPrimitiveType());
+        Assertions.assertEquals("name", columns.get(1).getName());
+        Assertions.assertEquals(PrimitiveType.STRING, 
columns.get(1).getType().getPrimitiveType());
+    }
+
+    private static BadRequestException tableEndpointError() {
+        return new BadRequestException("Table 'db.view1' is not an Iceberg 
compatible table");
+    }
+}


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

Reply via email to