Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
englefly committed Dec 17, 2024
1 parent 296fa02 commit 95ce8c0
Show file tree
Hide file tree
Showing 19 changed files with 364 additions and 27 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@ public class NereidsPlanner extends Planner {
private double cost = 0;
private LogicalPlanAdapter logicalPlanAdapter;

private CteExtractor cteExtractor;

public NereidsPlanner(StatementContext statementContext) {
this.statementContext = statementContext;
}
Expand Down Expand Up @@ -264,6 +266,9 @@ protected Plan planWithoutLock(
statementContext.getConnectContext().getExecutor().getSummaryProfile().setNereidsRewriteTime();
}

if (ConnectContext.get() != null && ConnectContext.get().getSessionVariable().enableCommonCte) {
extractCommonCTE();
}
if (explainLevel == ExplainLevel.REWRITTEN_PLAN || explainLevel == ExplainLevel.ALL_PLAN) {
rewrittenPlan = cascadesContext.getRewritePlan();
if (explainLevel == ExplainLevel.REWRITTEN_PLAN) {
Expand All @@ -286,8 +291,6 @@ protected Plan planWithoutLock(

setRuntimeFilterWaitTimeByTableRowCountAndType();

extractCommonCTE();

optimize();
if (statementContext.getConnectContext().getExecutor() != null) {
statementContext.getConnectContext().getExecutor().getSummaryProfile().setNereidsOptimizeTime();
Expand Down Expand Up @@ -325,8 +328,12 @@ protected LogicalPlan preprocess(LogicalPlan logicalPlan) {
}

private void extractCommonCTE() {
CteExtractor commonCTE = new CteExtractor((AbstractLogicalPlan) cascadesContext.getRewritePlan());
commonCTE.execute();
CteExtractor commonCTE = new CteExtractor(
(AbstractLogicalPlan) cascadesContext.getRewritePlan(),
cascadesContext);
List<Plan> plans = commonCTE.execute();
cascadesContext.setRewritePlan(plans.get(0));
cteExtractor = commonCTE;
}

/**
Expand Down Expand Up @@ -666,6 +673,7 @@ public String getExplainString(ExplainOptions explainOptions) {
break;
case REWRITTEN_PLAN:
plan = rewrittenPlan.treeString();
plan += "\n common cte info \n" + cteExtractor;
break;
case OPTIMIZED_PLAN:
plan = "cost = " + cost + "\n" + optimizedPlan.treeString() + mvSummary;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
package org.apache.doris.nereids.commonCTE;

import org.apache.doris.nereids.trees.expressions.CTEId;
import org.apache.doris.nereids.trees.expressions.Slot;
import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.AbstractLogicalPlan;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEConsumer;
import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
import org.apache.doris.nereids.trees.plans.visitor.DefaultPlanRewriter;
import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultimap;

import java.util.ArrayList;
import java.util.List;

public class ConsumerRewriter extends DefaultPlanRewriter<ConsumerRewriterContext> {
public static final ConsumerRewriter INSTANCE = new ConsumerRewriter();
@Override
public Plan visit(Plan plan, ConsumerRewriterContext context) {
if (context.isTarget(plan)) {
context.producer.getOutput();
plan.getOutput();
ImmutableMap.Builder<Slot, Slot> cToPBuilder = ImmutableMap.builder();
ImmutableMultimap.Builder<Slot, Slot> pToCBuilder = ImmutableMultimap.builder();
for (int i = 0; i< context.producer.getOutput().size(); i++) {
cToPBuilder.put(plan.getOutput().get(i), context.producer.getOutput().get(i));
pToCBuilder.put(context.producer.getOutput().get(i), plan.getOutput().get(i));
}
return new LogicalCTEConsumer(StatementScopeIdGenerator.newRelationId(), context.cteId,
"comm_cte_" + context.cteId.asInt(), cToPBuilder.build(), pToCBuilder.build());
}
return visitChildren(this, plan, context);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package org.apache.doris.nereids.commonCTE;

import org.apache.doris.nereids.trees.expressions.CTEId;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.AbstractLogicalPlan;

import java.util.List;

public class ConsumerRewriterContext {
private final List<Plan> targets;
public Plan producer;
public final CTEId cteId;

public ConsumerRewriterContext(List<Plan> targets, Plan producer, CTEId cteId) {
this.targets = targets;
this.producer = producer;
this.cteId = cteId;
}
public boolean isTarget(Plan plan) {
return targets.contains(plan);
}
}
Original file line number Diff line number Diff line change
@@ -1,43 +1,112 @@
package org.apache.doris.nereids.commonCTE;

import org.apache.doris.nereids.CascadesContext;
import org.apache.doris.nereids.rules.analysis.CheckAfterRewrite;
import org.apache.doris.nereids.rules.exploration.mv.ComparisonResult;
import org.apache.doris.nereids.rules.exploration.mv.LogicalCompatibilityContext;
import org.apache.doris.nereids.rules.exploration.mv.MaterializationContext;
import org.apache.doris.nereids.rules.exploration.mv.StructInfo;
import org.apache.doris.nereids.rules.exploration.mv.mapping.RelationMapping;
import org.apache.doris.nereids.rules.exploration.mv.mapping.SlotMapping;
import org.apache.doris.nereids.trees.expressions.CTEId;
import org.apache.doris.nereids.trees.expressions.StatementScopeIdGenerator;
import org.apache.doris.nereids.trees.plans.AbstractPlan;
import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.AbstractLogicalPlan;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEAnchor;
import org.apache.doris.nereids.trees.plans.logical.LogicalCTEProducer;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.BitSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

public class CteExtractor {
private AbstractLogicalPlan plan;
private Map<Plan, TableSignature> anchorToSignature = new HashMap<>();
private Map<TableSignature, List<Plan>> signatureToAnchorList = new HashMap<>();
private final CascadesContext cascadesContext;
private final AbstractLogicalPlan plan;
private final Map<AbstractLogicalPlan, TableSignature> planToSignature = new HashMap<>();
private final Map<TableSignature, List<AbstractLogicalPlan>> signatureToPlanList = new HashMap<>();

public CteExtractor(AbstractLogicalPlan plan) {
public CteExtractor(AbstractLogicalPlan plan, CascadesContext cascadesContext) {
this.plan = plan;
this.cascadesContext = cascadesContext;
}

public AbstractLogicalPlan execute() {
public List<Plan> execute() {
sign();
return plan;
return extract();
}

private void sign() {
SignatureVisitor visitor = new SignatureVisitor();
visitor.visit(plan, anchorToSignature);
extract();
visitor.visit(plan, planToSignature);
}

private void extract() {
List<TableSignature> a = anchorToSignature.values().stream().collect(Collectors.toList());
public List<Plan> extract() {
for (AbstractLogicalPlan plan : planToSignature.keySet()) {
TableSignature signature = planToSignature.get(plan);
List<AbstractLogicalPlan> plans = signatureToPlanList.computeIfAbsent(signature, key -> new ArrayList<>());
plans.add(plan);
}
TableSignature targetSignature = null;
for (TableSignature signature : signatureToPlanList.keySet()) {
if (signature.isContainsAggregation()) {
targetSignature = signature;
}
}
if (targetSignature != null) {
List<AbstractLogicalPlan> targetPlans = signatureToPlanList.get(targetSignature);
Plan target0 = targetPlans.get(0);
Optional<StructInfo> optStruct0 = MaterializationContext.constructStructInfo(target0, target0, cascadesContext, new BitSet());
StructInfo viewStructInfo = optStruct0.get();
Plan target1 = targetPlans.get(1);
Optional<StructInfo> optStruct1 = MaterializationContext.constructStructInfo(target1, target1, cascadesContext, new BitSet());
StructInfo queryStructInfo = optStruct1.get();
List<RelationMapping> queryToViewTableMappings = RelationMapping.generate(optStruct0.get().getRelations(),
optStruct1.get().getRelations());
RelationMapping queryToViewTableMapping = queryToViewTableMappings.get(0);
SlotMapping queryToViewSlotMapping = SlotMapping.generate(queryToViewTableMapping);
SlotMapping viewToQuerySlotMapping = queryToViewSlotMapping.inverse();
LogicalCompatibilityContext compatibilityContext = LogicalCompatibilityContext.from(
queryToViewTableMapping, viewToQuerySlotMapping, optStruct0.get(), optStruct1.get());
ComparisonResult comparisonResult = StructInfo.isGraphLogicalEquals(queryStructInfo, viewStructInfo,
compatibilityContext);
if (!comparisonResult.isInvalid()) {
CTEId cteId = StatementScopeIdGenerator.newCTEId();
LogicalCTEProducer producer = new LogicalCTEProducer(cteId, target0);
ConsumerRewriterContext context = new ConsumerRewriterContext(Lists.newArrayList(target0, target1), producer, cteId);
Plan rewritten = plan.accept(ConsumerRewriter.INSTANCE, context);
AbstractLogicalPlan root = new LogicalCTEAnchor(cteId, producer, rewritten);
CheckAfterRewrite checker = new CheckAfterRewrite();
checker.checkValidation(root);
return Lists.newArrayList(root);
}
System.out.println(queryToViewTableMappings);
}
return Lists.newArrayList();
}

private void checkPlanValidation(Plan plan) {

for (Plan plan : anchorToSignature.keySet()) {
TableSignature signature = anchorToSignature.get(plan);
List<Plan> plans = signatureToAnchorList.computeIfAbsent(signature, key -> new ArrayList<>());
plans.add(plan);
}

@Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (TableSignature signature : signatureToPlanList.keySet()) {
sb.append(String.format("%s\n", signature.toString()));
sb.append(" ");
for (AbstractLogicalPlan plan : signatureToPlanList.get(signature)) {
sb.append(plan.getId()).append(" ");
}
sb.append("\n");
}
return sb.toString();
}


Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package org.apache.doris.nereids.commonCTE;

import org.apache.doris.nereids.trees.plans.Plan;
import org.apache.doris.nereids.trees.plans.logical.AbstractLogicalPlan;
import org.apache.doris.nereids.trees.plans.logical.LogicalAggregate;
import org.apache.doris.nereids.trees.plans.logical.LogicalCatalogRelation;
import org.apache.doris.nereids.trees.plans.logical.LogicalFilter;
Expand All @@ -12,11 +13,11 @@

import java.util.Map;

public class SignatureVisitor extends DefaultPlanVisitor <TableSignature, Map<Plan, TableSignature>>{
public class SignatureVisitor extends DefaultPlanVisitor <TableSignature, Map<AbstractLogicalPlan, TableSignature>>{

@Override
public TableSignature visitLogicalCatalogRelation(LogicalCatalogRelation relation,
Map<Plan, TableSignature> signatureMap) {
Map<AbstractLogicalPlan, TableSignature> signatureMap) {
TableSignature signature = new TableSignature(true, false,
ImmutableSet.of(relation.getTable().getId()));
signatureMap.put(relation, signature);
Expand All @@ -25,7 +26,7 @@ public TableSignature visitLogicalCatalogRelation(LogicalCatalogRelation relatio

@Override
public TableSignature visitLogicalFilter(LogicalFilter<? extends Plan> filter,
Map<Plan, TableSignature> signatureMap) {
Map<AbstractLogicalPlan, TableSignature> signatureMap) {
TableSignature childSignature = filter.child().accept(this, signatureMap);
if (filter.child() instanceof LogicalAggregate) {
return TableSignature.EMPTY;
Expand All @@ -36,7 +37,7 @@ public TableSignature visitLogicalFilter(LogicalFilter<? extends Plan> filter,

@Override
public TableSignature visitLogicalJoin(LogicalJoin<? extends Plan, ? extends Plan> join,
Map<Plan, TableSignature> signatureMap) {
Map<AbstractLogicalPlan, TableSignature> signatureMap) {
TableSignature signature = TableSignature.EMPTY;
TableSignature leftSignature = join.left().accept(this, signatureMap);

Expand All @@ -56,7 +57,7 @@ public TableSignature visitLogicalJoin(LogicalJoin<? extends Plan, ? extends Pla

@Override
public TableSignature visitLogicalAggregate(LogicalAggregate<? extends Plan> aggregate,
Map<Plan, TableSignature> signatureMap) {
Map<AbstractLogicalPlan, TableSignature> signatureMap) {
TableSignature signature = TableSignature.EMPTY;
TableSignature childSignature = aggregate.child().accept(this, signatureMap);
if (childSignature != TableSignature.EMPTY) {
Expand All @@ -68,7 +69,7 @@ public TableSignature visitLogicalAggregate(LogicalAggregate<? extends Plan> agg

@Override
public TableSignature visitLogicalProject(LogicalProject<? extends Plan> project,
Map<Plan, TableSignature> signatureMap) {
Map<AbstractLogicalPlan, TableSignature> signatureMap) {
TableSignature childSignature = project.child().accept(this, signatureMap);
if (childSignature != TableSignature.EMPTY) {
signatureMap.put(project, childSignature);
Expand All @@ -77,7 +78,7 @@ public TableSignature visitLogicalProject(LogicalProject<? extends Plan> project
}

@Override
public TableSignature visit(Plan plan, Map<Plan, TableSignature> signatureMap) {
public TableSignature visit(Plan plan, Map<AbstractLogicalPlan, TableSignature> signatureMap) {
for (Plan child : plan.children()) {
child.accept(this, signatureMap);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -208,4 +208,14 @@ private void checkMatchIsUsedCorrectly(Plan plan) {
}
}
}

public void checkValidation(Plan plan) {
checkAllSlotReferenceFromChildren(plan);
checkUnexpectedExpression(plan);
checkMetricTypeIsUsedCorrectly(plan);
checkMatchIsUsedCorrectly(plan);
for (Plan child : plan.children()) {
checkValidation(child);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -196,6 +196,7 @@ public String toString() {
return Utils.toSqlString("LogicalCteConsumer[" + id.asInt() + "]",
"cteId", cteId,
"relationId", relationId,
"name", name);
"name", name,
"map", consumerToProducerOutputMap);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -228,7 +228,7 @@ public OlapTable getTable() {

@Override
public String toString() {
return Utils.toSqlString("LogicalOlapScan",
return Utils.toSqlString("LogicalOlapScan[" + id.asInt() + "]",
"qualified", qualifiedName(),
"indexName", getSelectedMaterializedIndexName().orElse("<index_not_selected>"),
"selectedIndexId", selectedIndexId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2214,6 +2214,13 @@ public void setIgnoreShapePlanNodes(String ignoreShapePlanNodes) {
)
public boolean enableCompressMaterialize = false;

@VariableMgr.VarAttr(
name = "enable_common_cte",
needForward = true, fuzzy = false,
varType = VariableAnnotation.EXPERIMENTAL
)
public boolean enableCommonCte = true;

@VariableMgr.VarAttr(
name = ENABLE_AGG_SPILL,
description = {"控制是否启用聚合算子落盘。默认为 false。",
Expand Down
17 changes: 17 additions & 0 deletions regression-test/data/query_p0/common_cte/common_cte.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
-- This file is automatically generated. You should know what you did if you want to edit this
-- !1 --
LogicalResultSink[168] ( outputExprs=[a#34] )
+--LogicalAggregate[166] ( groupByExpr=[a#34], outputExpr=[a#34], hasRepeat=false )
+--LogicalUnion ( qualifier=ALL, outputs=[a#34], regularChildrenOutputs=[[a#32], [b#33]], constantExprsList=[], hasPushedFilter=false )
|--LogicalAggregate[157] ( groupByExpr=[], outputExpr=[count(*) AS `a`#32], hasRepeat=false )
| +--LogicalProject[155] ( distinct=false, projects=[1 AS `1`#41] )
| +--LogicalOlapScan[129] ( qualified=internal.regression_test_query_p0_common_cte.lineitem, indexName=<index_not_selected>, selectedIndexId=1596500, preAgg=ON )
+--LogicalAggregate[160] ( groupByExpr=[], outputExpr=[count(*) AS `b`#33], hasRepeat=false )
+--LogicalProject[158] ( distinct=false, projects=[1 AS `1`#42] )
+--LogicalOlapScan[132] ( qualified=internal.regression_test_query_p0_common_cte.lineitem, indexName=<index_not_selected>, selectedIndexId=1596500, preAgg=ON )
common cte info
SPJG [1596499]
155 129 132 158
SPJG AGG [1596499]
157 160

25 changes: 25 additions & 0 deletions regression-test/suites/query_p0/common_cte/common_cte.groovy
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// 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.

suite("common_cte") {
qt_1 " explain rewritten plan select * from (select count() a from lineitem union all select count() b from lineitem) T"
}

set enable_common_cte=false;
explain physical plan
with x as (select count() a from lineitem)
select * from (select * from x union all select * from x) T;
Loading

0 comments on commit 95ce8c0

Please sign in to comment.