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 d026e254d0a [fix](jdbc) Reject unsupported scan column types before
execution (#71242)
d026e254d0a is described below
commit d026e254d0a24af87390a1d7bdf0dbdf931d5193
Author: Gabriel <[email protected]>
AuthorDate: Thu Dec 3 09:47:25 2026 +0800
[fix](jdbc) Reject unsupported scan column types before execution (#71242)
### Background
JDBC catalogs expose external schemas that can include types Doris
cannot read. Queries such as `COUNT(*)` reference no source column, but
a surviving scan still needs one column to preserve row counts. Logical
column pruning and physical scan translation both select such fallback
columns.
### What problem does this PR solve?
Issue Number: None
Related PR: #41548 (introduced the constant-projection path), #71243
(original scan guards on branch-4.2)
PR Type: Bugfix
Problem Summary:
`COUNT(*)` over an unsupported-only PostgreSQL table can send
`UNSUPPORTED` metadata to BE and abort it during descriptor
construction. Reject those scans during logical validation, select
readable fallback columns in both planning paths, and retain FE
serialization and BE ingestion guards. Mixed schemas remain usable even
when discarded subquery outputs contain unsupported types. Most changed
lines add tests, including column-level authorization checks.
### Details
- **Change map:** 122 production lines (+115/-7), 558 test lines, and 45
generated result lines across 15 files. Most lines are tests. Read FE
logical validation, fallback selection and authorization compatibility
first, then physical fallback/serialization (104 FE lines total),
followed by BE descriptor validation (18 lines).
- **Frequency:** Always for a surviving column-free scan over an
unsupported-only schema; PostgreSQL built-in `oid`, `name`, and
`regnamespace` reproduce the original crash. Nested fallback selection
failures were reproduced with logical-plan tests.
- **Root cause:** Constant projections hide source columns from
expression validation. Width-based fallback selection can choose
unsupported nested types or inputs, and discarded expressions can make
an unreadable key hide readable alternatives.
- **Why existing tests missed it:** `CountStarSmallestSlotTest` and
`SlotDescriptorTest` cover valid metadata; existing column-pruning and
privilege tests lack unsupported fallback inputs. PostgreSQL
catalog/type suites cover readable types and arrays containing NULL,
without unsupported-only counts or column-restricted empty subqueries.
- **Fix:** Check surviving catalog outputs, exclude recursively
unsupported executable fallback candidates, validate serialized slots,
and reject unsupported BE descriptors before datatype construction.
Preserve a non-null fallback until later validation and keep the
historical authorization selection policy, because privilege checks
precede scan elimination. Legitimate NULL types remain accepted.
- **Other paths and branches:** Shared planning and descriptor checks
cover other external scans and older-FE requests in both deployment
modes. The original guards have companion PR #71243 for `branch-4.2`;
this review follow-up updates master only. `branch-4.1` shares the
original path and is not fixed here; other release branches were not
checked.
- **Behavior change:** Unsupported-only scans report an error instead of
crashing BE. Supported candidates retain their width ordering;
permissions retain their existing column requirements. No protocol or
configuration changes.
### Testing
- Locally passed 57 FE tests, including nine new logical fallback tests,
scan-slot validation, COUNT(*) ordering, column pruning, expression
utilities, and the extended real-SQL privilege fixture. Targeted logical
tests failed before the fallback fixes.
- A non-root PostgreSQL regression reproduced the review follow-up's
extra permission denial before separating authorization from executable
pruning; the final suite passes the allowed query and still rejects an
unauthorized projection.
- PostgreSQL 15 suite `test_pg_jdbc_unsupported_scan_types`: 20 query
expectations; actual result generation and comparison both passed
without skips. Also covers supported projections, subquery aliases,
source casts, eliminated scans, and queries after rejection.
- The unfixed BE baseline aborted during datatype construction; the
guarded candidate passed 16 descriptor tests under ASAN at `8f5b7d5`. No
BE code changed in this follow-up.
### Notes for Reviewers
- Keep the translator filter: scan tuples still expose unused schema
columns after logical expression checks. Rejecting all-unsupported scans
earlier does not remove unsupported columns from mixed schemas.
- Nested unsupported types have logical-plan unit coverage; the
PostgreSQL subquery cases check compatibility rather than reproduce
nested unsupported mappings. Local review findings were fixed and
re-reviewed before this update.
### Release note
JDBC queries that retain an unsupported scan column now report a
descriptive error instead of crashing a BE. Queries using supported
columns from mixed schemas continue to work.
### Check List (For Author)
- Behavior changed: Yes (see Details)
- Does this need documentation: No
- Pre-submission status: Ready
### AI Disclosure
- Tool: Codex (GPT-6); GPT-6 Astra for local review.
- Generated: Implementation, tests, and this description.
- Human review: Not stated for this follow-up.
- Prompts: Fix master and branch-4.2 with unit and regression coverage
and resolve local review findings before submission. Then assess the
master PR's review comments and implement necessary changes.
---
be/src/runtime/descriptors.cpp | 18 +++
be/test/runtime/descriptor_test.cpp | 99 +++++++++++++
.../analysis/DescriptorToThriftConverter.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 | 119 +++++++++++++++
.../nereids/privileges/TestCheckPrivileges.java | 15 ++
.../rules/rewrite/UnsupportedScanPruningTest.java | 165 +++++++++++++++++++++
.../main/java/org/apache/doris/catalog/Type.java | 18 +++
.../jdbc/test_pg_jdbc_unsupported_scan_types.out | 45 ++++++
.../test_pg_jdbc_unsupported_scan_types.groovy | 160 ++++++++++++++++++++
15 files changed, 718 insertions(+), 7 deletions(-)
diff --git a/be/src/runtime/descriptors.cpp b/be/src/runtime/descriptors.cpp
index 3bd73392853..509b7227f51 100644
--- a/be/src/runtime/descriptors.cpp
+++ b/be/src/runtime/descriptors.cpp
@@ -512,6 +512,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());
@@ -580,6 +593,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 2c5d528d369..ca45e12cf7e 100644
--- a/be/test/runtime/descriptor_test.cpp
+++ b/be/test/runtime/descriptor_test.cpp
@@ -24,6 +24,7 @@
#include <memory>
#include "common/exception.h"
+#include "common/object_pool.h"
#include "core/assert_cast.h"
#include "core/data_type/data_type_decimal.h"
#include "core/data_type/data_type_nullable.h"
@@ -93,6 +94,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, CanonicalTypesWithoutPostConstructionConversion) {
auto tdesc = create_basic_slot_descriptor();
auto& scalar = tdesc.slotType.types[0].scalar_type;
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/analysis/DescriptorToThriftConverter.java
b/fe/fe-core/src/main/java/org/apache/doris/analysis/DescriptorToThriftConverter.java
index 33c9a6e378a..37bf69977ee 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/analysis/DescriptorToThriftConverter.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/analysis/DescriptorToThriftConverter.java
@@ -19,6 +19,7 @@ package org.apache.doris.analysis;
import org.apache.doris.catalog.Column;
import org.apache.doris.catalog.TableIf;
+import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.thrift.DescriptorsConstants;
import org.apache.doris.thrift.TAccessPathType;
import org.apache.doris.thrift.TColumnAccessPath;
@@ -54,6 +55,11 @@ public final class DescriptorToThriftConverter {
Column column = slotDesc.getColumn();
String colName = materializedColumnName != null ?
materializedColumnName :
((column != null) ?
column.getNonShadowName() : "");
+ // Physical scan fallback columns are selected after the logical
expression type checks.
+ if (slotDesc.getType().typeContainsUnsupported()) {
+ throw new AnalysisException("Cannot serialize slot " +
slotDesc.getId() + " (column '" + colName
+ + "') with unsupported type " +
slotDesc.getType().toSql());
+ }
TSlotDescriptor tSlotDescriptor = new
TSlotDescriptor(slotDesc.getId().asInt(),
slotDesc.getParentId().asInt(), slotDesc.getType().toThrift(),
-1,
0, 0, slotDesc.getIsNullable() ? 0 : -1, colName, -1,
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 87f7f5b2baf..4910df358a8 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
@@ -3061,6 +3061,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
@@ -3296,10 +3303,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
@@ -3307,7 +3314,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 3d2cfa4ef5b..c075b273e00 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
@@ -24,11 +24,13 @@ import org.apache.doris.nereids.jobs.JobContext;
import org.apache.doris.nereids.rules.expression.check.CheckCast;
import org.apache.doris.nereids.trees.expressions.Cast;
import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
import
org.apache.doris.nereids.trees.expressions.functions.AggCombinerFunctionBuilder;
import org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
import org.apache.doris.nereids.trees.expressions.literal.NullLiteral;
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.AggStateType;
@@ -60,6 +62,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 b877d740262..200e6c27687 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
@@ -88,9 +88,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:
@@ -382,12 +391,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 36fa4cc5ece..5d5469318cc 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
@@ -790,6 +790,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 d0e649a90e8..b4a49a0452d 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
@@ -465,9 +465,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 {
@@ -479,7 +490,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..2df01da2b06
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/glue/translator/ScanSlotTypeValidationTest.java
@@ -0,0 +1,119 @@
+// 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.DescriptorToThriftConverter;
+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
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,
+ () -> DescriptorToThriftConverter.toThrift(table),
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,
DescriptorToThriftConverter.toThrift(table).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 56344470523..3b79862a3b0 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
@@ -22,9 +22,11 @@ import org.apache.doris.analysis.UserIdentity;
import org.apache.doris.authorization.DataMaskSpec;
import org.apache.doris.authorization.RowFilterSpec;
import org.apache.doris.authorization.spi.AuthorizationPlugin;
+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;
@@ -80,6 +82,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))
)
)
);
@@ -137,6 +143,15 @@ public class TestCheckPrivileges extends TestWithFeService
implements GeneratedM
.getAccessControllerOrDefault("internal");
Deencapsulation.setField(Env.getCurrentEnv(), "accessManager",
spyAccessManager);
+ 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..647665dbab5
--- /dev/null
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/rewrite/UnsupportedScanPruningTest.java
@@ -0,0 +1,165 @@
+// 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 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 List.of(UnsupportedType.INSTANCE,
+ ArrayType.of(UnsupportedType.INSTANCE),
+ MapType.of(IntegerType.INSTANCE, UnsupportedType.INSTANCE),
+ MapType.of(UnsupportedType.INSTANCE, IntegerType.INSTANCE),
+ new StructType(List.of(new StructField("nested",
UnsupportedType.INSTANCE, true, ""))),
+ ArrayType.of(MapType.of(IntegerType.INSTANCE,
UnsupportedType.INSTANCE)),
+ new AggStateType("sum", List.of(UnsupportedType.INSTANCE),
List.of(true), 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,
+ List.of("catalog", "db"), List.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(List.of(unsupported, supported)),
+ type.toSql());
+ Assertions.assertSame(supported,
ExpressionUtils.selectMinimumColumn(List.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(List.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 : List.of(new Alias(unsupported, "unused"),
+ new Alias(new IsNull(unsupported), "unused"))) {
+ LogicalFileScan relation = scan(List.of(unsupported, supported));
+ LogicalProject<LogicalFileScan> project = new LogicalProject<>(
+ List.of(unsupported, supported, unused), relation);
+ LogicalAggregate<?> count = new LogicalAggregate<>(List.of(),
List.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 : List.of(NullType.INSTANCE,
ArrayType.of(NullType.INSTANCE),
+ MapType.of(NullType.INSTANCE, NullType.INSTANCE))) {
+ SlotReference slot = new SlotReference("literal", type);
+ Assertions.assertSame(slot,
ExpressionUtils.selectMinimumColumn(List.of(slot)), type.toSql());
+ }
+ }
+
+ @Test
+ public void rejectsAllUnsupportedCatalogScansBeforeTranslation() {
+ for (DataType type : unsupportedTypes()) {
+ LogicalFileScan relation = scan(List.of(new
SlotReference("unsupported", type)));
+ Plan plan = new LogicalProject<>(List.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(List.of(unsupported, supported));
+ Plan plan = new LogicalProject<>(List.of(supported), relation);
+ Assertions.assertSame(plan, new CheckDataTypes().rewriteRoot(plan,
null));
+ Assertions.assertEquals(List.of(unsupported, supported),
relation.getOutput());
+ }
+
+ @Test
+ public void emptyCatalogOutputIsNotClassifiedAsUnsupported() {
+ LogicalFileScan relation = scan(List.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(List.of(unsupported, supported));
+ LogicalProject<LogicalFileScan> project = new
LogicalProject<>(List.of(unsupported, supported), relation);
+ LogicalAggregate<?> count = new LogicalAggregate<>(List.of(),
List.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/fe/fe-type/src/main/java/org/apache/doris/catalog/Type.java
b/fe/fe-type/src/main/java/org/apache/doris/catalog/Type.java
index 55a9c7ca378..85b353899a3 100644
--- a/fe/fe-type/src/main/java/org/apache/doris/catalog/Type.java
+++ b/fe/fe-type/src/main/java/org/apache/doris/catalog/Type.java
@@ -452,6 +452,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/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}¤tSchema=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]