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 acbf7b89fe1 [fix](jdbc) Backport unsupported scan type guards to 
branch-4.1 (#71321)
acbf7b89fe1 is described below

commit acbf7b89fe1814953c3bcbd3411bf16145421330
Author: Gabriel <[email protected]>
AuthorDate: Thu Dec 3 14:49:35 2026 +0800

    [fix](jdbc) Backport unsupported scan type guards to branch-4.1 (#71321)
    
    ### What problem does this PR solve?
    
    Issue Number: None
    
    Related PR: apache/doris#71242
    
    Backport
    [apache/doris#71242](https://github.com/apache/doris/pull/71242), master
    commit `d026e254d0a24af87390a1d7bdf0dbdf931d5193`, to `branch-4.1`.
    
    `COUNT(*)` and other constant projections can retain an unsupported
    fallback column from an external schema and crash BE during descriptor
    construction. Reject unsupported-only scans, choose readable fallback
    columns for mixed schemas, and guard both FE serialization and BE
    descriptor ingestion. Preserve the existing column-authorization
    requirements, including eliminated subqueries.
    
    ### Branch adaptations
    
    - Put the serialization guard in the branch's
    `SlotDescriptor.toThrift()` and keep its descriptor-table API.
    - Retain the branch's existing authorization implementation and scan
    translation; backport the logical fallback checks without importing
    unrelated master refactors.
    - Use Java 8-compatible collections and the branch's aggregate-state
    test constructor. The PostgreSQL regression suite and generated result
    snapshot match upstream byte for byte.
    
    ### Validation
    
    - Fresh repository FE build and targeted tests passed: 55 tests, zero
    failures, errors or skips. Covers scan-slot validation, unsupported
    logical fallback selection, COUNT(*) ordering, column pruning,
    expression utilities and column privileges.
    - FE Checkstyle passed for `fe-common` and `fe-core`; clang-format 16
    passed for both changed C++ files.
    - Both changed C++ production/test translation units compiled with ASAN
    instrumentation. Existing deprecated-API and shadow warnings were left
    nonfatal for the local toolchain; no build-policy changes are included.
    - The PostgreSQL Groovy suite compiled. Live PostgreSQL regression and
    BE unit-test execution were not run locally and remain for CI.
    
    ### Release note
    
    External queries that retain an unsupported scan column now report an
    error instead of crashing BE. Supported columns in mixed schemas remain
    usable.
    
    ### Check List (For Author)
    
    - [x] Regression tests included
    - [x] Unit tests included
    - Behavior changed: Yes, unsupported scans fail with a descriptive
    error.
    - Documentation needed: No.
---
 be/src/runtime/descriptors.cpp                     |  18 +++
 be/test/runtime/descriptor_test.cpp                |  99 ++++++++++++
 .../main/java/org/apache/doris/catalog/Type.java   |  18 +++
 .../org/apache/doris/analysis/SlotDescriptor.java  |   6 +
 .../glue/translator/PhysicalPlanTranslator.java    |  17 ++-
 .../nereids/rules/rewrite/CheckDataTypes.java      |  11 ++
 .../nereids/rules/rewrite/CheckPrivileges.java     |   5 +
 .../doris/nereids/rules/rewrite/ColumnPruning.java |  17 ++-
 .../org/apache/doris/nereids/types/DataType.java   |  16 ++
 .../apache/doris/nereids/util/ExpressionUtils.java |  14 +-
 .../translator/ScanSlotTypeValidationTest.java     | 118 ++++++++++++++
 .../nereids/privileges/TestCheckPrivileges.java    |  15 ++
 .../rules/rewrite/UnsupportedScanPruningTest.java  | 170 +++++++++++++++++++++
 .../jdbc/test_pg_jdbc_unsupported_scan_types.out   |  45 ++++++
 .../test_pg_jdbc_unsupported_scan_types.groovy     | 160 +++++++++++++++++++
 15 files changed, 722 insertions(+), 7 deletions(-)

diff --git a/be/src/runtime/descriptors.cpp b/be/src/runtime/descriptors.cpp
index edd1f8b99d3..fb2ba730cb6 100644
--- a/be/src/runtime/descriptors.cpp
+++ b/be/src/runtime/descriptors.cpp
@@ -636,6 +636,19 @@ int RowDescriptor::get_column_id(int slot_id) const {
     return -1;
 }
 
+static bool slot_type_contains_unsupported(const TTypeDesc& type) {
+    // Array, map and struct children share the flattened type-node list.
+    for (const auto& node : type.types) {
+        if (node.type == TTypeNodeType::SCALAR &&
+            node.scalar_type.type == TPrimitiveType::UNSUPPORTED) {
+            return true;
+        }
+    }
+    // Aggregate-state inputs are stored as separate type descriptors.
+    return std::any_of(type.sub_types.begin(), type.sub_types.end(),
+                       slot_type_contains_unsupported);
+}
+
 Status DescriptorTbl::create(ObjectPool* pool, const TDescriptorTable& 
thrift_tbl,
                              DescriptorTbl** tbl) {
     *tbl = pool->add(new DescriptorTbl());
@@ -704,6 +717,11 @@ Status DescriptorTbl::create(ObjectPool* pool, const 
TDescriptorTable& thrift_tb
     }
 
     for (const auto& tdesc : thrift_tbl.slotDescriptors) {
+        // Older FEs can retain an unsupported fallback column for COUNT(*).
+        if (slot_type_contains_unsupported(tdesc.slotType)) {
+            return Status::NotSupported("Unsupported type UNSUPPORTED for slot 
{} (column '{}')",
+                                        tdesc.id, tdesc.colName);
+        }
         SlotDescriptor* slot_d = pool->add(new SlotDescriptor(tdesc));
         (*tbl)->_slot_desc_map[tdesc.id] = slot_d;
 
diff --git a/be/test/runtime/descriptor_test.cpp 
b/be/test/runtime/descriptor_test.cpp
index 20c2b1000c8..a62ccbc13b7 100644
--- a/be/test/runtime/descriptor_test.cpp
+++ b/be/test/runtime/descriptor_test.cpp
@@ -20,6 +20,7 @@
 #include <gtest/gtest.h>
 
 #include "common/exception.h"
+#include "common/object_pool.h"
 #include "runtime/descriptors.h"
 
 namespace doris {
@@ -84,6 +85,104 @@ TEST_F(SlotDescriptorTest, BasicConstructor) {
     });
 }
 
+TEST_F(SlotDescriptorTest, RejectUnsupportedSlotType) {
+    auto slot = create_basic_slot_descriptor(7, "unsupported_column");
+    slot.slotType.types[0].scalar_type.__set_type(TPrimitiveType::UNSUPPORTED);
+    TTupleDescriptor tuple;
+    tuple.__set_id(1);
+    TDescriptorTable thrift_table;
+    thrift_table.__set_tupleDescriptors({tuple});
+    thrift_table.__set_slotDescriptors({slot});
+    ObjectPool pool;
+    DescriptorTbl* table = nullptr;
+    auto status = DescriptorTbl::create(&pool, thrift_table, &table);
+    ASSERT_FALSE(status.ok());
+    EXPECT_NE(status.to_string().find("UNSUPPORTED"), std::string::npos);
+    EXPECT_NE(status.to_string().find("unsupported_column"), 
std::string::npos);
+    EXPECT_NE(status.to_string().find("7"), std::string::npos);
+}
+
+TEST_F(SlotDescriptorTest, RejectUnsupportedNestedSlotTypes) {
+    for (auto nested_type : {TTypeNodeType::ARRAY, TTypeNodeType::MAP, 
TTypeNodeType::STRUCT}) {
+        auto slot = create_basic_slot_descriptor();
+        auto unsupported = slot.slotType.types[0];
+        unsupported.scalar_type.__set_type(TPrimitiveType::UNSUPPORTED);
+        TTypeNode root;
+        root.__set_type(nested_type);
+        if (nested_type == TTypeNodeType::ARRAY) {
+            root.__set_contains_nulls({true});
+        }
+        if (nested_type == TTypeNodeType::MAP) {
+            root.__set_contains_nulls({true, true});
+            slot.slotType.__set_types({root, slot.slotType.types[0], 
unsupported});
+        } else {
+            if (nested_type == TTypeNodeType::STRUCT) {
+                TStructField field;
+                field.__set_name("nested_column");
+                field.__set_contains_null(true);
+                root.__set_struct_fields({field});
+            }
+            slot.slotType.__set_types({root, unsupported});
+        }
+        TTupleDescriptor tuple;
+        tuple.__set_id(1);
+        TDescriptorTable thrift_table;
+        thrift_table.__set_tupleDescriptors({tuple});
+        thrift_table.__set_slotDescriptors({slot});
+        ObjectPool pool;
+        DescriptorTbl* table = nullptr;
+        EXPECT_FALSE(DescriptorTbl::create(&pool, thrift_table, &table).ok());
+
+        for (auto& node : slot.slotType.types) {
+            if (node.type == TTypeNodeType::SCALAR &&
+                node.scalar_type.type == TPrimitiveType::UNSUPPORTED) {
+                node.scalar_type.__set_type(TPrimitiveType::INT);
+            }
+        }
+        thrift_table.__set_slotDescriptors({slot});
+        EXPECT_TRUE(DescriptorTbl::create(&pool, thrift_table, &table).ok());
+    }
+}
+
+TEST_F(SlotDescriptorTest, RejectUnsupportedAggregateStateInput) {
+    auto slot = create_basic_slot_descriptor();
+    auto unsupported = slot.slotType;
+    unsupported.types[0].scalar_type.__set_type(TPrimitiveType::UNSUPPORTED);
+    slot.slotType.types[0].scalar_type.__set_type(TPrimitiveType::AGG_STATE);
+    slot.slotType.__set_sub_types({unsupported});
+    slot.slotType.__set_function_name("sum");
+    slot.slotType.__set_result_is_nullable(true);
+    TTupleDescriptor tuple;
+    tuple.__set_id(1);
+    TDescriptorTable thrift_table;
+    thrift_table.__set_tupleDescriptors({tuple});
+    thrift_table.__set_slotDescriptors({slot});
+    ObjectPool pool;
+    DescriptorTbl* table = nullptr;
+    EXPECT_FALSE(DescriptorTbl::create(&pool, thrift_table, &table).ok());
+}
+
+TEST_F(SlotDescriptorTest, ValidDescriptorAfterUnsupportedDescriptor) {
+    auto slot = create_basic_slot_descriptor();
+    slot.slotType.types[0].scalar_type.__set_type(TPrimitiveType::UNSUPPORTED);
+    TTupleDescriptor tuple;
+    tuple.__set_id(1);
+    TDescriptorTable thrift_table;
+    thrift_table.__set_tupleDescriptors({tuple});
+    thrift_table.__set_slotDescriptors({slot});
+    ObjectPool pool;
+    DescriptorTbl* table = nullptr;
+    ASSERT_FALSE(DescriptorTbl::create(&pool, thrift_table, &table).ok());
+
+    for (auto scalar_type :
+         {TPrimitiveType::INT, TPrimitiveType::STRING, 
TPrimitiveType::NULL_TYPE}) {
+        slot.slotType.types[0].scalar_type.__set_type(scalar_type);
+        thrift_table.__set_slotDescriptors({slot});
+        ASSERT_TRUE(DescriptorTbl::create(&pool, thrift_table, &table).ok());
+        ASSERT_NE(table->get_slot_descriptor(slot.id), nullptr);
+    }
+}
+
 TEST_F(SlotDescriptorTest, VirtualColumnExprValid) {
     // Test constructor with valid virtual column expression
     TSlotDescriptor tdesc = create_basic_slot_descriptor();
diff --git a/fe/fe-common/src/main/java/org/apache/doris/catalog/Type.java 
b/fe/fe-common/src/main/java/org/apache/doris/catalog/Type.java
index b328344268f..e99f1f83632 100644
--- a/fe/fe-common/src/main/java/org/apache/doris/catalog/Type.java
+++ b/fe/fe-common/src/main/java/org/apache/doris/catalog/Type.java
@@ -423,6 +423,24 @@ public abstract class Type {
         return isScalarType(PrimitiveType.UNSUPPORTED);
     }
 
+    /** Whether this type contains an external type that BE cannot execute. */
+    public boolean typeContainsUnsupported() {
+        // An external ARRAY<UNSUPPORTED>, for example, must not become a scan 
fallback column.
+        if (isStructType()) {
+            return ((StructType) this).getFields().stream()
+                    .anyMatch(field -> 
field.getType().typeContainsUnsupported());
+        } else if (isMapType()) {
+            MapType mapType = (MapType) this;
+            return mapType.getKeyType().typeContainsUnsupported()
+                    || mapType.getValueType().typeContainsUnsupported();
+        } else if (isArrayType()) {
+            return ((ArrayType) this).getItemType().typeContainsUnsupported();
+        } else if (isAggStateType()) {
+            return ((AggStateType) 
this).getSubTypes().stream().anyMatch(Type::typeContainsUnsupported);
+        }
+        return isUnsupported();
+    }
+
     public boolean isValid() {
         return !isInvalid();
     }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/analysis/SlotDescriptor.java 
b/fe/fe-core/src/main/java/org/apache/doris/analysis/SlotDescriptor.java
index af0231c4f09..52c6b4876ab 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/analysis/SlotDescriptor.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/analysis/SlotDescriptor.java
@@ -23,6 +23,7 @@ package org.apache.doris.analysis;
 import org.apache.doris.catalog.Column;
 import org.apache.doris.catalog.OlapTable;
 import org.apache.doris.catalog.Type;
+import org.apache.doris.nereids.exceptions.AnalysisException;
 import org.apache.doris.thrift.TColumnAccessPath;
 import org.apache.doris.thrift.TSlotDescriptor;
 
@@ -203,6 +204,11 @@ public class SlotDescriptor {
         // Non-nullable slots will have 0 for the byte offset and -1 for the 
bit mask
         String colName = materializedColumnName != null ? 
materializedColumnName :
                                      ((column != null) ? 
column.getNonShadowName() : "");
+        // Physical scan fallback columns are selected after the logical 
expression type checks.
+        if (type.typeContainsUnsupported()) {
+            throw new AnalysisException("Cannot serialize slot " + id + " 
(column '" + colName
+                    + "') with unsupported type " + type.toSql());
+        }
         TSlotDescriptor tSlotDescriptor = new TSlotDescriptor(id.asInt(), 
parent.getId().asInt(), type.toThrift(), -1,
                 0, 0, getIsNullable() ? 0 : -1, colName, -1,
                 true);
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
index 527442b6363..1dd2c16fe05 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/glue/translator/PhysicalPlanTranslator.java
@@ -3119,6 +3119,13 @@ public class PhysicalPlanTranslator extends 
DefaultPlanVisitor<PlanFragment, Pla
         SlotDescriptor smallest = 
getSmallestSlot(scanNode.getTupleDesc().getSlots());
         scanNode.getTupleDesc().getSlots().removeIf(s -> 
!requiredWithVirtualColumns.contains(s.getId()));
         if (scanNode.getTupleDesc().getSlots().isEmpty()) {
+            // COUNT(*) hides source types from expression checks, but BE 
still constructs this scan slot.
+            if (smallest == null) {
+                TableIf table = scanNode.getTupleDesc().getTable();
+                throw new AnalysisException("No supported columns available to 
scan "
+                        + (table == null ? "tuple " + 
scanNode.getTupleDesc().getId()
+                                : "table '" + table.getName() + "'"));
+            }
             scanNode.getTupleDesc().getSlots().add(smallest);
         }
         if (context.getSessionVariable() != null
@@ -3135,10 +3142,10 @@ public class PhysicalPlanTranslator extends 
DefaultPlanVisitor<PlanFragment, Pla
     }
 
     /**
-     * Get the smallest slot in the slot list.
+     * Get the smallest slot whose type has no unsupported fields.
      *
      * @param slots slot list
-     * @return the smallest slot
+     * @return the smallest eligible slot, or null if none is available
      */
     @VisibleForTesting
     @Nullable
@@ -3146,7 +3153,11 @@ public class PhysicalPlanTranslator extends 
DefaultPlanVisitor<PlanFragment, Pla
         if (slots == null || slots.isEmpty()) {
             return null;
         }
-        return Collections.min(slots, new SlotSizeComparator());
+        // Scan tuples still expose unused schema columns after logical 
expression validation.
+        return slots.stream()
+                .filter(slot -> !slot.getType().typeContainsUnsupported())
+                .min(new SlotSizeComparator())
+                .orElse(null);
     }
 
     /**
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
index 4bfa8fb954a..788bca0444a 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckDataTypes.java
@@ -21,8 +21,10 @@ import org.apache.doris.nereids.exceptions.AnalysisException;
 import org.apache.doris.nereids.exceptions.UnboundException;
 import org.apache.doris.nereids.jobs.JobContext;
 import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
 import 
org.apache.doris.nereids.trees.expressions.visitor.DefaultExpressionVisitor;
 import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCatalogRelation;
 import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
 import org.apache.doris.nereids.trees.plans.visitor.CustomRewriter;
 import org.apache.doris.nereids.types.ArrayType;
@@ -52,6 +54,15 @@ public class CheckDataTypes implements CustomRewriter {
     }
 
     private void checkPlan(Plan plan) {
+        if (plan instanceof LogicalCatalogRelation) {
+            List<Slot> output = plan.getOutput();
+            // COUNT(*) leaves no scan expressions, but a surviving scan still 
needs a readable column.
+            if (!output.isEmpty() && output.stream()
+                    .allMatch(slot -> 
slot.getDataType().typeContainsUnsupported())) {
+                throw new AnalysisException("No supported columns available to 
scan table '"
+                        + ((LogicalCatalogRelation) plan).getTable().getName() 
+ "'");
+            }
+        }
         if (plan instanceof LogicalJoin) {
             checkLogicalJoin((LogicalJoin<? extends Plan, ? extends Plan>) 
plan);
         }
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckPrivileges.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckPrivileges.java
index bce4862aeac..60673fc9dd4 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckPrivileges.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/CheckPrivileges.java
@@ -63,6 +63,11 @@ public class CheckPrivileges extends ColumnPruning {
     private JobContext jobContext;
     private final Set<CTEId> checkedCteIds = new HashSet<>();
 
+    public CheckPrivileges() {
+        // Authorization precedes scan elimination and must preserve its 
historical column requirements.
+        super(false);
+    }
+
     @Override
     public Plan rewriteRoot(Plan plan, JobContext jobContext) {
         StatementContext stmtCtx = 
jobContext.getCascadesContext().getStatementContext();
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/ColumnPruning.java
 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/ColumnPruning.java
index 4597e3d2707..12b083731fd 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/ColumnPruning.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/rewrite/ColumnPruning.java
@@ -94,9 +94,18 @@ import java.util.function.Function;
  *                                                              plan
  */
 public class ColumnPruning extends DefaultPlanRewriter<PruneContext> 
implements CustomRewriter {
+    private final boolean requireSupportedFallback;
     private Set<Slot> keys;
     private JobContext jobContext;
 
+    public ColumnPruning() {
+        this(true);
+    }
+
+    protected ColumnPruning(boolean requireSupportedFallback) {
+        this.requireSupportedFallback = requireSupportedFallback;
+    }
+
     /**
      * collect all columns used in expressions, which should not be pruned
      * the purpose to collect keys are:
@@ -372,12 +381,14 @@ public class ColumnPruning extends 
DefaultPlanRewriter<PruneContext> implements
                 );
 
         if (prunedOutputs.isEmpty()) {
-            List<NamedExpression> candidates = 
Lists.newArrayList(originOutput);
-            candidates.retainAll(keys);
+            // Discarded expressions can leave unreadable keys that must not 
hide readable non-key outputs.
+            List<NamedExpression> candidates = 
Utils.filterImmutableList(originOutput,
+                    output -> keys.contains(output)
+                            && (!requireSupportedFallback || 
!output.getDataType().typeContainsUnsupported()));
             if (candidates.isEmpty()) {
                 candidates = originOutput;
             }
-            NamedExpression minimumColumn = 
ExpressionUtils.selectMinimumColumn(candidates);
+            NamedExpression minimumColumn = 
ExpressionUtils.selectMinimumColumn(candidates, requireSupportedFallback);
             prunedOutputs = ImmutableList.of(minimumColumn);
         }
 
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/DataType.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/DataType.java
index 066e7154bcf..1a3f5bee0a4 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/types/DataType.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/types/DataType.java
@@ -739,6 +739,22 @@ public abstract class DataType {
         return this instanceof VariantType;
     }
 
+    /** Inspect logical types without allocating an equivalent catalog type 
tree. */
+    public boolean typeContainsUnsupported() {
+        if (this instanceof ArrayType) {
+            return ((ArrayType) this).getItemType().typeContainsUnsupported();
+        } else if (this instanceof MapType) {
+            return ((MapType) this).getKeyType().typeContainsUnsupported()
+                    || ((MapType) 
this).getValueType().typeContainsUnsupported();
+        } else if (this instanceof StructType) {
+            return ((StructType) this).getFields().stream()
+                    .anyMatch(field -> 
field.getDataType().typeContainsUnsupported());
+        } else if (this instanceof AggStateType) {
+            return ((AggStateType) 
this).getSubTypes().stream().anyMatch(DataType::typeContainsUnsupported);
+        }
+        return this instanceof UnsupportedType;
+    }
+
     /** Inspect logical types, including unresolved signature placeholders, 
for a FILE leaf. */
     public boolean typeContainsFile() {
         if (this instanceof ArrayType) {
diff --git 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
index b0ec38b99dd..68554b50a20 100644
--- 
a/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
+++ 
b/fe/fe-core/src/main/java/org/apache/doris/nereids/util/ExpressionUtils.java
@@ -482,9 +482,20 @@ public class ExpressionUtils {
      * Choose the minimum slot from input parameter.
      */
     public static <S extends NamedExpression> S 
selectMinimumColumn(Collection<S> slots) {
+        return selectMinimumColumn(slots, true);
+    }
+
+    /** Choose a fallback while optionally retaining the historical 
authorization policy. */
+    public static <S extends NamedExpression> S 
selectMinimumColumn(Collection<S> slots,
+            boolean requireSupportedFallback) {
         Preconditions.checkArgument(!slots.isEmpty());
         S minSlot = null;
         for (S slot : slots) {
+            // Positive-width composite or computed outputs may still require 
UNSUPPORTED inputs.
+            if (requireSupportedFallback && slot.anyMatch(expression ->
+                    ((Expression) 
expression).getDataType().typeContainsUnsupported())) {
+                continue;
+            }
             if (minSlot == null) {
                 minSlot = slot;
             } else {
@@ -496,7 +507,8 @@ public class ExpressionUtils {
                         || minSlot.getDataType().width() <= 0 ? slot : minSlot;
             }
         }
-        return minSlot;
+        // Keep an output for row cardinality; the type check rejects it if no 
readable output exists.
+        return minSlot != null ? minSlot : slots.iterator().next();
     }
 
     /**
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/glue/translator/ScanSlotTypeValidationTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/glue/translator/ScanSlotTypeValidationTest.java
new file mode 100644
index 00000000000..6ec7021eebd
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/glue/translator/ScanSlotTypeValidationTest.java
@@ -0,0 +1,118 @@
+// 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.nereids.glue.translator;
+
+import org.apache.doris.analysis.DescriptorTable;
+import org.apache.doris.analysis.SlotDescriptor;
+import org.apache.doris.analysis.SlotId;
+import org.apache.doris.analysis.TupleDescriptor;
+import org.apache.doris.analysis.TupleId;
+import org.apache.doris.catalog.AggStateType;
+import org.apache.doris.catalog.ArrayType;
+import org.apache.doris.catalog.Column;
+import org.apache.doris.catalog.MapType;
+import org.apache.doris.catalog.StructField;
+import org.apache.doris.catalog.StructType;
+import org.apache.doris.catalog.Type;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+public class ScanSlotTypeValidationTest {
+    private SlotDescriptor slot(int id, Type type) {
+        SlotDescriptor slot = new SlotDescriptor(new SlotId(id), new 
TupleDescriptor(new TupleId(0)));
+        slot.setColumn(new Column("column_" + id, type));
+        return slot;
+    }
+
+    private List<Type> unsupportedTypes() {
+        return Arrays.asList(Type.UNSUPPORTED,
+                new ArrayType(Type.UNSUPPORTED),
+                new MapType(Type.INT, Type.UNSUPPORTED),
+                new MapType(Type.UNSUPPORTED, Type.STRING),
+                new StructType(new StructField("nested", Type.UNSUPPORTED)),
+                new ArrayType(new MapType(Type.STRING, new 
ArrayType(Type.UNSUPPORTED))),
+                new AggStateType("sum", true, 
Collections.singletonList(Type.UNSUPPORTED),
+                        Collections.singletonList(true)));
+    }
+
+    @Test
+    public void testNoUnsupportedFallbackColumn() {
+        for (Type type : unsupportedTypes()) {
+            Assertions.assertNull(PhysicalPlanTranslator.getSmallestSlot(
+                    Collections.singletonList(slot(1, type))), type.toSql());
+        }
+    }
+
+    @Test
+    public void testSupportedColumnSurvivesMixedSchema() {
+        for (Type type : unsupportedTypes()) {
+            SlotDescriptor supported = slot(2, Type.VARIANT);
+            Assertions.assertSame(supported, 
PhysicalPlanTranslator.getSmallestSlot(
+                    Arrays.asList(slot(1, type), supported)), type.toSql());
+        }
+    }
+
+    @Test
+    public void testSupportedFallbackOrderingIsUnchanged() {
+        SlotDescriptor integer = slot(3, Type.INT);
+        Assertions.assertSame(integer, PhysicalPlanTranslator.getSmallestSlot(
+                Arrays.asList(slot(1, Type.STRING), slot(2, Type.BIGINT), 
integer)));
+        
Assertions.assertNull(PhysicalPlanTranslator.getSmallestSlot(Collections.emptyList()));
+    }
+
+    @Test
+    public void testNullNestedTypesAreNotUnsupported() {
+        for (Type type : Arrays.asList(Type.NULL, new ArrayType(Type.NULL),
+                new MapType(Type.NULL, Type.NULL))) {
+            SlotDescriptor supported = slot(1, type);
+            Assertions.assertSame(supported, 
PhysicalPlanTranslator.getSmallestSlot(
+                    Collections.singletonList(supported)));
+        }
+    }
+
+    @Test
+    public void testRejectUnsupportedSerializedSlot() {
+        for (Type type : unsupportedTypes()) {
+            DescriptorTable table = new DescriptorTable();
+            TupleDescriptor tuple = table.createTupleDescriptor();
+            table.addSlotDescriptor(tuple).setColumn(new 
Column("unsupported_column", type));
+            AnalysisException exception = 
Assertions.assertThrows(AnalysisException.class,
+                    () -> table.toThrift(), type.toSql());
+            
Assertions.assertTrue(exception.getMessage().contains("unsupported_column"));
+            
Assertions.assertTrue(exception.getMessage().contains("UNSUPPORTED"));
+        }
+    }
+
+    @Test
+    public void testPrunedUnsupportedSlotDoesNotBlockSerialization() {
+        DescriptorTable table = new DescriptorTable();
+        TupleDescriptor tuple = table.createTupleDescriptor();
+        SlotDescriptor unused = table.addSlotDescriptor(tuple);
+        unused.setColumn(new Column("unused_column", Type.UNSUPPORTED));
+        SlotDescriptor supported = table.addSlotDescriptor(tuple);
+        supported.setColumn(new Column("supported_column", Type.INT));
+        tuple.getSlots().remove(unused);
+        Assertions.assertEquals(1, table.toThrift().getSlotDescriptorsSize());
+    }
+}
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/privileges/TestCheckPrivileges.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/privileges/TestCheckPrivileges.java
index e8c1733b1d6..de6caacb36d 100644
--- 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/privileges/TestCheckPrivileges.java
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/privileges/TestCheckPrivileges.java
@@ -19,9 +19,11 @@ package org.apache.doris.nereids.privileges;
 
 import org.apache.doris.analysis.ResourceTypeEnum;
 import org.apache.doris.analysis.UserIdentity;
+import org.apache.doris.catalog.ArrayType;
 import org.apache.doris.catalog.Column;
 import org.apache.doris.catalog.Env;
 import org.apache.doris.catalog.PrimitiveType;
+import org.apache.doris.catalog.Type;
 import org.apache.doris.common.AuthorizationException;
 import org.apache.doris.common.DdlException;
 import org.apache.doris.common.FeConstants;
@@ -81,6 +83,10 @@ public class TestCheckPrivileges extends TestWithFeService 
implements GeneratedM
                     "test_tbl4", ImmutableList.of(
                             new Column("id", PrimitiveType.INT),
                             new Column("name", PrimitiveType.VARCHAR)
+                    ),
+                    "fallback_types", ImmutableList.of(
+                            new Column("unsupported_value", Type.UNSUPPORTED),
+                            new Column("supported_values", 
ArrayType.create(Type.INT, true))
                     )
             )
     );
@@ -141,6 +147,15 @@ public class TestCheckPrivileges extends TestWithFeService 
implements GeneratedM
             }
         };
 
+        withPrivileges(ImmutableList.of(MakePrivileges.table(catalog, db, 
"fallback_types")
+                .allowSelectColumns(user, 
ImmutableSet.of("unsupported_value"))), () -> {
+                // Authorization precedes scan elimination and must keep its 
existing column requirements.
+                query("SELECT COUNT(*) FROM (SELECT unsupported_value, 
supported_values, "
+                        + "unsupported_value AS unused FROM 
custom_catalog.test_db.fallback_types LIMIT 0) q");
+                AnalysisException error = 
Assertions.assertThrows(AnalysisException.class, () ->
+                        query("SELECT supported_values FROM 
custom_catalog.test_db.fallback_types LIMIT 0"));
+                Assertions.assertTrue(error.getMessage().contains("denied"), 
error.getMessage());
+            });
         withPrivileges(privileges, () -> {
                 // test base table
                 {
diff --git 
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/UnsupportedScanPruningTest.java
 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/UnsupportedScanPruningTest.java
new file mode 100644
index 00000000000..15a5861c731
--- /dev/null
+++ 
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/UnsupportedScanPruningTest.java
@@ -0,0 +1,170 @@
+// 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.nereids.rules.rewrite;
+
+import org.apache.doris.datasource.ExternalTable;
+import org.apache.doris.nereids.exceptions.AnalysisException;
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.IsNull;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
+import org.apache.doris.nereids.trees.expressions.functions.agg.Count;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFileScan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalProject;
+import org.apache.doris.nereids.types.AggStateType;
+import org.apache.doris.nereids.types.ArrayType;
+import org.apache.doris.nereids.types.DataType;
+import org.apache.doris.nereids.types.IntegerType;
+import org.apache.doris.nereids.types.MapType;
+import org.apache.doris.nereids.types.NullType;
+import org.apache.doris.nereids.types.StructField;
+import org.apache.doris.nereids.types.StructType;
+import org.apache.doris.nereids.types.UnsupportedType;
+import org.apache.doris.nereids.util.ExpressionUtils;
+import org.apache.doris.nereids.util.MemoTestUtils;
+import org.apache.doris.nereids.util.PlanChecker;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+public class UnsupportedScanPruningTest {
+    private List<DataType> unsupportedTypes() {
+        return ImmutableList.of(UnsupportedType.INSTANCE,
+                ArrayType.of(UnsupportedType.INSTANCE),
+                MapType.of(IntegerType.INSTANCE, UnsupportedType.INSTANCE),
+                MapType.of(UnsupportedType.INSTANCE, IntegerType.INSTANCE),
+                new StructType(ImmutableList.of(new StructField("nested", 
UnsupportedType.INSTANCE, true, ""))),
+                ArrayType.of(MapType.of(IntegerType.INSTANCE, 
UnsupportedType.INSTANCE)),
+                new AggStateType("sum", 
ImmutableList.of(UnsupportedType.INSTANCE), ImmutableList.of(true)));
+    }
+
+    private LogicalFileScan scan(List<Slot> slots) {
+        ExternalTable table = Mockito.mock(ExternalTable.class);
+        Mockito.when(table.getName()).thenReturn("scan_types");
+        return new LogicalFileScan(StatementScopeIdGenerator.newRelationId(), 
table,
+                ImmutableList.of("catalog", "db"), ImmutableList.of(), 
Optional.empty(), Optional.empty(),
+                Optional.empty(), Optional.of(slots));
+    }
+
+    @Test
+    public void minimumColumnSkipsUnsupportedNestedTypes() {
+        SlotReference supported = new SlotReference("supported", 
ArrayType.of(IntegerType.INSTANCE));
+        for (DataType type : unsupportedTypes()) {
+            SlotReference unsupported = new SlotReference("unsupported", type);
+            Assertions.assertSame(supported,
+                    
ExpressionUtils.selectMinimumColumn(ImmutableList.of(unsupported, supported)),
+                    type.toSql());
+            Assertions.assertSame(supported,
+                    
ExpressionUtils.selectMinimumColumn(ImmutableList.of(supported, unsupported)),
+                    type.toSql());
+        }
+    }
+
+    @Test
+    public void minimumColumnSkipsExpressionsWithUnsupportedInput() {
+        SlotReference unsupported = new SlotReference("unsupported", 
UnsupportedType.INSTANCE);
+        Alias unused = new Alias(new IsNull(unsupported), "unused");
+        SlotReference supported = new SlotReference("supported", 
ArrayType.of(IntegerType.INSTANCE));
+        Assertions.assertSame(supported, 
ExpressionUtils.selectMinimumColumn(ImmutableList.of(unused, supported)));
+    }
+
+    @Test
+    public void columnPruningIgnoresDiscardedUnsupportedKeys() {
+        SlotReference unsupported = new SlotReference("unsupported", 
ArrayType.of(UnsupportedType.INSTANCE));
+        SlotReference supported = new SlotReference("supported", 
ArrayType.of(IntegerType.INSTANCE));
+        for (Alias unused : ImmutableList.of(new Alias(unsupported, "unused"),
+                new Alias(new IsNull(unsupported), "unused"))) {
+            LogicalFileScan relation = scan(ImmutableList.of(unsupported, 
supported));
+            LogicalProject<LogicalFileScan> project = new LogicalProject<>(
+                    ImmutableList.of(unsupported, supported, unused), 
relation);
+            LogicalAggregate<?> count = new 
LogicalAggregate<>(ImmutableList.of(),
+                    ImmutableList.of(new Alias(new Count())), project);
+            Plan pruned = 
PlanChecker.from(MemoTestUtils.createConnectContext(), count)
+                    .customRewrite(new ColumnPruning()).getPlan();
+            Assertions.assertDoesNotThrow(() -> new 
CheckDataTypes().rewriteRoot(pruned, null));
+        }
+    }
+
+    @Test
+    public void minimumColumnKeepsAnOutputWhenEveryTypeIsUnsupported() {
+        List<SlotReference> slots = unsupportedTypes().stream()
+                .map(type -> new SlotReference("unsupported", 
type)).collect(Collectors.toList());
+        
Assertions.assertTrue(slots.contains(ExpressionUtils.selectMinimumColumn(slots)));
+    }
+
+    @Test
+    public void minimumColumnPreservesNullTypes() {
+        for (DataType type : ImmutableList.of(NullType.INSTANCE, 
ArrayType.of(NullType.INSTANCE),
+                MapType.of(NullType.INSTANCE, NullType.INSTANCE))) {
+            SlotReference slot = new SlotReference("literal", type);
+            Assertions.assertSame(slot, 
ExpressionUtils.selectMinimumColumn(ImmutableList.of(slot)), type.toSql());
+        }
+    }
+
+    @Test
+    public void rejectsAllUnsupportedCatalogScansBeforeTranslation() {
+        for (DataType type : unsupportedTypes()) {
+            LogicalFileScan relation = scan(ImmutableList.of(new 
SlotReference("unsupported", type)));
+            Plan plan = new LogicalProject<>(ImmutableList.of(), relation);
+            AnalysisException error = 
Assertions.assertThrows(AnalysisException.class,
+                    () -> new CheckDataTypes().rewriteRoot(plan, null), 
type.toSql());
+            Assertions.assertTrue(error.getMessage().contains("No supported 
columns"), error.getMessage());
+            Assertions.assertTrue(error.getMessage().contains("scan_types"), 
error.getMessage());
+        }
+    }
+
+    @Test
+    public void mixedCatalogScanRetainsItsFullSchemaAfterTypeChecking() {
+        SlotReference unsupported = new SlotReference("unsupported", 
UnsupportedType.INSTANCE);
+        SlotReference supported = new SlotReference("supported", 
IntegerType.INSTANCE);
+        LogicalFileScan relation = scan(ImmutableList.of(unsupported, 
supported));
+        Plan plan = new LogicalProject<>(ImmutableList.of(supported), 
relation);
+        Assertions.assertSame(plan, new CheckDataTypes().rewriteRoot(plan, 
null));
+        Assertions.assertEquals(ImmutableList.of(unsupported, supported), 
relation.getOutput());
+    }
+
+    @Test
+    public void emptyCatalogOutputIsNotClassifiedAsUnsupported() {
+        LogicalFileScan relation = scan(ImmutableList.of());
+        Assertions.assertSame(relation, new 
CheckDataTypes().rewriteRoot(relation, null));
+    }
+
+    @Test
+    public void columnPruningKeepsAReadableSubqueryOutputForCount() {
+        for (DataType type : unsupportedTypes()) {
+            SlotReference unsupported = new SlotReference("unsupported", type);
+            SlotReference supported = new SlotReference("supported", 
ArrayType.of(IntegerType.INSTANCE));
+            LogicalFileScan relation = scan(ImmutableList.of(unsupported, 
supported));
+            LogicalProject<LogicalFileScan> project = new 
LogicalProject<>(ImmutableList.of(unsupported, supported), relation);
+            LogicalAggregate<?> count = new 
LogicalAggregate<>(ImmutableList.of(),
+                    ImmutableList.of(new Alias(new Count())), project);
+            Plan pruned = 
PlanChecker.from(MemoTestUtils.createConnectContext(), count)
+                    .customRewrite(new ColumnPruning()).getPlan();
+            Assertions.assertDoesNotThrow(() -> new 
CheckDataTypes().rewriteRoot(pruned, null), type.toSql());
+        }
+    }
+}
diff --git 
a/regression-test/data/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.out
 
b/regression-test/data/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.out
new file mode 100644
index 00000000000..2a78b885402
--- /dev/null
+++ 
b/regression-test/data/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.out
@@ -0,0 +1,45 @@
+-- This file is automatically generated. You should know what you did if you 
want to edit this
+-- !mixed_projection --
+1      value
+2      \N
+
+-- !mixed_count --
+2
+
+-- !mixed_count_one --
+2
+
+-- !mixed_constant --
+1
+1
+
+-- !mixed_filter --
+2
+
+-- !source_cast_view --
+1      first
+2      second
+
+-- !mixed_subquery_count --
+1
+
+-- !mixed_subquery_unused_alias_count --
+1
+
+-- !mixed_subquery_unused_expression_count --
+1
+
+-- !array_fallback_count --
+2
+
+-- !unsupported_empty_filter --
+0
+
+-- !unsupported_limit_zero --
+
+-- !column_privilege_empty_count --
+0
+
+-- !query_after_rejection --
+2
+
diff --git 
a/regression-test/suites/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.groovy
 
b/regression-test/suites/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.groovy
new file mode 100644
index 00000000000..df1e31b1f05
--- /dev/null
+++ 
b/regression-test/suites/external_table_p0/jdbc/test_pg_jdbc_unsupported_scan_types.groovy
@@ -0,0 +1,160 @@
+// 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 java.sql.DriverManager
+
+suite("test_pg_jdbc_unsupported_scan_types", "p0,external") {
+    String enabled = context.config.otherConfigs.get("enableJdbcTest")
+    if (enabled == null || !enabled.equalsIgnoreCase("true")) {
+        return
+    }
+
+    String host = context.config.otherConfigs.get("externalEnvIp")
+    String port = context.config.otherConfigs.get("pg_14_port")
+    String user = context.config.otherConfigs.get("pgUser", "postgres")
+    String password = context.config.otherConfigs.get("pgPassword", "123456")
+    String jdbcUrl = "jdbc:postgresql://${host}:${port}/postgres?useSSL=false"
+    String driverUrl = context.config.otherConfigs.get("pgDriverUrl",
+        
"https://${getS3BucketName()}.${getS3Endpoint()}/regression/jdbc_driver/postgresql-42.5.0.jar")
+
+    Class.forName("org.postgresql.Driver")
+    def connection = DriverManager.getConnection(jdbcUrl, user, password)
+    try {
+        def statement = connection.createStatement()
+        try {
+            statement.execute("DROP SCHEMA IF EXISTS unsupported_scan_test 
CASCADE")
+            statement.execute("CREATE SCHEMA unsupported_scan_test")
+            // PostgreSQL built-in types reproduce the unsupported mapping 
without an extension.
+            statement.execute("""CREATE TABLE 
unsupported_scan_test.unsupported_only (
+                unsupported_oid oid, unsupported_name name, 
unsupported_namespace regnamespace)""")
+            statement.execute("""INSERT INTO 
unsupported_scan_test.unsupported_only VALUES
+                (1, 'first', 'pg_catalog'::regnamespace), (2, 'second', 
'pg_catalog'::regnamespace)""")
+            statement.execute("""CREATE TABLE 
unsupported_scan_test.mixed_types (
+                unsupported_name name, supported_id integer, supported_text 
text)""")
+            statement.execute("""INSERT INTO unsupported_scan_test.mixed_types 
VALUES
+                ('first', 1, 'value'), ('second', 2, NULL)""")
+            statement.execute("""CREATE TABLE 
unsupported_scan_test.wide_fallback_types (
+                unsupported_value oid, supported_values integer[])""")
+            statement.execute("""INSERT INTO 
unsupported_scan_test.wide_fallback_types VALUES
+                (1, ARRAY[10, 20]), (2, ARRAY[30])""")
+            statement.execute("""CREATE VIEW 
unsupported_scan_test.compatible_view AS
+                SELECT unsupported_oid::bigint AS object_id, 
unsupported_name::text AS object_name
+                FROM unsupported_scan_test.unsupported_only""")
+        } finally {
+            statement.close()
+        }
+    } finally {
+        connection.close()
+    }
+
+    sql "DROP CATALOG IF EXISTS pg_unsupported_scan_catalog"
+    sql """CREATE CATALOG pg_unsupported_scan_catalog PROPERTIES (
+        "type" = "jdbc",
+        "user" = "${user}",
+        "password" = "${password}",
+        "jdbc_url" = "${jdbcUrl}&currentSchema=unsupported_scan_test",
+        "driver_url" = "${driverUrl}",
+        "driver_class" = "org.postgresql.Driver"
+    )"""
+
+    // These queries reference no source columns, but the scan still needs a 
fallback slot.
+    [
+        "SELECT COUNT(*) FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only",
+        "SELECT COUNT(1) FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only",
+        "SELECT 1 FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only LIMIT 1"
+    ].each { query ->
+        test {
+            sql query
+            exception "No supported columns"
+        }
+    }
+
+    test {
+        sql """SELECT unsupported_oid
+            FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only LIMIT 1"""
+        exception "UNSUPPORTED"
+    }
+    test {
+        sql """SELECT unsupported_name
+            FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types 
LIMIT 1"""
+        exception "UNSUPPORTED"
+    }
+
+    // A pruned unsupported column must not reject a supported projection or 
row count.
+    order_qt_mixed_projection """SELECT supported_id, supported_text
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types 
ORDER BY supported_id"""
+    order_qt_mixed_count """SELECT COUNT(*)
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types"""
+    order_qt_mixed_count_one """SELECT COUNT(1)
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types"""
+    order_qt_mixed_constant """SELECT 1
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types"""
+    order_qt_mixed_filter """SELECT supported_id
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types
+        WHERE supported_id > 1 ORDER BY supported_id"""
+    order_qt_source_cast_view """SELECT object_id, object_name
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.compatible_view 
ORDER BY object_id"""
+    // LIMIT keeps the subquery projection separate so logical pruning must 
choose its fallback.
+    order_qt_mixed_subquery_count """SELECT COUNT(*) FROM (
+        SELECT unsupported_value, supported_values
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types LIMIT 1) 
subquery_rows"""
+    order_qt_mixed_subquery_unused_alias_count """SELECT COUNT(*) FROM (
+        SELECT unsupported_value, supported_values, unsupported_value AS unused
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types LIMIT 1) 
subquery_rows"""
+    order_qt_mixed_subquery_unused_expression_count """SELECT COUNT(*) FROM (
+        SELECT unsupported_value, supported_values, unsupported_value IS NULL 
AS unused
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types LIMIT 1) 
subquery_rows"""
+    order_qt_array_fallback_count """SELECT COUNT(*)
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types"""
+    // An eliminated scan needs no readable column and must remain legal.
+    order_qt_unsupported_empty_filter """SELECT COUNT(*)
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only WHERE 1 = 
0"""
+    order_qt_unsupported_limit_zero """SELECT 1
+        FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.unsupported_only LIMIT 0"""
+    String privilegeUser = "unsupported_scan_privilege_user"
+    sql "DROP USER IF EXISTS ${privilegeUser}"
+    sql "CREATE USER ${privilegeUser}"
+    try {
+        sql """GRANT SELECT_PRIV(unsupported_value)
+            ON 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types TO 
${privilegeUser}"""
+        if (isCloudMode()) {
+            def clusters = sql "SHOW CLUSTERS"
+            assertTrue(!clusters.isEmpty())
+            sql "GRANT USAGE_PRIV ON CLUSTER `${clusters[0][0]}` TO 
${privilegeUser}"
+        }
+        def dorisJdbcUri = new 
URI(context.config.jdbcUrl.substring("jdbc:".length()))
+        String privilegeJdbcUrl = "jdbc:mysql://${dorisJdbcUri.rawAuthority}/"
+        if (dorisJdbcUri.rawQuery != null) {
+            privilegeJdbcUrl += "?${dorisJdbcUri.rawQuery}"
+        }
+        connectToDoris(privilegeUser, "", privilegeJdbcUrl) {
+            // A discarded execution fallback must not add a new authorization 
requirement.
+            order_qt_column_privilege_empty_count """SELECT COUNT(*) FROM (
+                SELECT unsupported_value, supported_values, unsupported_value 
AS unused
+                FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types LIMIT 0) 
subquery_rows"""
+            test {
+                sql """SELECT supported_values
+                    FROM 
pg_unsupported_scan_catalog.unsupported_scan_test.wide_fallback_types LIMIT 0"""
+                exception "denied"
+            }
+        }
+    } finally {
+        sql "DROP USER IF EXISTS ${privilegeUser}"
+    }
+    order_qt_query_after_rejection """SELECT COUNT(*)
+        FROM pg_unsupported_scan_catalog.unsupported_scan_test.mixed_types"""
+}


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

Reply via email to