924060929 commented on code in PR #71224:
URL: https://github.com/apache/doris/pull/71224#discussion_r4778717415
##########
fe/fe-core/src/main/java/org/apache/doris/datasource/connector/converter/ConnectorSpatialWriteNormalizer.java:
##########
@@ -225,7 +256,225 @@ public static LogicalPlan normalize(List<Column> targets,
LogicalPlan source,
}
}
}
- 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;
+ private final 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) {
+ Pair<ExprId, DataType> key =
Pair.of(project.getProjects().get(ordinal).getExprId(), target);
+ Slot cached = appendedOutputs.get(key);
+ if (cached != null) {
+ // Earlier appends only widen this projection, so the cached
slot remains in scope.
+ Preconditions.checkState(project.getOutput().contains(cached));
Review Comment:
[P1] `appendedOutputs` is keyed only by `(ExprId, DataType)` without scoping
by `LogicalProject`, which causes an `IllegalStateException` when the same
`Slot` is forwarded across multiple `LogicalProject` layers and also aliased
for another same-typed spatial target.
Repro:
```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)) AS s FROM
base
) inner_q
) outer_q;
```
Trace (`s` keeps the same `ExprId` `#1` across all 3 projects; `renamed` has
`#2`):
1. Target `g1` (`s#1`): `inner_q` appends `s#10` and puts `(#1, target) ->
#10`; `outer_q` appends `s#11` and overwrites `(#1, target) -> #11`; top
project appends `s#12` and overwrites `(#1, target) -> #12`.
2. Target `g2` (`renamed#2`): top and `outer_q` miss `(#2, target)` and
recurse into `inner_q` on `s#1`. `inner_q` looks up `(#1, target)`, gets `#12`
(from the top project, not in `inner_q.getOutput()`), and fails
`Preconditions.checkState(project.getOutput().contains(cached))`.
Since `LogicalProject.withProjectsAndChild` preserves `project.getId()` via
`AbstractPlan.copyWithSameId`, keying `appendedOutputs` by `project.getId()` as
well (e.g., `Map<ObjectId, Map<Pair<ExprId, DataType>, Slot>>`) avoids
cross-layer collisions.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]