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 1d004bd8b22 [fix](iceberg) Fix spatial NULL writes through derived
tables and CTEs (#71224)
1d004bd8b22 is described below
commit 1d004bd8b22d2526de37fb470a410795c8981b59
Author: Gabriel <[email protected]>
AuthorDate: Thu Dec 3 13:58:47 2026 +0800
[fix](iceberg) Fix spatial NULL writes through derived tables and CTEs
(#71224)
### Background
Iceberg V3 spatial columns can appear inside ARRAY, MAP and STRUCT
values. Doris assigns destination spatial types to proven NULL leaves
before binding a connector write. Derived tables and CTE consumers
expose constructed values through slots, with CTEIds identifying their
producers.
### What problem does this PR solve?
Issue Number: None
Related PR: #69032 (introduced the original forwarding bug)
PR Type: Bugfix
Problem Summary:
INSERT SELECT rejects forwarded containers with runtime ordinary fields
and NULL spatial leaves, although the direct constructor succeeds.
Retarget NULL leaves at their producer, preserving ordinary outputs and
shared evaluation. Keep CTE identities across folded names, synchronize
rewritten producers and reuse typed outputs within their projection
scope. Most of the diff is tests.
```sql
INSERT INTO spatial_target(g1, g2)
SELECT s, renamed FROM (
SELECT s, s AS renamed FROM (
SELECT named_struct('k', id, 'shape', CAST(NULL AS INT)) s FROM
source_table
) inner_q
) outer_q;
```
The example previously failed type validation; the unscoped output cache
added during review then caused `IllegalStateException`. It now writes
both spatial targets while retaining ordinary fields.
### Details
- **Change map:** Production +296/-11 lines in three files, tests
+831/-2 lines in five files, and 109 generated result lines.
| Part | Purpose | Changed lines |
| --- | --- | --- |
| Write normalization | Preserve outputs and shared inputs, scope
typed-output reuse, and synchronize anchor registration | 270 |
| CTE bindings | Resolve bound ids through all scopes and refresh the
final producer definition | 37 |
- **Frequency:** Always for forwarded runtime constructors requiring
spatial NULL retagging; modes 1/2 also expose plain WITH name
collisions. Passthrough slots plus same-typed aliases expose the cache
collision.
- **Root cause:** The original normalizer retagged only the outer
projection. Folded names hid earlier CTEIds, anchor registration became
stale, and repeated targets appended redundant outputs. Caching only by
ExprId/type then confused distinct projects that forwarded the same
slot.
- **Why existing tests missed it:**
`ConnectorSpatialWriteNormalizerTest` and `test_iceberg_spatial_v3`
separated direct constructors from constant CTE provenance. Case-mode
tests lacked plain WITH spatial writes; anchor tests lacked
registry/identity assertions. Repeated-target tests used fresh aliases,
missing raw slots retained across project layers.
- **Fix:** Append typed outputs while retaining original outputs and
hoisted runtime inputs. CTEContext retains outward links and lazily
indexes bound CTEIds. Both anchor paths register changed producers and
retain unchanged nodes. Share typed CTE outputs across UNION ALL
branches; scope projection outputs by stable project id, preserving
reuse across rewrites and the scope assertion.
- **Other paths and branches:** GEOMETRY/GEOGRAPHY, nested
ARRAY/MAP/STRUCT and connector INSERT/MERGE share normalization.
Existing proof barriers remain. Freshly checked branch-3.1, branch-4.0,
branch-4.1 and branch-4.2 lack the introducing normalizer; this targets
unreleased master. The cache defect exists only in this PR.
### Testing
- All 145 tests in seven related FE classes pass locally. The two new
passthrough/alias tests fail with `IllegalStateException` before this
revision; they cover both target orders, both spatial kinds and three
projection depths, retaining ordinary outputs and deduplication. The
native review SQL also fails before and plans afterward.
- `test_cte_name_reuse` passes comparison; full
`test_iceberg_spatial_v3` passes generation and comparison using the
current FE package and an ASAN BE. Independent checks validate six new
rows/16 fields, the earlier 36 case-mode rows/27 groups, nested NULL
boundaries and shared volatile evaluation. Previous expected results
remain byte-identical.
- Official FE build and repository FE Checkstyle pass, with zero style
violations.
### Notes for Reviewers
CTE indexes retain binding objects so later sink updates remain visible.
Projection caches use the integer returned by `getId()`, which survives
`withProjectsAndChild`; producer-level CTE reuse remains separate. Full
target types and independent consumer ExprIds are preserved.
### Release note
None
### Check List (For Author)
- Behavior changed: No
- Does this need documentation: No
- Pre-submission status: Ready
### AI Disclosure
- Tool: OpenAI Codex (GPT-6)
- Generated: Code, tests and this description
- Human review: not stated
---
.../converter/ConnectorSpatialWriteNormalizer.java | 270 ++++++++++-
.../java/org/apache/doris/nereids/CTEContext.java | 25 +
.../doris/nereids/rules/analysis/AnalyzeCTE.java | 12 +-
.../ConnectorSpatialWriteNormalizerTest.java | 509 ++++++++++++++++++++-
.../org/apache/doris/nereids/CTEContextTest.java | 95 ++++
.../nereids/rules/analysis/AnalyzeCTETest.java | 52 +++
.../iceberg/test_iceberg_spatial_v3.out | 99 ++++
.../nereids_rules_p0/cte/test_cte_name_reuse.out | 10 +
.../iceberg/test_iceberg_spatial_v3.groovy | 163 +++++++
.../cte/test_cte_name_reuse.groovy | 14 +
10 files changed, 1236 insertions(+), 13 deletions(-)
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java
b/fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java
index 9c50b8a1c1d..d3804352a6c 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java
@@ -18,7 +18,9 @@
package org.apache.doris.datasource.connector.converter;
import org.apache.doris.catalog.Column;
+import org.apache.doris.common.Pair;
import org.apache.doris.nereids.CTEContext;
+import org.apache.doris.nereids.StatementContext;
import org.apache.doris.nereids.analyzer.UnboundFunction;
import org.apache.doris.nereids.properties.OrderKey;
import org.apache.doris.nereids.rules.analysis.ExpressionAnalyzer;
@@ -70,13 +72,18 @@ import org.apache.doris.nereids.types.MapType;
import org.apache.doris.nereids.types.StructType;
import org.apache.doris.nereids.util.ExpressionUtils;
import org.apache.doris.nereids.util.TypeCoercionUtils;
+import org.apache.doris.qe.ConnectContext;
+import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
+import com.google.common.collect.LinkedHashMultimap;
+import com.google.common.collect.Multimap;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.IdentityHashMap;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -99,14 +106,38 @@ public final class ConnectorSpatialWriteNormalizer {
if (targets.stream().noneMatch(column ->
column.getType().typeContainsSpatialType())) {
return source;
}
+ return normalize(targets, source, sourceOrdinals, cteContext, new
NormalizationState());
+ }
+
+ private static LogicalPlan normalize(List<Column> targets, LogicalPlan
source,
+ List<Integer> sourceOrdinals, CTEContext cteContext,
NormalizationState state) {
if (source instanceof LogicalUnion && ((LogicalUnion)
source).getQualifier() == Qualifier.ALL) {
- return normalizeUnionAll(targets, (LogicalUnion) source,
sourceOrdinals, cteContext);
+ return normalizeUnionAll(targets, (LogicalUnion) source,
sourceOrdinals, cteContext, state);
}
if (source instanceof LogicalSubQueryAlias) {
LogicalPlan child = (LogicalPlan) source.child(0);
- LogicalPlan normalized = normalize(targets, child, sourceOrdinals,
cteContext);
+ LogicalPlan normalized = normalize(targets, child, sourceOrdinals,
cteContext, state);
return normalized == child ? source : (LogicalPlan)
source.withChildren(ImmutableList.of(normalized));
}
+ if (source instanceof LogicalCTEAnchor) {
+ LogicalCTEAnchor<?, ?> anchor = (LogicalCTEAnchor<?, ?>) source;
+ LogicalCTEProducer<?> producer = (LogicalCTEProducer<?>)
anchor.left();
+ if (producer.child() instanceof LogicalSubQueryAlias) {
+ LogicalSubQueryAlias<?> alias = (LogicalSubQueryAlias<?>)
producer.child();
+ CTEContext scope = new CTEContext(anchor.getCteId(),
+ alias.withChildren(ImmutableList.of(alias.child())),
cteContext);
+ scope.setAnalyzedPlan((LogicalPlan) producer.child());
+ // Normalize UNION ALL branches with their shared producer in
scope. Resolving
+ // the UNION output itself cannot prove its NULL leaves or
preserve branch values.
+ LogicalPlan normalized = normalize(targets, (LogicalPlan)
anchor.right(), sourceOrdinals, scope, state);
+ LogicalPlan definition =
scope.getAnalyzedCTEPlan(anchor.getCteId()).get();
+ if (normalized == anchor.right() && definition ==
producer.child()) {
+ return source;
+ }
+ return (LogicalPlan) anchor.withChildren(
+ state.rewriteProducer(producer, definition),
normalized);
+ }
+ }
if (source instanceof LogicalProject &&
isForwardingProject((LogicalProject<?>) source)) {
Plan input = source.child(0);
while (input instanceof LogicalSubQueryAlias) {
@@ -130,7 +161,7 @@ public final class ConnectorSpatialWriteNormalizer {
((LogicalProject<?>) source).getProjects(),
(LogicalUnion) input));
}
if (pushed.isPresent()) {
- return normalize(targets, (LogicalPlan) pushed.get(),
sourceOrdinals, cteContext);
+ return normalize(targets, (LogicalPlan) pushed.get(),
sourceOrdinals, cteContext, state);
}
}
}
@@ -225,7 +256,228 @@ public final class ConnectorSpatialWriteNormalizer {
}
}
}
- return changed ? new LogicalProject<>(outputs, normalizedSource) :
normalizedSource;
+ LogicalPlan result = changed ? new LogicalProject<>(outputs,
normalizedSource) : normalizedSource;
+ return normalizeForwardedNulls(targets, result, sourceOrdinals,
cteContext, state);
+ }
+
+ private static final class NormalizationState {
+ private final Map<Pair<ExprId, DataType>, Slot> cteOutputs = new
HashMap<>();
+ private final StatementContext statementContext;
+
+ private NormalizationState() {
+ ConnectContext connection = ConnectContext.get();
+ statementContext = connection == null ? null :
connection.getStatementContext();
+ }
+
+ private LogicalCTEProducer<?> rewriteProducer(LogicalCTEProducer<?>
producer, LogicalPlan definition) {
+ if (definition == producer.child()) {
+ return producer;
+ }
+ LogicalCTEProducer<?> rewritten = (LogicalCTEProducer<?>) producer
+ .withChildren(ImmutableList.of(definition));
+ // Bound analysis must expose the same added slots in its anchor
and producer registry.
+ // Standalone normalization can run without a statement context.
+ if (statementContext != null) {
+ statementContext.setCteProducer(producer.getCteId(),
rewritten);
+ }
+ return rewritten;
+ }
+ }
+
+ private static LogicalPlan normalizeForwardedNulls(List<Column> targets,
LogicalPlan source,
+ List<Integer> sourceOrdinals, CTEContext context,
NormalizationState state) {
+ ForwardedNulls forwarder = null;
+ LogicalPlan result = source;
+ List<NamedExpression> projected = new ArrayList<>(source.getOutput());
+ for (int i = 0; i < targets.size(); i++) {
+ if (!targets.get(i).getType().typeContainsSpatialType()) {
+ continue;
+ }
+ DataType target =
DataType.fromCatalogType(targets.get(i).getType());
+ int ordinal = sourceOrdinals.get(i);
+ Slot slot = projected.get(ordinal).toSlot();
+ if
(slot.getDataType().equals(spatialLiteralType(slot.getDataType(), target))) {
+ continue;
+ }
+ if (forwarder == null) {
+ forwarder = new ForwardedNulls(new Resolver(source, context),
state);
+ }
+ if (!canRetargetSpatialNulls(forwarder.resolver.resolve(slot,
result), target, true)) {
+ continue;
+ }
+ Optional<Pair<LogicalPlan, Slot>> appended =
forwarder.append(result, slot, target);
+ if (appended.isPresent()) {
+ projected.set(ordinal, appended.get().second);
+ result = appended.get().first;
+ }
+ }
+ // Restore the sink's width once, instead of adding another forwarding
layer per target.
+ return result == source ? source : new LogicalProject<>(projected,
result);
+ }
+
+ /** Adds a typed output without changing the old output used by other
projections/CTE consumers. */
+ private static final class ForwardedNulls {
+ private final Resolver resolver;
+ private final NormalizationState state;
+ // Passthrough ExprIds span projects; stable project ids scope
appended slots across rewrites.
+ private final Map<Integer, Map<Pair<ExprId, DataType>, Slot>>
appendedOutputs = new HashMap<>();
+ private final Set<CTEId> activeCtes = new HashSet<>();
+
+ private ForwardedNulls(Resolver resolver, NormalizationState state) {
+ this.resolver = resolver;
+ this.state = state;
+ }
+
+ private Optional<Pair<LogicalPlan, Slot>> append(LogicalPlan source,
Slot slot, DataType target) {
+ if (source instanceof LogicalProject && !((LogicalProject<?>)
source).isDistinct()) {
+ LogicalProject<?> project = (LogicalProject<?>) source;
+ for (int i = 0; i < project.getProjects().size(); i++) {
+ NamedExpression output = project.getProjects().get(i);
+ if (output.getExprId().equals(slot.getExprId())) {
+ return appendProject(project, i, output instanceof
Alias ? output.child(0) : output, target);
+ }
+ }
+ } else if (source instanceof LogicalSubQueryAlias || source
instanceof LogicalSort
+ || source instanceof LogicalLimit || source instanceof
LogicalFilter) {
+ return append((LogicalPlan) source.child(0), slot,
target).map(result -> {
+ LogicalPlan wrapper = (LogicalPlan)
source.withChildren(ImmutableList.of(result.first));
+ Slot output = wrapper.getOutput().stream()
+ .filter(value ->
value.getExprId().equals(result.second.getExprId())).findFirst().get();
+ return Pair.of(wrapper, output);
+ });
+ } else if (source instanceof LogicalCTEConsumer) {
+ return appendConsumer((LogicalCTEConsumer) source, slot,
target);
+ } else if (source instanceof LogicalCTEAnchor) {
+ LogicalCTEAnchor<?, ?> anchor = (LogicalCTEAnchor<?, ?>)
source;
+ return append((LogicalPlan) anchor.right(), slot,
target).map(result -> {
+ LogicalCTEProducer<?> producer = (LogicalCTEProducer<?>)
anchor.left();
+ Plan updated = state.rewriteProducer(producer,
+ (LogicalPlan)
resolver.producers.get(anchor.getCteId()));
+ return Pair.of((LogicalPlan) anchor.withChildren(updated,
result.first), result.second);
+ });
+ }
+ return Optional.empty();
+ }
+
+ private Optional<Pair<LogicalPlan, Slot>>
appendProject(LogicalProject<?> project, int ordinal,
+ Expression value, DataType target) {
+ Map<Pair<ExprId, DataType>, Slot> projectOutputs =
appendedOutputs.computeIfAbsent(
+ project.getId(), ignored -> new HashMap<>());
+ Pair<ExprId, DataType> key =
Pair.of(project.getProjects().get(ordinal).getExprId(), target);
+ Slot cached = projectOutputs.get(key);
+ if (cached != null) {
+ // Earlier appends only widen this projection, so the cached
slot remains in scope.
+ Preconditions.checkState(project.getOutput().contains(cached));
+ return Optional.of(Pair.of(project, cached));
+ }
+ Optional<Pair<LogicalPlan, Slot>> appended =
appendProjectValue(project, ordinal, value, target);
+ appended.ifPresent(result -> projectOutputs.put(key,
result.second));
+ return appended;
+ }
+
+ private Optional<Pair<LogicalPlan, Slot>>
appendProjectValue(LogicalProject<?> project, int ordinal,
+ Expression value, DataType target) {
+ if (value instanceof Slot) {
+ return append((LogicalPlan) project.child(), (Slot) value,
target).map(result -> {
+ List<NamedExpression> outputs = new
ArrayList<>(project.getProjects());
+ Alias typed = new Alias(result.second,
project.getProjects().get(ordinal).getName());
+ outputs.add(typed);
+ return Pair.of(project.withProjectsAndChild(outputs,
result.first), typed.toSlot());
+ });
+ }
+ if (!canRetargetSpatialNulls(value, target, true)) {
+ return Optional.empty();
+ }
+ List<NamedExpression> inputs = new
ArrayList<>(project.child().getOutput());
+ Expression shared = hoist(value, target, inputs);
+ LogicalPlan input = inputs.size() ==
project.child().getOutput().size()
+ ? (LogicalPlan) project.child() : new
LogicalProject<>(inputs, project.child());
+ List<NamedExpression> outputs = new
ArrayList<>(project.getProjects());
+ // Forwarding must not move runtime siblings out of scope or
evaluate RAND twice.
+ // Keep the original container for ordinary/shared consumers and
reuse its leaf inputs.
+ outputs.set(ordinal, (NamedExpression)
outputs.get(ordinal).withChildren(ImmutableList.of(shared)));
+ Alias typed = new Alias(normalizeSpatialNullsBeforeBinding(shared,
target, true),
+ outputs.get(ordinal).getName());
+ outputs.add(typed);
+ return Optional.of(Pair.of(project.withProjectsAndChild(outputs,
input), typed.toSlot()));
+ }
+
+ private Expression hoist(Expression value, DataType target,
List<NamedExpression> inputs) {
+ if (value instanceof Slot || isLiteralConstruction(value)) {
+ return value;
+ }
+ if (!target.toCatalogDataType().typeContainsSpatialType()
+ || target instanceof GeometryType || target instanceof
GeographyType) {
+ Alias input = new Alias(value, "spatial_write_input");
+ inputs.add(input);
+ return input.toSlot();
+ }
+ if (value.getClass() == Cast.class) {
+ return
value.withChildren(ImmutableList.of(hoist(value.child(0), target, inputs)));
+ }
+ List<Expression> children = new ArrayList<>(value.children());
+ for (int i = 0; i < children.size(); i++) {
+ DataType childTarget;
+ if (target instanceof ArrayType) {
+ childTarget = ((ArrayType) target).getItemType();
+ } else if (target instanceof MapType) {
+ childTarget = i % 2 == 0 ? ((MapType) target).getKeyType()
: ((MapType) target).getValueType();
+ } else {
+ boolean named = value instanceof CreateNamedStruct;
+ if (named && i % 2 == 0) {
+ continue;
+ }
+ childTarget = ((StructType) target).getFields().get(named
? i / 2 : i).getDataType();
+ }
+ children.set(i, hoist(children.get(i), childTarget, inputs));
+ }
+ return value.withChildren(children);
+ }
+
+ private Optional<Pair<LogicalPlan, Slot>>
appendConsumer(LogicalCTEConsumer consumer,
+ Slot slot, DataType target) {
+ Optional<CTEContext> context =
resolver.context.findCTEContext(consumer.getCteId());
+ Optional<LogicalPlan> producer =
resolver.context.getAnalyzedCTEPlan(consumer.getCteId());
+ if (!producer.isPresent()) {
+ producer =
Optional.ofNullable(resolver.producers.get(consumer.getCteId()))
+ .map(LogicalPlan.class::cast);
+ }
+ if (!producer.isPresent() || !activeCtes.add(consumer.getCteId()))
{
+ return Optional.empty();
+ }
+ try {
+ Slot producerSlot = consumer.getProducerSlot(slot);
+ Pair<ExprId, DataType> key = Pair.of(producerSlot.getExprId(),
target);
+ Slot typed = state.cteOutputs.get(key);
+ if (typed == null) {
+ Optional<Pair<LogicalPlan, Slot>> appended =
append(producer.get(), producerSlot, target);
+ if (!appended.isPresent()) {
+ return Optional.empty();
+ }
+ LogicalPlan updated = appended.get().first;
+ resolver.producers.put(consumer.getCteId(), updated);
+ context.ifPresent(binding ->
binding.setAnalyzedPlan(updated));
+ typed = appended.get().second;
+ // UNION branches share the producer, while each consumer
keeps its own ExprIds.
+ state.cteOutputs.put(key, typed);
+ } else {
+
Preconditions.checkState(producer.get().getOutput().contains(typed));
+ }
+ Optional<Slot> existing =
consumer.getProducerToConsumerOutputMap().get(typed).stream().findFirst();
+ if (existing.isPresent()) {
+ return Optional.of(Pair.of(consumer, existing.get()));
+ }
+ Slot output =
LogicalCTEConsumer.generateConsumerSlot(consumer.getName(), typed)
+ .withName(slot.getName());
+ Map<Slot, Slot> toProducer = new
LinkedHashMap<>(consumer.getConsumerToProducerOutputMap());
+ Multimap<Slot, Slot> toConsumer =
LinkedHashMultimap.create(consumer.getProducerToConsumerOutputMap());
+ toProducer.put(output, typed);
+ toConsumer.put(typed, output);
+ return Optional.of(Pair.of((LogicalPlan)
consumer.withTwoMaps(toProducer, toConsumer), output));
+ } finally {
+ activeCtes.remove(consumer.getCteId());
+ }
+ }
}
private static void collectSortInputs(Expression expression, Set<ExprId>
inputs) {
@@ -251,7 +503,7 @@ public final class ConnectorSpatialWriteNormalizer {
}
private static LogicalPlan normalizeUnionAll(List<Column> targets,
LogicalUnion source,
- List<Integer> sourceOrdinals, CTEContext context) {
+ List<Integer> sourceOrdinals, CTEContext context,
NormalizationState state) {
List<Plan> children = new ArrayList<>();
List<List<SlotReference>> childOutputs = new ArrayList<>();
boolean changed = !source.getConstantExprsList().isEmpty();
@@ -260,7 +512,7 @@ public final class ConnectorSpatialWriteNormalizer {
List<SlotReference> outputs = source.getRegularChildOutput(i);
LogicalPlan input = child.getOutput().equals(outputs)
? child : new
LogicalProject<>(ImmutableList.<NamedExpression>copyOf(outputs), child);
- LogicalPlan normalized = normalize(targets, input, sourceOrdinals,
context);
+ LogicalPlan normalized = normalize(targets, input, sourceOrdinals,
context, state);
children.add(normalized);
childOutputs.add(normalized.getOutput().stream().map(SlotReference.class::cast)
.collect(ImmutableList.toImmutableList()));
@@ -271,7 +523,7 @@ public final class ConnectorSpatialWriteNormalizer {
for (List<NamedExpression> row : source.getConstantExprsList()) {
LogicalPlan normalized = normalize(targets,
new
LogicalOneRowRelation(StatementScopeIdGenerator.newRelationId(), row),
- sourceOrdinals, context);
+ sourceOrdinals, context, state);
children.add(normalized);
childOutputs.add(normalized.getOutput().stream().map(SlotReference.class::cast)
.collect(ImmutableList.toImmutableList()));
@@ -403,9 +655,7 @@ public final class ConnectorSpatialWriteNormalizer {
LogicalCTEConsumer consumer = (LogicalCTEConsumer) source;
Optional<Plan> producer =
Optional.ofNullable(producers.get(consumer.getCteId()));
if (!producer.isPresent()) {
- producer = context.findCTEContext(consumer.getName())
- .filter(cte ->
cte.getCteId().equals(consumer.getCteId()))
- .flatMap(cte ->
cte.getAnalyzedCTEPlan(consumer.getName())).map(Plan.class::cast);
+ producer =
context.getAnalyzedCTEPlan(consumer.getCteId()).map(Plan.class::cast);
}
// Recursive CTEs do not prove constant provenance through
their cycle.
if (producer.isPresent() &&
activeCtes.add(consumer.getCteId())) {
diff --git a/fe/fe-core/src/main/java/org/apache/doris/nereids/CTEContext.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/CTEContext.java
index c54ca35137e..1446bc954f5 100644
--- a/fe/fe-core/src/main/java/org/apache/doris/nereids/CTEContext.java
+++ b/fe/fe-core/src/main/java/org/apache/doris/nereids/CTEContext.java
@@ -29,6 +29,7 @@ import org.apache.doris.qe.GlobalVariable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
@@ -47,6 +48,8 @@ public class CTEContext {
private LogicalPlan analyzedPlan;
private final Map<String, CTEContext> cteContextMap;
+ private final CTEContext previousCteContext;
+ private Map<CTEId, CTEContext> cteContextsById;
/* build head CTEContext */
public CTEContext() {
@@ -71,6 +74,7 @@ public class CTEContext {
// if inner name same with outer name, use inner name
in this scope.
.buildKeepingLast();
this.cteId = cteId;
+ this.previousCteContext = previousCteContext;
this.recursiveCteOutputs = ImmutableList.of();
}
@@ -83,6 +87,7 @@ public class CTEContext {
this.recursiveCteOutputs = recursiveCteOutputs != null ?
ImmutableList.copyOf(recursiveCteOutputs)
: ImmutableList.of();
this.cteContextMap = ImmutableMap.of(name, this);
+ this.previousCteContext = null;
}
private static int currentLowerCaseTableNames() {
@@ -115,6 +120,26 @@ public class CTEContext {
return Optional.of(findCTEContext(cteName).get().analyzedPlan);
}
+ public Optional<LogicalPlan> getAnalyzedCTEPlan(CTEId id) {
+ return findCTEContext(id).map(context -> context.analyzedPlan);
+ }
+
+ /** Finds the original binding even when a later name shadows it after
case folding. */
+ public Optional<CTEContext> findCTEContext(CTEId id) {
+ if (id.equals(cteId)) {
+ return Optional.of(this);
+ }
+ if (cteContextsById == null) {
+ // Analysis is synchronous. Index binding objects once so updates
remain visible
+ // without copying every ancestor's id map at registration or
rescanning it per slot.
+ cteContextsById = new HashMap<>();
+ for (CTEContext context = previousCteContext; context != null;
context = context.previousCteContext) {
+ cteContextsById.putIfAbsent(context.cteId, context);
+ }
+ }
+ return Optional.ofNullable(cteContextsById.get(id));
+ }
+
/**
* findCTEContext
*/
diff --git
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTE.java
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTE.java
index 4789f1cdb8e..63964aefd4c 100644
---
a/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTE.java
+++
b/fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTE.java
@@ -92,7 +92,17 @@ public class AnalyzeCTE extends OneAnalysisRuleFactory {
ctx.cascadesContext.addPlanProcesses(outerCascadesCtx.getPlanProcesses());
// should construct anchor from back to front, because the cte
behind depends on the front
for (int i = result.second.size() - 1; i >= 0; i--) {
- root = new LogicalCTEAnchor<>(result.second.get(i).getCteId(),
result.second.get(i), root);
+ LogicalCTEProducer<Plan> producer = result.second.get(i);
+ LogicalSubQueryAlias<?> alias = (LogicalSubQueryAlias<?>)
producer.child();
+ // Sink binding may add a typed output while retaining every
original CTE slot.
+ // Anchor the final producer so the new consumer mapping has a
matching output.
+ // A later name can hide this binding after case folding;
producer identity must retain its CTEId.
+ LogicalPlan finalPlan =
result.first.getAnalyzedCTEPlan(producer.getCteId()).get();
+ if (finalPlan != alias) {
+ producer = new LogicalCTEProducer<>(producer.getCteId(),
finalPlan);
+
ctx.cascadesContext.getStatementContext().setCteProducer(producer.getCteId(),
producer);
+ }
+ root = new LogicalCTEAnchor<>(producer.getCteId(), producer,
root);
}
return root;
}).toRule(RuleType.ANALYZE_CTE);
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizerTest.java
b/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizerTest.java
index b1b1994036c..570f42e55b5 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizerTest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizerTest.java
@@ -25,6 +25,7 @@ import org.apache.doris.catalog.StructField;
import org.apache.doris.catalog.StructType;
import org.apache.doris.catalog.Type;
import org.apache.doris.nereids.CTEContext;
+import org.apache.doris.nereids.StatementContext;
import org.apache.doris.nereids.exceptions.AnalysisException;
import org.apache.doris.nereids.properties.OrderKey;
import org.apache.doris.nereids.rules.exploration.join.JoinReorderContext;
@@ -36,6 +37,7 @@ import org.apache.doris.nereids.trees.expressions.CaseWhen;
import org.apache.doris.nereids.trees.expressions.Cast;
import org.apache.doris.nereids.trees.expressions.Expression;
import org.apache.doris.nereids.trees.expressions.NamedExpression;
+import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.SlotReference;
import org.apache.doris.nereids.trees.expressions.WhenClause;
import org.apache.doris.nereids.trees.expressions.functions.BoundFunction;
@@ -66,6 +68,7 @@ import
org.apache.doris.nereids.trees.plans.algebra.SetOperation.Qualifier;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
import org.apache.doris.nereids.trees.plans.logical.LogicalJoin;
import org.apache.doris.nereids.trees.plans.logical.LogicalLimit;
import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation;
@@ -84,14 +87,17 @@ import org.apache.doris.nereids.types.TinyIntType;
import org.apache.doris.nereids.util.TypeCoercionUtils;
import org.apache.doris.qe.AutoCloseConnectContext;
import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.GlobalVariable;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
+import java.util.Optional;
public class ConnectorSpatialWriteNormalizerTest {
@Test
@@ -312,6 +318,11 @@ public class ConnectorSpatialWriteNormalizerTest {
private void assertNullProjection(Type target, LogicalPlan source,
CTEContext context) {
LogicalPlan normalized = ConnectorSpatialWriteNormalizer.normalize(
ImmutableList.of(new Column("shape", target)), source,
context);
+ if (source instanceof LogicalCTEAnchor) {
+ Assertions.assertInstanceOf(LogicalCTEAnchor.class, normalized);
+ source = (LogicalPlan) source.child(1);
+ normalized = (LogicalPlan) normalized.child(1);
+ }
Assertions.assertInstanceOf(LogicalProject.class, normalized);
Assertions.assertSame(source, normalized.child(0));
Assertions.assertNotEquals(source.getOutput().get(0).getExprId(),
normalized.getOutput().get(0).getExprId());
@@ -654,6 +665,491 @@ public class ConnectorSpatialWriteNormalizerTest {
}
}
+ @Test
+ public void
testForwardedProjectRetagsSpatialNullWithDynamicOrdinarySibling() {
+ LogicalPlan input = row(new SlotReference("id", IntegerType.INSTANCE));
+ Slot id = input.getOutput().get(0);
+ Expression payload = new CreateNamedStruct(new StringLiteral("k"), id,
+ new StringLiteral("shape"), new Cast(NullLiteral.INSTANCE,
IntegerType.INSTANCE));
+ LogicalProject<?> producer = new LogicalProject<>(ImmutableList.of(new
Alias(payload, "payload")), input);
+ LogicalSubQueryAlias<?> alias = new LogicalSubQueryAlias<>("q",
producer);
+ LogicalProject<?> forwarded = new LogicalProject<>(ImmutableList.of(
+ new Alias(alias.getOutput().get(0), "renamed")), alias);
+ Type geometry = ScalarType.createGeometryType("OGC:CRS84");
+ Type target = new StructType(new StructField("k", Type.INT), new
StructField("shape", geometry));
+
+ LogicalPlan normalized = ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)), forwarded,
new CTEContext());
+
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals("renamed",
normalized.getOutput().get(0).getName());
+ }
+
+ @Test
+ public void testDeepForwardingPreservesOriginalOutputsAndRequiredFields() {
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical"))) {
+ for (int kind = 0; kind < 3; kind++) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE, false));
+ Slot id = input.getOutput().get(0);
+ Expression value = new CreateNamedStruct(new
StringLiteral("k"), id,
+ new StringLiteral("shape"), new
Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ Type target = new StructType(new StructField("k", Type.INT,
null, false),
+ new StructField("shape", spatial));
+ if (kind == 1) {
+ value = new Array(value);
+ target = new ArrayType(target);
+ } else if (kind == 2) {
+ value = new CreateMap(new Cast(id, StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE,
IntegerType.INSTANCE));
+ target = new MapType(Type.STRING, spatial);
+ }
+ LogicalPlan source = new LogicalProject<>(ImmutableList.of(new
Alias(value, "payload")), input);
+ for (int depth = 0; depth < 4; depth++) {
+ LogicalSubQueryAlias<?> alias = new
LogicalSubQueryAlias<>("q" + depth,
+ Optional.of(ImmutableList.of("renamed")), source);
+ source = new
LogicalProject<>(ImmutableList.of(alias.getOutput().get(0)), alias);
+ }
+ Slot ordinary = source.getOutput().get(0);
+ source = new LogicalProject<>(ImmutableList.of(new
Alias(ordinary, "ordinary"),
+ new Alias(ordinary, "spatial")), source);
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("ordinary",
value.getDataType().toCatalogDataType()),
+ new Column("spatial", target)), source, new
CTEContext());
+ Assertions.assertEquals(2, normalized.getOutput().size());
+ Assertions.assertEquals(value.getDataType(),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(1).getDataType());
+ Assertions.assertEquals("spatial",
normalized.getOutput().get(1).getName());
+ }
+ }
+ }
+
+ @Test
+ public void
testMultipleForwardedSpatialTargetsKeepOrdinaryOutputAndColumnOrder() {
+ LogicalPlan input = row(new SlotReference("id", IntegerType.INSTANCE));
+ Expression value = new CreateNamedStruct(new StringLiteral("k"),
input.getOutput().get(0),
+ new StringLiteral("shape"), new Cast(NullLiteral.INSTANCE,
IntegerType.INSTANCE));
+ LogicalProject<?> producer = new LogicalProject<>(ImmutableList.of(new
Alias(value, "payload")), input);
+ Slot payload = producer.getOutput().get(0);
+ LogicalProject<?> source = new LogicalProject<>(ImmutableList.of(new
Alias(payload, "geom"),
+ new Alias(payload, "ordinary"), new Alias(payload, "geog")),
producer);
+ Type geometry = new StructType(new StructField("k", Type.INT),
+ new StructField("shape",
ScalarType.createGeometryType("OGC:CRS84")));
+ Type geography = new StructType(new StructField("k", Type.INT),
+ new StructField("shape",
ScalarType.createGeographyType("OGC:CRS84", "spherical")));
+
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("geom", geometry), new Column("ordinary",
value.getDataType().toCatalogDataType()),
+ new Column("geog", geography)), source, new CTEContext());
+
+ Assertions.assertEquals(3, normalized.getOutput().size());
+ Assertions.assertEquals(DataType.fromCatalogType(geometry),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals(value.getDataType(),
normalized.getOutput().get(1).getDataType());
+ Assertions.assertEquals(source.getOutput().get(1),
normalized.getOutput().get(1));
+ Assertions.assertEquals(DataType.fromCatalogType(geography),
normalized.getOutput().get(2).getDataType());
+ Assertions.assertEquals(ImmutableList.of("geom", "ordinary", "geog"),
normalized.getOutput().stream()
+ .map(Slot::getName).collect(ImmutableList.toImmutableList()));
+ Assertions.assertNotEquals(normalized.getOutput().get(0).getExprId(),
+ normalized.getOutput().get(2).getExprId());
+
+ LogicalPlan routed =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("shape", geometry), new Column("location",
geography)), source,
+ ImmutableList.of(2, 0), new CTEContext());
+ Assertions.assertEquals(3, routed.getOutput().size());
+ Assertions.assertEquals(DataType.fromCatalogType(geography),
routed.getOutput().get(0).getDataType());
+ Assertions.assertEquals(value.getDataType(),
routed.getOutput().get(1).getDataType());
+ Assertions.assertEquals(source.getOutput().get(1),
routed.getOutput().get(1));
+ Assertions.assertEquals(DataType.fromCatalogType(geometry),
routed.getOutput().get(2).getDataType());
+ }
+
+ @Test
+ public void testForwardedCtePreservesSharedConsumerAndSingleEvaluation() {
+ try (AutoCloseConnectContext ignored = new AutoCloseConnectContext(new
ConnectContext())) {
+ for (boolean anchored : ImmutableList.of(false, true)) {
+ Type spatial = ScalarType.createGeometryType("OGC:CRS84");
+ Type target = new MapType(Type.STRING, spatial);
+ Expression value = new CreateMap(new Cast(new Random(),
StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> producer = new
LogicalSubQueryAlias<>("source",
+ Optional.of(ImmutableList.of("renamed")), new
LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")),
row(new IntegerLiteral(1))));
+ CTEId id = new CTEId(10);
+ CTEContext context = new CTEContext(id, producer, new
CTEContext());
+ context.setAnalyzedPlan(producer);
+ LogicalCTEConsumer consumer = new LogicalCTEConsumer(new
RelationId(2), id, "source", producer);
+ LogicalCTEConsumer shared = new LogicalCTEConsumer(new
RelationId(3), id, "source", producer);
+ LogicalPlan source = anchored ? new LogicalCTEAnchor<>(id,
+ new LogicalCTEProducer<>(id, producer), consumer) :
consumer;
+
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)),
source,
+ anchored ? new CTEContext() : context);
+
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals("renamed",
normalized.getOutput().get(0).getName());
+ Plan updated = anchored ? normalized.child(0).child(0)
+ : context.getAnalyzedCTEPlan("source").get();
+ Assertions.assertEquals(2, updated.getOutput().size());
+ Assertions.assertEquals(producer.getOutput().get(0),
updated.getOutput().get(0));
+ Assertions.assertEquals(value.getDataType(),
updated.getOutput().get(0).getDataType());
+
Assertions.assertEquals(consumer.getConsumerToProducerOutputMap(),
+ ImmutableMap.of(consumer.getOutput().get(0),
producer.getOutput().get(0)));
+ Assertions.assertEquals(producer.getOutput().get(0),
shared.getProducerSlot(shared.getOutput().get(0)));
+ Assertions.assertEquals(1, countRandom(updated));
+ LogicalCTEConsumer rewritten = (LogicalCTEConsumer) (anchored
+ ? normalized.child(1).child(0) : normalized.child(0));
+ Assertions.assertEquals(2, rewritten.getOutput().size());
+ Assertions.assertEquals(consumer.getOutput().get(0),
rewritten.getOutput().get(0));
+
Assertions.assertTrue(updated.getOutput().contains(rewritten.getProducerSlot(
+ rewritten.getOutput().get(1))));
+ }
+ }
+ }
+
+ @Test
+ public void
testAnchoredUnionAllSharesRuntimeProducerAndKeepsOrdinaryOutput() {
+ try (AutoCloseConnectContext ignored = new AutoCloseConnectContext(new
ConnectContext())) {
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical")))
{
+ Expression value = new CreateMap(new Cast(new Random(),
StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> producer = new
LogicalSubQueryAlias<>("source", new LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")), row(new
IntegerLiteral(1))));
+ CTEId id = new CTEId(20);
+ LogicalCTEConsumer first = new LogicalCTEConsumer(new
RelationId(2), id, "source", producer);
+ LogicalCTEConsumer second = new LogicalCTEConsumer(new
RelationId(3), id, "source", producer);
+ LogicalProject<?> left = new LogicalProject<>(ImmutableList.of(
+ new Alias(first.getOutput().get(0), "spatial"),
+ new Alias(first.getOutput().get(0), "ordinary")),
first);
+ LogicalProject<?> right = new
LogicalProject<>(ImmutableList.of(
+ new Alias(second.getOutput().get(0), "spatial"),
+ new Alias(second.getOutput().get(0), "ordinary")),
second);
+ LogicalUnion branches = new LogicalUnion(Qualifier.ALL,
ImmutableList.of(
+ new SlotReference("spatial", value.getDataType()),
+ new SlotReference("ordinary", value.getDataType())),
ImmutableList.of(
+
left.getOutput().stream().map(SlotReference.class::cast)
+
.collect(ImmutableList.toImmutableList()),
+
right.getOutput().stream().map(SlotReference.class::cast)
+
.collect(ImmutableList.toImmutableList())),
+ ImmutableList.of(), false, ImmutableList.of(left,
right));
+ LogicalCTEAnchor<?, ?> source = new LogicalCTEAnchor<>(id,
+ new LogicalCTEProducer<>(id, producer), branches);
+ Type target = new MapType(Type.STRING, spatial);
+
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("spatial", target), new Column("ordinary",
new MapType(Type.STRING, Type.INT))),
+ source, new CTEContext());
+
+ Assertions.assertEquals(2, normalized.getOutput().size());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals(value.getDataType(),
normalized.getOutput().get(1).getDataType());
+ Assertions.assertEquals(1, normalized.collectToList(p -> p
instanceof LogicalCTEProducer).size());
+ Plan updated = normalized.child(0).child(0);
+ Assertions.assertEquals(2, updated.getOutput().size());
+ Assertions.assertEquals(producer.getOutput().get(0),
updated.getOutput().get(0));
+ Assertions.assertEquals(value.getDataType(),
updated.getOutput().get(0).getDataType());
+ Assertions.assertEquals(1, countRandom(normalized));
+ for (LogicalCTEConsumer consumer :
normalized.<LogicalCTEConsumer>collectToList(
+ p -> p instanceof LogicalCTEConsumer)) {
+ Assertions.assertEquals(value.getDataType(),
consumer.getOutput().get(0).getDataType());
+ for (Slot output : consumer.getOutput()) {
+
Assertions.assertTrue(updated.getOutput().contains(consumer.getProducerSlot(output)));
+ }
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testPlainCteCaseSensitiveForwarding() {
+ assertPlainCteCaseCollidingForwarding(0);
+ }
+
+ @Test
+ public void testPlainCteLowercaseForwarding() {
+ assertPlainCteCaseCollidingForwarding(1);
+ }
+
+ @Test
+ public void testPlainCteCaseInsensitiveForwarding() {
+ assertPlainCteCaseCollidingForwarding(2);
+ }
+
+ private void assertPlainCteCaseCollidingForwarding(int mode) {
+ int originalMode = GlobalVariable.lowerCaseTableNames;
+ try {
+ GlobalVariable.lowerCaseTableNames = mode;
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical")))
{
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ Expression value = new CreateNamedStruct(new
StringLiteral("k"), input.getOutput().get(0),
+ new StringLiteral("shape"), new
Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> first = new
LogicalSubQueryAlias<>("c", new LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")), input));
+ CTEId firstId = new CTEId(60);
+ CTEContext firstContext = new CTEContext(firstId, first, new
CTEContext());
+ firstContext.setAnalyzedPlan(first);
+ LogicalCTEConsumer dependency = new LogicalCTEConsumer(new
RelationId(2), firstId, "c", first);
+ LogicalSubQueryAlias<Plan> second = new
LogicalSubQueryAlias<>("C", new LogicalProject<>(
+ ImmutableList.of(new
Alias(dependency.getOutput().get(0), "payload")), dependency));
+ CTEId secondId = new CTEId(61);
+ CTEContext context = new CTEContext(secondId, second,
firstContext);
+ context.setAnalyzedPlan(second);
+ LogicalCTEConsumer consumer = new LogicalCTEConsumer(new
RelationId(3), secondId, "C", second);
+ Type target = new StructType(new StructField("k", Type.INT),
new StructField("shape", spatial));
+
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)),
consumer, context);
+
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals(first.getOutput().get(0),
+
firstContext.getAnalyzedCTEPlan("c").get().getOutput().get(0));
+ Assertions.assertEquals(2,
firstContext.getAnalyzedCTEPlan("c").get().getOutput().size());
+ Assertions.assertEquals(2,
context.getAnalyzedCTEPlan("C").get().getOutput().size());
+ }
+ } finally {
+ GlobalVariable.lowerCaseTableNames = originalMode;
+ }
+ }
+
+ @Test
+ public void testAnchoredRewriteUpdatesStatementProducer() {
+ ConnectContext connection = new ConnectContext();
+ try (AutoCloseConnectContext ignored = new
AutoCloseConnectContext(connection)) {
+ StatementContext statement = new StatementContext();
+ connection.setStatementContext(statement);
+ for (boolean wrapped : ImmutableList.of(false, true)) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ Expression value = new CreateMap(new
Cast(input.getOutput().get(0), StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> alias = new
LogicalSubQueryAlias<>("source", new LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")), input));
+ CTEId id = new CTEId(70);
+ LogicalCTEProducer<?> producer = new LogicalCTEProducer<>(id,
alias);
+ statement.setCteProducer(id, producer);
+ LogicalCTEConsumer consumer = new LogicalCTEConsumer(new
RelationId(2), id, "source", alias);
+ LogicalPlan source = new LogicalCTEAnchor<>(id, producer,
consumer);
+ if (wrapped) {
+ source = new LogicalProject<>(ImmutableList.of(new
Alias(source.getOutput().get(0), "result")),
+ source);
+ }
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(new Column(
+ "payload", new MapType(Type.STRING,
ScalarType.createGeometryType("OGC:CRS84")))),
+ source, new CTEContext());
+ LogicalCTEProducer<?> rewritten =
normalized.<LogicalCTEProducer<?>>collectToList(
+ p -> p instanceof LogicalCTEProducer).get(0);
+ Assertions.assertNotSame(producer, rewritten);
+ Assertions.assertSame(rewritten,
statement.getCteProducerByCteId(id));
+ }
+ }
+ }
+
+ @Test
+ public void testUnrelatedAnchorRetainsProducerIdentity() {
+ for (boolean wrapped : ImmutableList.of(false, true)) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ Expression value = new CreateMap(new
Cast(input.getOutput().get(0), StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> alias = new
LogicalSubQueryAlias<>("source", new LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")), input));
+ CTEId id = new CTEId(80);
+ LogicalCTEConsumer consumer = new LogicalCTEConsumer(new
RelationId(2), id, "source", alias);
+ CTEId unusedId = new CTEId(81);
+ LogicalCTEProducer<?> unused = new LogicalCTEProducer<>(unusedId,
+ new LogicalSubQueryAlias<>("unused", row(new
IntegerLiteral(1))));
+ LogicalPlan source = new LogicalCTEAnchor<>(id, new
LogicalCTEProducer<>(id, alias),
+ new LogicalCTEAnchor<>(unusedId, unused, consumer));
+ if (wrapped) {
+ source = new LogicalProject<>(ImmutableList.of(new
Alias(source.getOutput().get(0), "result")), source);
+ }
+ Type target = new MapType(Type.STRING,
ScalarType.createGeometryType("OGC:CRS84"));
+ LogicalPlan normalized = ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)), source,
new CTEContext());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ LogicalCTEProducer<?> preserved =
normalized.<LogicalCTEProducer<?>>collectToList(
+ p -> p instanceof LogicalCTEProducer &&
((LogicalCTEProducer<?>) p).getCteId().equals(unusedId)).get(0);
+ Assertions.assertSame(unused, preserved);
+ }
+ }
+
+ @Test
+ public void testRepeatedForwardedSlotReusesEachTargetType() {
+ LogicalPlan input = row(new SlotReference("id", IntegerType.INSTANCE));
+ Expression value = new CreateMap(new Cast(input.getOutput().get(0),
StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalProject<?> producer = new LogicalProject<>(ImmutableList.of(new
Alias(value, "payload")), input);
+ LogicalProject<?> source = new LogicalProject<>(ImmutableList.of(
+ new Alias(producer.getOutput().get(0), "first"), new
Alias(producer.getOutput().get(0), "second"),
+ new Alias(producer.getOutput().get(0), "third"), new
Alias(producer.getOutput().get(0), "fourth")),
+ producer);
+ Type geometry = new MapType(Type.STRING,
ScalarType.createGeometryType("OGC:CRS84"));
+ Type geography = new MapType(Type.STRING,
ScalarType.createGeographyType("OGC:CRS84", "spherical"));
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("first", geometry), new Column("second", geometry),
+ new Column("third", geography), new Column("fourth",
geometry)), source, new CTEContext());
+ LogicalPlan rewrittenProducer = (LogicalPlan)
normalized.child(0).child(0);
+ Assertions.assertEquals(3, rewrittenProducer.getOutput().size());
+ Assertions.assertEquals(producer.getOutput().get(0),
rewrittenProducer.getOutput().get(0));
+
Assertions.assertEquals(ImmutableList.of(DataType.fromCatalogType(geometry),
DataType.fromCatalogType(geometry),
+ DataType.fromCatalogType(geography),
DataType.fromCatalogType(geometry)), normalized.getOutput().stream()
+
.map(Slot::getDataType).collect(ImmutableList.toImmutableList()));
+ }
+
+ @Test
+ public void testPassthroughProjectsKeepAppendedOutputsInScope() {
+ assertPassthroughProjectCacheScope(false);
+ }
+
+ @Test
+ public void testPassthroughProjectsKeepAliasedTargetFirstInScope() {
+ assertPassthroughProjectCacheScope(true);
+ }
+
+ private void assertPassthroughProjectCacheScope(boolean aliasFirst) {
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical"))) {
+ for (int depth : ImmutableList.of(0, 1, 4)) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ Expression value = new CreateNamedStruct(new
StringLiteral("k"), input.getOutput().get(0),
+ new StringLiteral("shape"), new
Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalProject<?> producer = new
LogicalProject<>(ImmutableList.of(new Alias(value, "s")), input);
+ LogicalPlan forwarded = producer;
+ for (int i = 0; i < depth; i++) {
+ forwarded = new
LogicalProject<>(ImmutableList.of(forwarded.getOutput().get(0)), forwarded);
+ }
+ Slot original = forwarded.getOutput().get(0);
+ LogicalProject<?> aliases = new
LogicalProject<>(ImmutableList.of(original,
+ new Alias(original, "renamed")), forwarded);
+ LogicalProject<?> source = new
LogicalProject<>(ImmutableList.of(
+ aliases.getOutput().get(aliasFirst ? 1 : 0),
aliases.getOutput().get(aliasFirst ? 0 : 1),
+ new Alias(original, "ordinary")), aliases);
+ Type target = new StructType(new StructField("k", Type.INT),
new StructField("shape", spatial));
+
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("first", target), new Column("second",
target),
+ new Column("ordinary",
value.getDataType().toCatalogDataType())), source, new CTEContext());
+
+ Assertions.assertEquals(3, normalized.getOutput().size());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(1).getDataType());
+ Assertions.assertEquals(source.getOutput().get(2),
normalized.getOutput().get(2));
+ Assertions.assertEquals(value.getDataType(),
normalized.getOutput().get(2).getDataType());
+ LogicalProject<?> rewritten =
normalized.<LogicalProject<?>>collectToList(
+ p -> p instanceof LogicalProject &&
((LogicalProject<?>) p).getId() == producer.getId()).get(0);
+ Assertions.assertEquals(2, rewritten.getOutput().size());
+ Assertions.assertEquals(producer.getOutput().get(0),
rewritten.getOutput().get(0));
+ }
+ }
+ }
+
+ @Test
+ public void testAnchoredCteShadowingRetainsBoundOuterProducer() {
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical"))) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ Expression value = new CreateMap(new
Cast(input.getOutput().get(0), StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalSubQueryAlias<Plan> outer = new
LogicalSubQueryAlias<>("source", new LogicalProject<>(
+ ImmutableList.of(new Alias(value, "payload")), input));
+ CTEId outerId = new CTEId(30);
+ CTEContext context = new CTEContext(outerId, outer, new
CTEContext());
+ context.setAnalyzedPlan(outer);
+ LogicalCTEConsumer outerConsumer = new LogicalCTEConsumer(new
RelationId(2), outerId, "source", outer);
+ LogicalSubQueryAlias<Plan> inner = new
LogicalSubQueryAlias<>("source", new LogicalProject<>(
+ ImmutableList.of(new
Alias(outerConsumer.getOutput().get(0), "payload")), outerConsumer));
+ CTEId innerId = new CTEId(31);
+ LogicalCTEConsumer innerConsumer = new LogicalCTEConsumer(new
RelationId(3), innerId, "source", inner);
+ LogicalCTEAnchor<?, ?> source = new LogicalCTEAnchor<>(innerId,
+ new LogicalCTEProducer<>(innerId, inner), innerConsumer);
+ Type target = new MapType(Type.STRING, spatial);
+
+ LogicalPlan normalized = ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)), source,
context);
+
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ LogicalPlan updatedOuter =
context.getAnalyzedCTEPlan("source").get();
+ Assertions.assertEquals(outer.getOutput().get(0),
updatedOuter.getOutput().get(0));
+ Assertions.assertEquals(value.getDataType(),
updatedOuter.getOutput().get(0).getDataType());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
updatedOuter.getOutput().get(1).getDataType());
+ Assertions.assertEquals(outerId,
context.findCTEContext("source").get().getCteId());
+ }
+ }
+
+ @Test
+ public void
testForwardingThroughRowPreservingWrappersKeepsTheirOriginalInputs() {
+ LogicalPlan input = row(new SlotReference("id", IntegerType.INSTANCE));
+ Expression value = new CreateMap(new Cast(input.getOutput().get(0),
StringType.INSTANCE),
+ new Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalProject<?> producer = new LogicalProject<>(ImmutableList.of(new
Alias(value, "payload")), input);
+ Slot original = producer.getOutput().get(0);
+ Expression predicate = new MapContainsKey(original, new
StringLiteral("1"));
+ LogicalFilter<?> filter = new
LogicalFilter<>(ImmutableSet.of(predicate), producer);
+ OrderKey key = new OrderKey(original, true, false);
+ LogicalSort<?> sort = new LogicalSort<>(ImmutableList.of(key), filter);
+ LogicalLimit<?> limit = new LogicalLimit<>(1, 2, LimitPhase.ORIGIN,
sort);
+ LogicalProject<?> source = new LogicalProject<>(ImmutableList.of(new
Alias(original, "result")), limit);
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(new Column("payload",
+ new MapType(Type.STRING,
ScalarType.createGeometryType("OGC:CRS84")))), source, new CTEContext());
+ LogicalLimit<?> rewrittenLimit = (LogicalLimit<?>)
normalized.child(0).child(0);
+ Assertions.assertEquals(1, rewrittenLimit.getLimit());
+ Assertions.assertEquals(2, rewrittenLimit.getOffset());
+ LogicalSort<?> rewrittenSort = (LogicalSort<?>) rewrittenLimit.child();
+ Assertions.assertSame(key, rewrittenSort.getOrderKeys().get(0));
+ Assertions.assertEquals(filter.getConjuncts(), ((LogicalFilter<?>)
rewrittenSort.child()).getConjuncts());
+ }
+
+ @Test
+ public void testForwardedInvalidSpatialValueAndCastAreRejected() {
+ Type geometry = ScalarType.createGeometryType("OGC:CRS84");
+ Type target = new MapType(Type.STRING, geometry);
+ for (Expression leaf : ImmutableList.of(new IntegerLiteral(1),
+ new Cast(new NullLiteral(DataType.fromCatalogType(geometry)),
IntegerType.INSTANCE))) {
+ LogicalPlan input = row(new SlotReference("id",
IntegerType.INSTANCE));
+ LogicalProject<?> producer = new
LogicalProject<>(ImmutableList.of(new Alias(new CreateMap(
+ new Cast(input.getOutput().get(0), StringType.INSTANCE),
leaf), "payload")), input);
+ LogicalProject<?> source = new LogicalProject<>(ImmutableList.of(
+ new Alias(producer.getOutput().get(0), "renamed")),
producer);
+ Assertions.assertThrows(AnalysisException.class, () ->
ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)), source,
new CTEContext()));
+ }
+ }
+
+ private int countRandom(Plan plan) {
+ return plan.getExpressions().stream().mapToInt(expression -> expression
+ .collect(value -> value instanceof Random).size()).sum()
+ + plan.children().stream().mapToInt(this::countRandom).sum();
+ }
+
+ @Test
+ public void testForwardedConstructorSharesMatchingSpatialFunction() {
+ try (AutoCloseConnectContext ignored = new AutoCloseConnectContext(new
ConnectContext())) {
+ for (Type spatial :
ImmutableList.of(ScalarType.createGeometryType("OGC:CRS84"),
+ ScalarType.createGeographyType("OGC:CRS84", "spherical")))
{
+ LogicalPlan input = row(new SlotReference("wkb",
StringType.INSTANCE));
+ Expression function =
spatial.equals(ScalarType.createGeometryType("OGC:CRS84"))
+ ? new StGeometryFromWKBTyped(input.getOutput().get(0))
+ : new StGeogFromWKB(input.getOutput().get(0));
+ Expression value = new CreateNamedStruct(new
StringLiteral("shape"), function,
+ new StringLiteral("extra"), new
Cast(NullLiteral.INSTANCE, IntegerType.INSTANCE));
+ LogicalProject<?> producer = new
LogicalProject<>(ImmutableList.of(new Alias(value, "payload")), input);
+ LogicalProject<?> source = new
LogicalProject<>(ImmutableList.of(
+ new Alias(producer.getOutput().get(0), "renamed")),
producer);
+ Type target = new StructType(new StructField("shape",
spatial), new StructField("extra", spatial));
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(
+ ImmutableList.of(new Column("payload", target)),
source, new CTEContext());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(0).getDataType());
+ LogicalProject<?> rewritten = (LogicalProject<?>)
normalized.child(0).child(0);
+ LogicalProject<?> inputs = (LogicalProject<?>)
rewritten.child();
+ Assertions.assertSame(input, inputs.child());
+ Assertions.assertSame(function,
inputs.getProjects().get(1).child(0));
+ Slot shared = inputs.getOutput().get(1);
+ Assertions.assertEquals(shared,
rewritten.getProjects().get(0).child(0).child(1));
+ Assertions.assertEquals(shared,
rewritten.getProjects().get(1).child(0).child(1));
+ Assertions.assertEquals(value.getDataType(),
rewritten.getOutput().get(0).getDataType());
+ }
+ }
+ }
+
@Test
public void
testDirectProjectKeepsMatchingSpatialSlotWhenRetaggingAnotherField() {
Type geometry = ScalarType.createGeometryType("OGC:CRS84");
@@ -853,8 +1349,17 @@ public class ConnectorSpatialWriteNormalizerTest {
new OrderKey(consumer, false, true), new OrderKey(id,
true, false)), project);
LogicalLimit<?> limit = new LogicalLimit<>(1, 0,
LimitPhase.ORIGIN, sort);
Type target = new MapType(Type.STRING,
ScalarType.createGeometryType("OGC:CRS84"));
- Assertions.assertSame(limit,
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
- new Column("id", Type.INT), new Column("shape", target)),
limit, new CTEContext()));
+ LogicalPlan normalized =
ConnectorSpatialWriteNormalizer.normalize(ImmutableList.of(
+ new Column("id", Type.INT), new Column("shape", target)),
limit, new CTEContext());
+ Assertions.assertEquals(DataType.fromCatalogType(target),
normalized.getOutput().get(1).getDataType());
+ LogicalLimit<?> rewrittenLimit = (LogicalLimit<?>)
normalized.child(0);
+ Assertions.assertEquals(limit.getLimit(),
rewrittenLimit.getLimit());
+ LogicalSort<?> rewrittenSort = (LogicalSort<?>)
rewrittenLimit.child();
+ Assertions.assertEquals(sort.getOrderKeys(),
rewrittenSort.getOrderKeys());
+ LogicalProject<?> rewrittenProducer = (LogicalProject<?>)
rewrittenSort.child();
+ Assertions.assertEquals(map.toSlot(),
rewrittenProducer.getOutput().get(1));
+ Assertions.assertEquals(map.getDataType(),
rewrittenProducer.getOutput().get(1).getDataType());
+ Assertions.assertSame(consumer,
rewrittenSort.getOrderKeys().get(0).getExpr());
}
}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/CTEContextTest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/CTEContextTest.java
new file mode 100644
index 00000000000..5915a3dda4c
--- /dev/null
+++ b/fe/fe-core/src/test/java/org/apache/doris/nereids/CTEContextTest.java
@@ -0,0 +1,95 @@
+// 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;
+
+import org.apache.doris.nereids.trees.expressions.Alias;
+import org.apache.doris.nereids.trees.expressions.CTEId;
+import org.apache.doris.nereids.trees.expressions.literal.IntegerLiteral;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.RelationId;
+import org.apache.doris.nereids.trees.plans.logical.LogicalOneRowRelation;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+import org.apache.doris.qe.AutoCloseConnectContext;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.qe.GlobalVariable;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class CTEContextTest {
+ @Test
+ public void testCaseFoldedNameLookupAndBoundIdLookup() {
+ int originalMode = GlobalVariable.lowerCaseTableNames;
+ try (AutoCloseConnectContext ignored = new AutoCloseConnectContext(new
ConnectContext())) {
+ for (int mode : ImmutableList.of(0, 1, 2)) {
+ GlobalVariable.lowerCaseTableNames = mode;
+ CTEContext first = context(1, "c", 1, new CTEContext());
+ CTEContext second = context(2, "C", 2, first);
+ Assertions.assertSame(mode == 0 ? first : second,
second.findCTEContext("c").get());
+ Assertions.assertSame(second,
second.findCTEContext("C").get());
+ Assertions.assertSame(first, second.findCTEContext(new
CTEId(1)).get());
+ Assertions.assertSame(second, second.findCTEContext(new
CTEId(2)).get());
+ Assertions.assertSame(first.getAnalyzedCTEPlan("c").get(),
+ second.getAnalyzedCTEPlan(new CTEId(1)).get());
+ Assertions.assertFalse(first.findCTEContext(new
CTEId(2)).isPresent());
+ Assertions.assertFalse(second.findCTEContext(new
CTEId(99)).isPresent());
+ }
+ } finally {
+ GlobalVariable.lowerCaseTableNames = originalMode;
+ }
+ }
+
+ @Test
+ public void testIdIndexSeesBindingUpdatesAndNearestScope() {
+ CTEContext outer = context(10, "source", 1, new CTEContext());
+ CTEContext inner = context(11, "source", 2, outer);
+ Assertions.assertSame(outer, inner.findCTEContext(new
CTEId(10)).get());
+ LogicalPlan replacement = context(12, "replacement", 3, new
CTEContext())
+ .getAnalyzedCTEPlan("replacement").get();
+ outer.setAnalyzedPlan(replacement);
+ Assertions.assertSame(replacement, inner.getAnalyzedCTEPlan(new
CTEId(10)).get());
+ Assertions.assertSame(inner, inner.findCTEContext("source").get());
+ CTEContext anchored = context(10, "source", 4, outer);
+ Assertions.assertSame(anchored, anchored.findCTEContext(new
CTEId(10)).get());
+ Assertions.assertNotSame(replacement, anchored.getAnalyzedCTEPlan(new
CTEId(10)).get());
+ }
+
+ @Test
+ public void testRecursiveBindingAndUnknownId() {
+ CTEId id = new CTEId(20);
+ CTEContext recursive = new CTEContext(id, "recursive_source",
ImmutableList.of());
+ Assertions.assertSame(recursive, recursive.findCTEContext(id).get());
+ Assertions.assertFalse(recursive.getAnalyzedCTEPlan(id).isPresent());
+ Assertions.assertFalse(recursive.findCTEContext(new
CTEId(21)).isPresent());
+ LogicalPlan analyzed = context(22, "recursive_source", 1, new
CTEContext())
+ .getAnalyzedCTEPlan("recursive_source").get();
+ recursive.setAnalyzedPlan(analyzed);
+ Assertions.assertSame(analyzed,
recursive.getAnalyzedCTEPlan(id).get());
+ }
+
+ private CTEContext context(int id, String name, int value, CTEContext
previous) {
+ LogicalSubQueryAlias<Plan> alias = new LogicalSubQueryAlias<>(name,
+ new LogicalOneRowRelation(new RelationId(value),
+ ImmutableList.of(new Alias(new IntegerLiteral(value),
"x"))));
+ CTEContext context = new CTEContext(new CTEId(id), alias, previous);
+ context.setAnalyzedPlan(alias);
+ return context;
+ }
+}
diff --git
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTETest.java
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTETest.java
index 36e86195ceb..e4c59b750f9 100644
---
a/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTETest.java
+++
b/fe/fe-core/src/test/java/org/apache/doris/nereids/rules/analysis/AnalyzeCTETest.java
@@ -32,11 +32,15 @@ import
org.apache.doris.nereids.rules.rewrite.UnCorrelatedApplyFilter;
import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
import org.apache.doris.nereids.trees.expressions.functions.scalar.Nullable;
import org.apache.doris.nereids.trees.plans.commands.ExplainCommand;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer;
+import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer;
import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
import org.apache.doris.nereids.util.MemoPatternMatchSupported;
import org.apache.doris.nereids.util.MemoTestUtils;
import org.apache.doris.nereids.util.PlanChecker;
+import org.apache.doris.qe.GlobalVariable;
import org.apache.doris.qe.OriginStatement;
import org.apache.doris.utframe.TestWithFeService;
@@ -133,6 +137,54 @@ public class AnalyzeCTETest extends TestWithFeService
implements MemoPatternMatc
Assertions.assertTrue(planner.getCascadesContext().isLeadingDisableJoinReorder());
}
+ @Test
+ public void testCaseSensitiveCteProducerBindings() {
+ assertCaseCollidingCteProducerBindings(0);
+ }
+
+ @Test
+ public void testLowercaseCteProducerBindings() {
+ assertCaseCollidingCteProducerBindings(1);
+ }
+
+ @Test
+ public void testCaseInsensitiveCteProducerBindings() {
+ assertCaseCollidingCteProducerBindings(2);
+ }
+
+ private void assertCaseCollidingCteProducerBindings(int mode) {
+ int originalMode = GlobalVariable.lowerCaseTableNames;
+ try {
+ GlobalVariable.lowerCaseTableNames = mode;
+ for (String sql : ImmutableList.of(
+ "WITH c AS (SELECT 1 AS x), C AS (SELECT x + 1 AS y FROM
c) SELECT y FROM C",
+ "WITH c AS (SELECT 1 AS x), C AS (SELECT x + 1 AS y FROM
c), "
+ + "next_cte AS (SELECT y + 1 AS z FROM C) SELECT z
FROM next_cte",
+ "WITH c AS (SELECT 1 AS x), C AS (SELECT x + 1 AS y FROM
c) "
+ + "SELECT y FROM C UNION ALL SELECT y FROM C")) {
+ LogicalCTEAnchor<?, ?> root = (LogicalCTEAnchor<?, ?>)
PlanChecker.from(connectContext)
+ .analyze(sql).getPlan().child(0);
+ LogicalCTEProducer<?> first = (LogicalCTEProducer<?>)
root.left();
+ LogicalCTEProducer<?> second = (LogicalCTEProducer<?>)
root.child(1).child(0);
+ Assertions.assertEquals("x",
first.getOutput().get(0).getName(), "mode=" + mode);
+ Assertions.assertEquals("y",
second.getOutput().get(0).getName(), "mode=" + mode);
+ Assertions.assertNotEquals(first.getCteId(),
second.getCteId());
+ Assertions.assertTrue(first.child().collectToList(p -> p
instanceof LogicalCTEConsumer).isEmpty());
+ LogicalCTEConsumer dependency =
second.child().<LogicalCTEConsumer>collectToList(
+ p -> p instanceof LogicalCTEConsumer).get(0);
+ Assertions.assertEquals(first.getCteId(),
dependency.getCteId());
+ Assertions.assertTrue(first.getOutput().contains(
+
dependency.getProducerSlot(dependency.getOutput().get(0))));
+ StatementContext context =
MemoTestUtils.createStatementContext(connectContext, sql);
+ PhysicalPlan plan = new
NereidsPlanner(context).planWithLock(parser.parseSingle(sql),
+ PhysicalProperties.ANY);
+ new PhysicalPlanTranslator(new
PlanTranslatorContext()).translatePlan(plan);
+ }
+ } finally {
+ GlobalVariable.lowerCaseTableNames = originalMode;
+ }
+ }
+
@Test
public void testCTEInHavingAndSubquery() {
diff --git
a/regression-test/data/external_table_p0/iceberg/test_iceberg_spatial_v3.out
b/regression-test/data/external_table_p0/iceberg/test_iceberg_spatial_v3.out
index 081fc931369..15ac9b119d5 100644
--- a/regression-test/data/external_table_p0/iceberg/test_iceberg_spatial_v3.out
+++ b/regression-test/data/external_table_p0/iceberg/test_iceberg_spatial_v3.out
@@ -510,3 +510,102 @@ POINT (1 2)
0101000000000000000000F03F0000000000000040
2 false 1 ["ordinary-key"] true false 1
["ordinary-key"] true false true 10 false true 11
3 true \N \N true false 0 [] true true
true \N false true empty-control
+-- !spatial_forwarded_nulls --
+0 false 0 true false 0 true ["0"] true ["0"]
true 2 0 true true 2 0 true true
+1 false 1 true false 1 true ["1"] true ["1"]
true 2 1 true true 2 1 true true
+10 false 10 true false 10 true ["10"] true ["10"]
true 2 10 true true 2 10 true true
+11 false 11 true false 11 true ["11"] true ["11"]
true 2 11 true true 2 11 true true
+12 false 12 true false 12 true ["12"] true ["12"]
true 2 12 true true 2 12 true true
+2 false 2 true false 2 true ["2"] true ["2"]
true 2 2 true true 2 2 true true
+20 false 20 true false 20 true ["20"] true ["20"]
true 2 20 true true 2 20 true true
+21 false 21 true false 21 true ["21"] true ["21"]
true 2 21 true true 2 21 true true
+22 false 22 true false 22 true ["22"] true ["22"]
true 2 22 true true 2 22 true true
+30 false 30 true false 30 true ["30"] true ["30"]
true 2 30 true true 2 30 true true
+31 false 31 true false 31 true ["31"] true ["31"]
true 2 31 true true 2 31 true true
+32 false 32 true false 32 true ["32"] true ["32"]
true 2 32 true true 2 32 true true
+40 false 40 true false 40 true ["40"] true ["40"]
true 2 40 true true 2 40 true true
+41 false 41 true false 41 true ["41"] true ["41"]
true 2 41 true true 2 41 true true
+42 false 42 true false 42 true ["42"] true ["42"]
true 2 42 true true 2 42 true true
+50 false 50 true false 50 true ["50"] true ["50"]
true 2 50 true true 2 50 true true
+51 false 51 true false 51 true ["51"] true ["51"]
true 2 51 true true 2 51 true true
+52 false 52 true false 52 true ["52"] true ["52"]
true 2 52 true true 2 52 true true
+
+-- !spatial_forwarded_shared_values --
+6 6
+
+-- !spatial_forwarded_shared_evaluation --
+0 2 1
+1 2 1
+2 2 1
+
+-- !case_colliding_producers_0 --
+2
+
+-- !case_colliding_chain_0 --
+3
+
+-- !case_colliding_shared_0 --
+2
+2
+
+-- !case_forwarded_values_0 --
+0 1 0 0 0 0 1
+1 1 1 1 1 1 1
+10 1 10 10 10 10 1
+11 1 11 11 11 11 1
+12 1 12 12 12 12 1
+2 1 2 2 2 2 1
+20 2 20 20 20 20 2
+21 2 21 21 21 21 2
+22 2 22 22 22 22 2
+
+-- !case_colliding_producers_1 --
+3
+
+-- !case_colliding_chain_1 --
+4
+
+-- !case_colliding_shared_1 --
+3
+3
+
+-- !case_forwarded_values_1 --
+100 1 100 100 100 100 1
+101 1 101 101 101 101 1
+102 1 102 102 102 102 1
+110 1 110 110 110 110 1
+111 1 111 111 111 111 1
+112 1 112 112 112 112 1
+120 2 120 120 120 120 2
+121 2 121 121 121 121 2
+122 2 122 122 122 122 2
+
+-- !case_colliding_producers_2 --
+4
+
+-- !case_colliding_chain_2 --
+5
+
+-- !case_colliding_shared_2 --
+4
+4
+
+-- !case_forwarded_values_2 --
+200 1 200 200 200 200 1
+201 1 201 201 201 201 1
+202 1 202 202 202 202 1
+210 1 210 210 210 210 1
+211 1 211 211 211 211 1
+212 1 212 212 212 212 1
+220 2 220 220 220 220 2
+221 2 221 221 221 221 2
+222 2 222 222 222 222 2
+
+-- !spatial_project_cache_scope --
+0 0 0 0 0 0 false false false false
false true true true true true
+1 1 1 1 1 1 false false false false
false true true true true true
+10 10 10 10 10 10 false false false false
false true true true true true
+11 11 11 11 11 11 false false false false
false true true true true true
+12 12 12 12 12 12 false false false false
false true true true true true
+2 2 2 2 2 2 false false false false
false true true true true true
+
diff --git a/regression-test/data/nereids_rules_p0/cte/test_cte_name_reuse.out
b/regression-test/data/nereids_rules_p0/cte/test_cte_name_reuse.out
index 52966eaa688..0dfd78ad692 100644
--- a/regression-test/data/nereids_rules_p0/cte/test_cte_name_reuse.out
+++ b/regression-test/data/nereids_rules_p0/cte/test_cte_name_reuse.out
@@ -8,3 +8,13 @@
-- !reuse_name_with_self_outer_cte --
1 1
+-- !case_colliding_producers --
+2
+
+-- !case_colliding_chain --
+3
+
+-- !case_colliding_shared_producer --
+2
+2
+
diff --git
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_spatial_v3.groovy
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_spatial_v3.groovy
index b45a4b9ffe5..7fb490afe54 100644
---
a/regression-test/suites/external_table_p0/iceberg/test_iceberg_spatial_v3.groovy
+++
b/regression-test/suites/external_table_p0/iceberg/test_iceberg_spatial_v3.groovy
@@ -2113,4 +2113,167 @@ public class CreateIcebergSpatialV3Table {
"""select max(id) + ${target.offset}, 1, array(cast(max(id) as
string)), true
from geometry_values""")
}
+
+ // Forwarded runtime constructors must retain ordinary values and NULL
container boundaries.
+ sql "drop table if exists spatial_forwarded_nulls"
+ sql """create table spatial_forwarded_nulls (
+ id int, g struct<k:int,shape:geometry>, gg
struct<k:int,shape:geography>,
+ gm map<string,geometry>, ggm map<string,geography>,
+ ga array<struct<k:int,shape:geometry>>, gga
array<struct<k:int,shape:geography>>
+ ) properties ('format-version'='3', 'write.format.default'='parquet')"""
+ ["derived", "cte", "chained", "outer_cte", "nested",
"shadowed"].eachWithIndex { mode, index ->
+ String values = """select id,
+ named_struct('k',id,'shape',cast(null as int)) s,
+ map(cast(id as string),cast(null as int)) m,
+ array(named_struct('k',id,'shape',cast(null as int)),
+ cast(null as struct<k:int,shape:int>)) a
+ from (select cast(number + ${index * 10} as int) id from
numbers('number'='3')) n"""
+ String query = mode == "derived"
+ ? "select id,s,s,m,m,a,a from (select * from (${values}) p) q
order by id limit 3"
+ : mode == "cte"
+ ? "with source(row_id,payload,entries,items) as (${values}) " +
+ "select row_id,payload,payload,entries,entries,items,items
from source"
+ : "with source as (${values}), forwarded as (select a,m,id,s
from source) " +
+ "select id,s,s,m,m,a,a from forwarded where id >= 0"
+ if (mode == "shadowed") {
+ sql """with source as (${values}) insert into
spatial_forwarded_nulls
+ with source as (select * from source) select id,s,s,m,m,a,a
from source"""
+ } else if (mode == "outer_cte") {
+ sql """with source as (${values}) insert into
spatial_forwarded_nulls
+ select id,s,s,m,m,a,a from source"""
+ } else if (mode == "nested") {
+ sql """insert into spatial_forwarded_nulls with source as (
+ with inner_source as (${values}) select * from inner_source)
+ select id,s,s,m,m,a,a from source"""
+ } else {
+ sql "insert into spatial_forwarded_nulls ${query}"
+ }
+ }
+ sql "refresh table spatial_forwarded_nulls"
+ order_qt_spatial_forwarded_nulls """select id,g is null,g.k,g.shape is
null,gg is null,gg.k,gg.shape is null,
+ map_keys(gm),gm[cast(id as string)] is
null,map_keys(ggm),ggm[cast(id as string)] is null,
+ size(ga),ga[1].k,ga[1].shape is null,ga[2] is null,
+ size(gga),gga[1].k,gga[1].shape is null,gga[2] is null
+ from spatial_forwarded_nulls order by id"""
+
+ // Keep one runtime key evaluation for spatial and ordinary outputs of a
shared CTE.
+ sql "drop table if exists spatial_forwarded_shared_cte"
+ sql """create table spatial_forwarded_shared_cte (
+ id int, g map<string,geometry>, ordinary map<string,int>
+ ) properties ('format-version'='3', 'write.format.default'='parquet')"""
+ def originalCteInlineMode = sql("show variables like
'cte_inline_mode'")[0][1]
+ def originalCteMaterialize = sql("show variables like
'enable_cte_materialize'")[0][1]
+ sql "set enable_cte_materialize = true"
+ sql "set cte_inline_mode = -1"
+ try {
+ sql """insert into spatial_forwarded_shared_cte with source as (
+ select cast(number as int) id,map(cast(rand() as string),cast(null
as int)) m
+ from numbers('number'='3'))
+ select id,m,m from source union all select id,m,m from source"""
+ } finally {
+ sql "set cte_inline_mode = ${originalCteInlineMode}"
+ sql "set enable_cte_materialize = ${originalCteMaterialize}"
+ }
+ sql "refresh table spatial_forwarded_shared_cte"
+ qt_spatial_forwarded_shared_values """select count(*),sum(case when
map_keys(g) = map_keys(ordinary)
+ and size(g) = 1 and element_at(map_values(g),1) is null then 1
else 0 end)
+ from spatial_forwarded_shared_cte"""
+ order_qt_spatial_forwarded_shared_evaluation """select
id,count(*),count(distinct element_at(map_keys(g),1))
+ from spatial_forwarded_shared_cte group by id order by id"""
+ for (String invalid : ["1", "cast(cast(null as geometry) as int)"]) {
+ test {
+ sql """insert into spatial_forwarded_nulls(id,gm)
+ select id,m from (select cast(number as int) id,
+ map(cast(number as string),${invalid}) m from
numbers('number'='3')) q"""
+ exception (invalid == "1" ? "Spatial connector write cannot
convert input column" : "can not cast")
+ }
+ }
+
+ sql "drop table if exists spatial_case_forwarding"
+ sql """create table spatial_case_forwarding (
+ id int, g struct<k:int,shape:geometry>, gg
struct<k:int,shape:geography>,
+ g_repeat struct<k:int,shape:geometry>, ordinary struct<k:int,shape:int>
+ ) properties ('format-version'='3', 'write.format.default'='parquet')"""
+
+ // Bound identities must survive folded names in plain WITH scopes and
anchored INSERT sources.
+ for (int mode : [0, 1, 2]) {
+ String caseCatalog = "test_iceberg_cte_case_${mode}"
+ sql "drop catalog if exists ${caseCatalog}"
+ sql """create catalog ${caseCatalog} properties (
+ 'type'='iceberg', 'iceberg.catalog.type'='rest',
+ 'uri'='http://${externalEnvIp}:${restPort}',
+ 's3.endpoint'='http://${externalEnvIp}:${minioPort}',
+ 's3.access_key'='admin', 's3.secret_key'='password',
's3.region'='us-east-1',
+ 'only_test_lower_case_table_names'='${mode}')"""
+ sql "switch ${caseCatalog}"
+ sql "use ${dbName}"
+ try {
+ "qt_case_colliding_producers_${mode}"("""with c as (select ${mode
+ 1} as x),
+ C as (select x + 1 as y from c) select y from C""")
+ "qt_case_colliding_chain_${mode}"("""with c as (select ${mode + 1}
as x),
+ C as (select x + 1 as y from c), next_cte as (select y + 1 as
z from C)
+ select z from next_cte""")
+ "order_qt_case_colliding_shared_${mode}"("""with c as (select
${mode + 1} as x),
+ C as (select x + 1 as y from c) select y from C union all
select y from C""")
+
+ String definitions = """with c as (
+ select cast(number + ${mode * 100} as int) id,
+ named_struct('k',cast(number + ${mode * 100} as
int),'shape',cast(null as int)) s
+ from numbers('number'='3')), C as (select id,s from c)"""
+ sql """${definitions} insert into spatial_case_forwarding select
id,s,s,s,s from C"""
+ definitions = """with c as (
+ select cast(number + ${mode * 100 + 10} as int) id,
+ named_struct('k',cast(number + ${mode * 100 + 10} as
int),'shape',cast(null as int)) s
+ from numbers('number'='3')), C as (select id,s from c)"""
+ sql """insert into spatial_case_forwarding ${definitions} select
id,s,s,s,s from C"""
+ definitions = """with c as (
+ select cast(number + ${mode * 100 + 20} as int) id,
+ named_struct('k',cast(number + ${mode * 100 + 20} as
int),'shape',cast(null as int)) s
+ from numbers('number'='3')), C as (select id,s from c)"""
+ sql """insert into spatial_case_forwarding ${definitions}
+ select id,s,s,s,s from C union all select id,s,s,s,s from C"""
+ sql "refresh table spatial_case_forwarding"
+ "order_qt_case_forwarded_values_${mode}"("""select
id,count(*),min(g.k),min(gg.k),
+ min(g_repeat.k),min(ordinary.k),sum(case when g is not null
and gg is not null
+ and g_repeat is not null and ordinary is not null and
g.shape is null
+ and gg.shape is null and g_repeat.shape is null and
ordinary.shape is null then 1 else 0 end)
+ from spatial_case_forwarding where id between ${mode * 100}
and ${mode * 100 + 99}
+ group by id order by id""")
+ for (String invalid : ["1", "cast(cast(null as geometry) as
int)"]) {
+ test {
+ sql """with c as (select named_struct('k',cast(number as
int),'shape',${invalid}) s
+ from numbers('number'='1')), C as (select s from c)
+ insert into spatial_case_forwarding(g) select s from
C"""
+ exception (invalid == "1" ? "Spatial connector write
cannot convert input column" : "can not cast")
+ }
+ }
+ } finally {
+ sql "switch ${catalogName}"
+ sql "use ${dbName}"
+ }
+ }
+
+ // Passthrough slots retain ExprIds across projects; same-typed aliases
must stay in their own scope.
+ sql "drop table if exists spatial_project_cache_scope"
+ sql """create table spatial_project_cache_scope (
+ id int, g1 struct<k:int,shape:geometry>, g2
struct<k:int,shape:geometry>,
+ gg1 struct<k:int,shape:geography>, gg2 struct<k:int,shape:geography>,
+ ordinary struct<k:int,shape:int>
+ ) properties ('format-version'='3', 'write.format.default'='parquet')"""
+ for (boolean aliasFirst : [false, true]) {
+ int offset = aliasFirst ? 10 : 0
+ String first = aliasFirst ? "renamed" : "s"
+ String second = aliasFirst ? "s" : "renamed"
+ sql """insert into spatial_project_cache_scope
+ select id,${first},${second},${first},${second},s from (
+ select id,s,s as renamed from (
+ select cast(number + ${offset} as int) id,
+ named_struct('k',cast(number + ${offset} as
int),'shape',cast(null as int)) s
+ from numbers('number'='3')) inner_q) outer_q"""
+ }
+ sql "refresh table spatial_project_cache_scope"
+ order_qt_spatial_project_cache_scope """select
id,g1.k,g2.k,gg1.k,gg2.k,ordinary.k,
+ g1 is null,g2 is null,gg1 is null,gg2 is null,ordinary is null,
+ g1.shape is null,g2.shape is null,gg1.shape is null,gg2.shape is
null,ordinary.shape is null
+ from spatial_project_cache_scope order by id"""
}
diff --git
a/regression-test/suites/nereids_rules_p0/cte/test_cte_name_reuse.groovy
b/regression-test/suites/nereids_rules_p0/cte/test_cte_name_reuse.groovy
index c146763853e..6f58e0ea566 100644
--- a/regression-test/suites/nereids_rules_p0/cte/test_cte_name_reuse.groovy
+++ b/regression-test/suites/nereids_rules_p0/cte/test_cte_name_reuse.groovy
@@ -56,4 +56,18 @@ suite("test_cte_name_reuse") {
qt_reuse_name_with_self_outer_cte """
with a as (with a as (select * from test_cte_name_reuse) select * from
a) select * from a;
"""
+
+ qt_case_colliding_producers """
+ with c as (select 1 as x), C as (select x + 1 as y from c) select y
from C
+ """
+
+ qt_case_colliding_chain """
+ with c as (select 1 as x), C as (select x + 1 as y from c),
+ next_cte as (select y + 1 as z from C) select z from next_cte
+ """
+
+ order_qt_case_colliding_shared_producer """
+ with c as (select 1 as x), C as (select x + 1 as y from c)
+ select y from C union all select y from C
+ """
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]