You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@doris.apache.org by GitBox <gi...@apache.org> on 2022/07/20 08:10:45 UTC

[GitHub] [doris] sohardforaname opened a new pull request, #11035: [Feature](nereids) support sub-query and alias for TPC-H

sohardforaname opened a new pull request, #11035:
URL: https://github.com/apache/doris/pull/11035

   # Proposed changes
   
   Issue Number: close #xxx
   
   ## Problem Summary:
   
   Support sub-query and alias for TPC-H,for example:
   select * from (select * from (T1) A join T2 as B on T1.id = T2.id) T;
   
   ## Checklist(Required)
   
   1. Does it affect the original behavior: (Yes)
   2. Has unit tests been added: (Yes)
   3. Has document been added or modified: (No)
   4. Does it need to update dependencies: (No)
   5. Are there any changes that cannot be rolled back: (No)
   
   ## Further comments
   
   If this is a relatively large or complex change, kick off the discussion at [dev@doris.apache.org](mailto:dev@doris.apache.org) by explaining why you chose the solution you did and what alternatives you considered, etc...
   


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931973043


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,39 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {
+        if (null != ctx.strictIdentifier()) {
+            String alias = ctx.strictIdentifier().getText();
+            if (null != ctx.identifierList()) {
+                throw new IllegalStateException("Do not implemented");
+                // List<String> colName = visitIdentifierSeq(ctx.identifierList().identifierSeq());
+                // TODO: multi-colName
+            } else {
+                return new LogicalSubQueryAlias<>(alias, plan);
+            }
+        }
+        return plan;
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        return applyAlias(ctx.tableAlias(), new UnboundRelation(tableId));
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        String alias = "__auto_generated_name__";
+        LogicalPlan query = visitQuery(ctx.query());
+        if (null != ctx.tableAlias().strictIdentifier()) {

Review Comment:
   strictIdentifier cannot be null



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode(child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(Plan node) {

Review Comment:
   why not use GroupPlan as parameter's type directly?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,39 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {
+        if (null != ctx.strictIdentifier()) {
+            String alias = ctx.strictIdentifier().getText();
+            if (null != ctx.identifierList()) {
+                throw new IllegalStateException("Do not implemented");

Review Comment:
   use ParseException instead of IllegalStateException



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/jobs/batch/FinalizeAnalyzeJob.java:
##########
@@ -0,0 +1,43 @@
+// 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.jobs.batch;
+
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.rules.analysis.EliminateAliasNode;
+
+import com.google.common.collect.ImmutableList;
+
+/**
+ * Job to eliminate the logical node of sub query and alias
+ */
+public class FinalizeAnalyzeJob extends BatchRulesJob {
+
+    /**
+     * constructor
+     * @param plannerContext ctx
+     */
+    public FinalizeAnalyzeJob(PlannerContext plannerContext) {
+        super(plannerContext);
+        rulesJob.addAll(ImmutableList.of(
+                bottomUpBatch(ImmutableList.of(
+                                new EliminateAliasNode()
+                        )
+                )
+        ));

Review Comment:
   ```suggestion
           rulesJob.addAll(ImmutableList.of(
                   bottomUpBatch(ImmutableList.of(new EliminateAliasNode()))
           ));
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,11 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalOlapScan, this == that should be true,
+        // because equals() can not divide UnboundRelation and the plan above.

Review Comment:
   this comment is not clear to describe the question. we need to explain that if one relation appear in plan more than once, we cannot distinguish them throw equals function, since equals function cannot use output info.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,39 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {

Review Comment:
   ```suggestion
       private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,11 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalOlapScan, this == that should be true,
+        // because equals() can not divide UnboundRelation and the plan above.
+        if (plan instanceof LogicalOlapScan) {

Review Comment:
   we should use LogicalRelation instead of LogicalOlapScan.
   BTW, i think PhysicalRelation also need to use equal operator.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931090024


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSubQueryAlias.java:
##########
@@ -0,0 +1,41 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Rule to bind relation when encounter sub query and alias
+ */
+public class BindSubQueryAlias implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.BINDING_ALIAS_SLOT.build(
+                        logicalSubQueryAlias().then(alias -> new LogicalSubQueryAlias<>(alias.getAlias(), alias.child())

Review Comment:
   No, if delete that, it will core when analyze.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931994568


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,39 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {
+        if (null != ctx.strictIdentifier()) {
+            String alias = ctx.strictIdentifier().getText();
+            if (null != ctx.identifierList()) {
+                throw new IllegalStateException("Do not implemented");
+                // List<String> colName = visitIdentifierSeq(ctx.identifierList().identifierSeq());
+                // TODO: multi-colName
+            } else {
+                return new LogicalSubQueryAlias<>(alias, plan);
+            }
+        }
+        return plan;
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        return applyAlias(ctx.tableAlias(), new UnboundRelation(tableId));
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        String alias = "__auto_generated_name__";
+        LogicalPlan query = visitQuery(ctx.query());
+        if (null != ctx.tableAlias().strictIdentifier()) {

Review Comment:
   Yes, I got an error at running query.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] Kikyou1997 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
Kikyou1997 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930770660


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/NereidsPlanner.java:
##########
@@ -104,13 +105,18 @@ public PhysicalPlan plan(LogicalPlan plan, PhysicalProperties outputProperties,
                 // cascades style optimize phase.
                 .setJobContext(outputProperties);
 
+        finalizeAnalyze();
         rewrite();
         optimize();
 
         // Get plan directly. Just for SSB.
         return getRoot().extractPlan();
     }
 
+    private void finalizeAnalyze() {
+        new FinalizeAnalyzeJob(plannerContext).execute();

Review Comment:
   Do we really need a specific job to do this?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r942246518


##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,194 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.analyzer.NereidsAnalyzer;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.analysis.EliminateAliasNode;
+import org.apache.doris.nereids.trees.expressions.EqualTo;
+import org.apache.doris.nereids.trees.expressions.ExprId;
+import org.apache.doris.nereids.trees.expressions.SlotReference;
+import org.apache.doris.nereids.trees.plans.JoinType;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.nereids.types.BigIntType;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.ImmutableList;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Optional;
+
+// The test should run one by one.
+public class AnalyzeSubQueryTest extends TestWithFeService implements PatternMatchSupported {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = ImmutableList.of(
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT * FROM T1 TT1 JOIN (SELECT * FROM T2 TT2) T ON TT1.ID = T.ID",
+            "SELECT * FROM T1 TT1 JOIN (SELECT TT2.ID FROM T2 TT2) T ON TT1.ID = T.ID",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID FROM T1 A, T2 B WHERE A.ID = B.ID",
+            "SELECT * FROM T1 JOIN T1 T2 ON T1.ID = T2.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    @Test
+    public void testTranslateCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("\n\n***** " + sql + " *****\n\n");
+            PhysicalPlan plan = new NereidsPlanner(connectContext).plan(
+                    parser.parseSingle(sql),
+                    PhysicalProperties.ANY,
+                    connectContext
+            );
+            // Just to check whether translate will throw exception
+            new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        }
+    }
+
+    @Test
+    public void testCase1() {

Review Comment:
   give test case a meaningful name to explain what it is test



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 merged pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
924060929 merged PR #11035:
URL: https://github.com/apache/doris/pull/11035


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] wangshuo128 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931748268


##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,249 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.batch.FinalizeAnalyzeJob;
+import org.apache.doris.nereids.jobs.rewrite.RewriteBottomUpJob;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.RuleFactory;
+import org.apache.doris.nereids.rules.analysis.BindFunction;
+import org.apache.doris.nereids.rules.analysis.BindRelation;
+import org.apache.doris.nereids.rules.analysis.BindSlotReference;
+import org.apache.doris.nereids.rules.analysis.BindSubQueryAlias;
+import org.apache.doris.nereids.rules.analysis.ProjectToGlobalAggregate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM T1",
+            "SELECT * FROM T1 ORDER BY ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID",
+            "SELECT * FROM T1 T",
+            "SELECT T.ID FROM T1 T",
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT T1.ID ID FROM T1",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID, B.SCORE FROM T1 A, T2 B WHERE A.ID = B.ID GROUP BY A.ID ORDER BY A.ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID JOIN T2 T ON T1.ID = T.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testParse() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(5));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        PhysicalPlan plan = testPlanCase(testSql.get(9));
+        PlanFragment root = new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        System.out.println(root.getPlanRoot());
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            testPlanCase(sql);
+        }
+    }
+
+    private PhysicalPlan testPlanCase(String sql) throws AnalysisException {
+        return new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(sql),
+                new PhysicalProperties(),
+                connectContext
+        );
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        Memo memo = new Memo(parser.parseSingle(sql));
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        System.out.println(memo.copyOut().treeString());
+        new FinalizeAnalyzeJob(plannerContext).execute();
+        System.out.println(memo.copyOut().treeString());
+    }
+
+    private LogicalPlan analyze(String sql) {
+        try {
+            LogicalPlan parsed = parser.parseSingle(sql);
+            System.out.println(parsed.treeString());
+            return analyze(parsed, connectContext);
+        } catch (Throwable t) {
+            throw new IllegalStateException("Analyze failed", t);
+        }
+    }
+
+    private LogicalPlan analyze(LogicalPlan inputPlan, ConnectContext connectContext) {
+        Memo memo = new Memo(inputPlan);
+
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        return (LogicalPlan) memo.copyOut();
+    }
+
+    private void executeRewriteBottomUpJob(PlannerContext plannerContext, RuleFactory... ruleFactory) {
+        Group rootGroup = plannerContext.getMemo().getRoot();

Review Comment:
   ditto.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932472551


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,12 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalRelation, this == that should be true,
+        // when if one relation appear in plan more than once,
+        // we cannot distinguish them throw equals function, since equals function cannot use output info.
+        if (plan instanceof LogicalRelation) {

Review Comment:
   ok!



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] github-actions[bot] commented on pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #11035:
URL: https://github.com/apache/doris/pull/11035#issuecomment-1211544646

   PR approved by at least one committer and no changes requested.


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931936217


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   i think logicalJoin could use
   ```
   logicalJoin(logicalSubqueryAlias(), group())
   
   +
   
   logicalJoin(group(), logicalSubqueryAlias()) 
   ```



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932478061


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   It works, I've rewritten the code, thx.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932472362


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -206,11 +211,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {

Review Comment:
   ok



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r934112273


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> project.withChildren(ImmutableList.of(project.child().child())))
+                //.then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   done



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932472090


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   I've tried this, but unluckily it will core at Select * From T1 T;



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930952715


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/RuleType.java:
##########
@@ -33,6 +33,7 @@ public enum RuleType {
     BINDING_SORT_SLOT(RuleTypeClass.REWRITE),
     BINDING_PROJECT_FUNCTION(RuleTypeClass.REWRITE),
     BINDING_AGGREGATE_FUNCTION(RuleTypeClass.REWRITE),
+    BINDING_ALIAS_SLOT(RuleTypeClass.REWRITE),

Review Comment:
   ```suggestion
       BINDING_ALIAS_SUBQUERY_SLOT(RuleTypeClass.REWRITE),
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSubQueryAlias.java:
##########
@@ -0,0 +1,41 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Rule to bind relation when encounter sub query and alias
+ */
+public class BindSubQueryAlias implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.BINDING_ALIAS_SLOT.build(
+                        logicalSubQueryAlias().then(alias -> new LogicalSubQueryAlias<>(alias.getAlias(), alias.child())

Review Comment:
   this line do nothing?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   why not use this pattern and save work to judge child type is LogicalSubqueryAlias?
   
   ```
   logicalProject(logicalSubqueryAlias()).then(...)
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,38 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {
+        if (null != ctx.strictIdentifier()) {
+            String alias = ctx.strictIdentifier().getText();
+            if (null != ctx.identifierList()) {
+                // List<String> colName = visitIdentifierSeq(ctx.identifierList().identifierSeq());
+                // TODO: multi-colName

Review Comment:
   You should throw a ParseException here



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -167,6 +168,9 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        if (plan instanceof LogicalOlapScan) {

Review Comment:
   You should add a comment here to show why LogicalOlapScan is not equals



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931995398


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode(child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(Plan node) {

Review Comment:
   Yes, really Ok hhh



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932233689


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   get children plan from GroupPlan is not recommended.
   
   I think you can simple return LogicalSubQueryAlias's children plan which is groupPlan.
   
   ```java
   logicalProject(logicalSubQueryAlias()).then(project -> {
     return project.withChildren(ImmutableList(project.child().child()));
   });
   
   logicalJoin(logicalSubQueryAlias(), groupPlan()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left().child(), join.right()));
   });
   
   logicalJoin(groupPlan(), logicalSubQueryAlias()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left(), join.right().child()));
   });
   ```
   
   @morrySnow do you think so?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   get children plan from GroupPlan is not recommended.
   
   I think you can simple return LogicalSubQueryAlias's children plan which is groupPlan.
   
   ```java
   logicalProject(logicalSubQueryAlias()).then(project -> {
     return project.withChildren(ImmutableList.of(project.child().child()));
   });
   
   logicalJoin(logicalSubQueryAlias(), groupPlan()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left().child(), join.right()));
   });
   
   logicalJoin(groupPlan(), logicalSubQueryAlias()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left(), join.right().child()));
   });
   ```
   
   @morrySnow do you think so?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] jackwener commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
jackwener commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r929618914


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSlotReference.java:
##########
@@ -51,64 +51,64 @@ public class BindSlotReference implements AnalysisRuleFactory {
     @Override
     public List<Rule> buildRules() {
         return ImmutableList.of(
-            RuleType.BINDING_PROJECT_SLOT.build(
-                logicalProject().then(project -> {
-                    List<NamedExpression> boundSlots =
-                            bind(project.getProjects(), project.children(), project);
-                    return new LogicalProject<>(flatBoundStar(boundSlots), project.child());
-                })
-            ),
-            RuleType.BINDING_FILTER_SLOT.build(
-                logicalFilter().then(filter -> {
-                    Expression boundPredicates = bind(filter.getPredicates(), filter.children(), filter);
-                    return new LogicalFilter<>(boundPredicates, filter.child());
-                })
-            ),
-            RuleType.BINDING_JOIN_SLOT.build(
-                logicalJoin().then(join -> {
-                    Optional<Expression> cond = join.getCondition()
-                            .map(expr -> bind(expr, join.children(), join));
-                    return new LogicalJoin<>(join.getJoinType(), cond, join.left(), join.right());
-                })
-            ),
-            RuleType.BINDING_AGGREGATE_SLOT.build(
-                logicalAggregate().then(agg -> {
-                    List<Expression> groupBy = bind(agg.getGroupByExpressions(), agg.children(), agg);
-                    List<NamedExpression> output = bind(agg.getOutputExpressions(), agg.children(), agg);
-                    return agg.withGroupByAndOutput(groupBy, output);
-                })
-            ),
-            RuleType.BINDING_SORT_SLOT.build(
-                logicalSort().then(sort -> {
-                    List<OrderKey> sortItemList = sort.getOrderKeys()
-                            .stream()
-                            .map(orderKey -> {
-                                Expression item = bind(orderKey.getExpr(), sort.children(), sort);
-                                return new OrderKey(item, orderKey.isAsc(), orderKey.isNullFirst());
-                            }).collect(Collectors.toList());
+                RuleType.BINDING_PROJECT_SLOT.build(

Review Comment:
   Reduce the `code-style-change`.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932011128


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,11 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalOlapScan, this == that should be true,
+        // because equals() can not divide UnboundRelation and the plan above.

Review Comment:
   comment rewritten



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r929852592


##########
fe/fe-core/pom.xml:
##########
@@ -668,6 +668,12 @@ under the License.
             <artifactId>maven-compiler-plugin</artifactId>
             <version>3.10.1</version>
         </dependency>
+<!--        <dependency>-->

Review Comment:
   revert these changes



##########
docs/zh-CN/developer/developer-guide/fe-idea-dev.md:
##########
@@ -32,6 +32,15 @@ under the License.
 
 安装 JDK1.8+ ,使用 IntelliJ IDEA 打开 FE.
 
+#### MacOS下载

Review Comment:
   revert these changes



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/Memo.java:
##########
@@ -131,11 +172,16 @@ private Plan groupToTreeNode(Group group) {
      */
     private GroupExpression insertOrRewriteGroupExpression(GroupExpression groupExpression, Group target,
             boolean rewrite, LogicalProperties logicalProperties) {
-        GroupExpression existedGroupExpression = groupExpressions.get(groupExpression);
-        if (existedGroupExpression != null) {
+        GroupExpressionAdapter adapter = new GroupExpressionAdapter(groupExpression);
+        // GroupExpression existedGroupExpression = groupExpressions.get(groupExpression);

Review Comment:
   remove useless code directly



##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,261 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.batch.FinalizeAnalyzeJob;
+import org.apache.doris.nereids.jobs.rewrite.RewriteBottomUpJob;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.RuleFactory;
+import org.apache.doris.nereids.rules.analysis.BindFunction;
+import org.apache.doris.nereids.rules.analysis.BindRelation;
+import org.apache.doris.nereids.rules.analysis.BindSlotReference;
+import org.apache.doris.nereids.rules.analysis.BindSubQueryAlias;
+import org.apache.doris.nereids.rules.analysis.ProjectToGlobalAggregate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM T1",
+            "SELECT * FROM T1 ORDER BY ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID",
+            "SELECT * FROM T1 T",
+            "SELECT T.ID FROM T1 T",
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT T1.ID ID FROM T1",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID, B.SCORE FROM T1 A, T2 B WHERE A.ID = B.ID GROUP BY A.ID ORDER BY A.ID",
+            "SELECT X.ID FROM (SELECT * FROM T1 A JOIN (SELECT ID ID1 FROM T1) AS B ON A.ID = B.ID1) X WHERE X.SCORE < 20",
+            "SELECT X.ID + X.SCORE FROM (SELECT * FROM T1 A JOIN (SELECT SUM(ID + 1) ID1 FROM T1 T GROUP BY ID) AS B ON A.ID = B.ID1 ORDER BY A.ID DESC) X WHERE X.ID - X.SCORE < 20"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testParse() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        System.out.println(new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(testSql.get(10)),
+                new PhysicalProperties(),
+                connectContext
+        ).treeString());
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            System.out.println(new NereidsPlanner(connectContext).plan(
+                    parser.parseSingle(sql),
+                    new PhysicalProperties(),
+                    connectContext
+            ).treeString());
+        }
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        Memo memo = new Memo(parser.parseSingle(sql));
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        System.out.println(memo.copyOut().treeString());
+        new FinalizeAnalyzeJob(plannerContext).execute();
+        System.out.println(memo.copyOut().treeString());
+    }
+
+    private LogicalPlan analyze(String sql) {
+        try {
+            LogicalPlan parsed = parser.parseSingle(sql);
+            System.out.println(parsed.treeString());
+            return analyze(parsed, connectContext);
+        } catch (Throwable t) {
+            throw new IllegalStateException("Analyze failed", t);
+        }
+    }
+
+    private LogicalPlan analyze(LogicalPlan inputPlan, ConnectContext connectContext) {
+        Memo memo = new Memo(inputPlan);
+
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        return (LogicalPlan) memo.copyOut();
+    }
+
+    private void executeRewriteBottomUpJob(PlannerContext plannerContext, RuleFactory... ruleFactory) {
+        Group rootGroup = plannerContext.getMemo().getRoot();
+        RewriteBottomUpJob job = new RewriteBottomUpJob(rootGroup,
+                plannerContext.getCurrentJobContext(), Lists.newArrayList(ruleFactory));
+        plannerContext.pushJob(job);
+        plannerContext.getJobScheduler().executeJobPool(plannerContext);
+    }
+
+    /**
+     * PlanNode and its expressions are all bound.
+     */
+    private boolean checkBound(LogicalPlan plan) {
+        if (plan instanceof Unbound) {
+            return false;
+        }
+
+        List<Plan> children = plan.children();
+        for (Plan child : children) {
+            if (!checkBound((LogicalPlan) child)) {
+                return false;
+            }
+        }
+
+        List<Expression> expressions = plan.getExpressions();
+        return expressions.stream().allMatch(this::checkExpressionBound);
+    }
+
+    private boolean checkExpressionBound(Expression expr) {
+        if (expr instanceof Unbound) {
+            return false;
+        }
+
+        List<Expression> children = expr.children();
+        for (Expression child : children) {
+            if (!checkExpressionBound(child)) {
+                return false;
+            }
+        }
+        return true;
+    }
+}
+
+/*

Review Comment:
   remove these



##########
fe/fe-core/src/main/antlr4/org/apache/doris/nereids/DorisLexer.tokens:
##########
@@ -0,0 +1,620 @@
+SEMICOLON=1

Review Comment:
   this file should not add to source



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/PrimitiveType.java:
##########
@@ -92,6 +92,7 @@ public enum PrimitiveType {
     }
 
     private static ImmutableSetMultimap<PrimitiveType, PrimitiveType> implicitCastMap;
+

Review Comment:
   revert these changes



##########
fe/fe-core/src/main/java/org/apache/doris/catalog/View.java:
##########
@@ -45,7 +45,7 @@
  * Table metadata representing a catalog view or a local view from a WITH clause.
  * Most methods inherited from Table are not supposed to be called on this class because
  * views are substituted with their underlying definition during analysis of a statement.
- *
+ * <p>

Review Comment:
   revert these changes



##########
fe/fe-core/src/main/java/org/apache/doris/mysql/MysqlCommand.java:
##########
@@ -51,6 +51,7 @@ public enum MysqlCommand {
     COM_RESET_CONNECTION("COM_RESET_CONNECTION", 31);
 
     private static Map<Integer, MysqlCommand> codeMap = Maps.newHashMap();
+

Review Comment:
   revert these changes



##########
fe/fe-core/src/main/java/org/apache/doris/analysis/SchemaTableType.java:
##########
@@ -68,6 +68,7 @@ public enum SchemaTableType {
     SCH_INVALID("NULL", "NULL", TSchemaTableType.SCH_INVALID);
     private static final String dbName = "INFORMATION_SCHEMA";
     private static SelectList fullSelectLists;
+

Review Comment:
   revert these changes



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/NereidsPlanner.java:
##########
@@ -124,6 +125,10 @@ private void analyze() {
         new AnalyzeRulesJob(plannerContext).execute();
     }
 
+    private void finalizeAnalyze() {
+

Review Comment:
   still empty?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] Kikyou1997 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
Kikyou1997 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930728800


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSubQueryAlias.java:
##########
@@ -0,0 +1,113 @@
+// 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.trees.plans.logical;
+
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * The node of logical plan for sub query and alias
+ *
+ * @param <CHILD_TYPE> param
+ */
+public class LogicalSubQueryAlias<CHILD_TYPE extends Plan> extends LogicalUnary<CHILD_TYPE> {
+    private final String alias;
+
+    public LogicalSubQueryAlias(String tableAlias, CHILD_TYPE child) {
+        this(tableAlias, Optional.empty(), Optional.empty(), child);
+    }
+
+    public LogicalSubQueryAlias(String tableAlias, Optional<GroupExpression> groupExpression,
+            Optional<LogicalProperties> logicalProperties, CHILD_TYPE child) {
+        super(PlanType.LOGICAL_SUBQUERY_ALIAS, groupExpression, logicalProperties, child);
+        this.alias = tableAlias;
+
+    }
+
+    public List<Slot> computeOutput(Plan input) {
+        return input.getOutput().stream()
+                .map(slot -> slot.withQualifier(ImmutableList.of(alias)))
+                .collect(Collectors.toList());
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    @Override
+    public String toString() {
+        return "LogicalSubQueryAlias (" + alias.toString() + ")";
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        LogicalSubQueryAlias that = (LogicalSubQueryAlias) o;
+        return alias.equals(that.alias);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(alias);
+    }
+
+    @Override
+    public Plan withChildren(List<Plan> children) {
+        Preconditions.checkArgument(children.size() == 1);
+        return new LogicalSubQueryAlias<>(alias, children.get(0));
+    }
+
+    @Override
+    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
+        return visitor.visitSubQueryAlias((LogicalSubQueryAlias<Plan>) this, context);
+    }
+
+    @Override
+    public List<Expression> getExpressions() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Plan withGroupExpression(Optional<GroupExpression> groupExpression) {
+        return new LogicalSubQueryAlias<>(alias, groupExpression, Optional.of(logicalProperties), child());
+    }

Review Comment:
   Ok, thx



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931757423


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   > why not use this pattern and save work to judge child type is LogicalSubqueryAlias?
   > 
   > ```java
   > logicalProject(logicalSubqueryAlias()).then(...)
   > ```
   logicalJoin cannot use the pattern, others are ok
   



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932233689


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   get children plan from GroupPlan is not recommended.
   
   I think you can simple return LogicalSubQueryAlias's children plan which is groupPlan.
   
   ```java
   logicalProject(logicalSubQueryAlias()).then(project -> {
     return project.withChildren(project.child().child());
   });
   
   logicalJoin(logicalSubQueryAlias(), groupPlan()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left().child(), join.right()));
   });
   
   logicalJoin(groupPlan(), logicalSubQueryAlias()).then(join -> {
     return join.withChildren(ImmutableList.of(join.left(), join.right().child()));
   });
   ```
   
   @morrySnow do you think so?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] github-actions[bot] commented on pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on PR #11035:
URL: https://github.com/apache/doris/pull/11035#issuecomment-1210439514

   PR approved by anyone and no changes requested.


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932472090


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,91 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> eliminateSubQueryAliasNode(project, project.children()))
+                ),
+                RuleType.FILTER_ELIMINATE_ALIAS_NODE.build(
+                        logicalFilter(logicalSubQueryAlias())
+                                .then(filter -> eliminateSubQueryAliasNode(filter, filter.children()))
+                ),
+                RuleType.AGGREGATE_ELIMINATE_ALIAS_NODE.build(
+                        logicalAggregate(logicalSubQueryAlias())
+                                .then(agg -> eliminateSubQueryAliasNode(agg, agg.children()))
+                ),
+                RuleType.JOIN_ELIMINATE_ALIAS_NODE.build(
+                        logicalJoin().then(join -> joinEliminateSubQueryAliasNode(join, join.children()))
+                )
+        );
+    }
+
+    private LogicalPlan eliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNodes) {
+        List<Plan> nodes = aliasNodes.stream()
+                .map(this::getPlan)
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private LogicalPlan joinEliminateSubQueryAliasNode(LogicalPlan node, List<Plan> aliasNode) {
+        List<Plan> nodes = aliasNode.stream()
+                .map(child -> {
+                    if (checkIsSubQueryAliasNode((GroupPlan) child)) {
+                        return ((GroupPlan) child).getGroup()
+                                .getLogicalExpression()
+                                .child(0)
+                                .getLogicalExpression()
+                                .getPlan();
+                    }
+                    return child;
+                })
+                .collect(Collectors.toList());
+        return (LogicalPlan) node.withChildren(nodes);
+    }
+
+    private boolean checkIsSubQueryAliasNode(GroupPlan node) {
+        return node.getGroup().getLogicalExpression().getPlan().getType()
+                == PlanType.LOGICAL_SUBQUERY_ALIAS;
+    }
+
+    private Plan getPlan(Plan node) {
+        return ((GroupPlan) node.child(0)).getGroup().getLogicalExpression().getPlan();

Review Comment:
   I've tried this, but unluckily it will core at Select * From T1 T;



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] wangshuo128 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931749040


##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,249 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.batch.FinalizeAnalyzeJob;
+import org.apache.doris.nereids.jobs.rewrite.RewriteBottomUpJob;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.RuleFactory;
+import org.apache.doris.nereids.rules.analysis.BindFunction;
+import org.apache.doris.nereids.rules.analysis.BindRelation;
+import org.apache.doris.nereids.rules.analysis.BindSlotReference;
+import org.apache.doris.nereids.rules.analysis.BindSubQueryAlias;
+import org.apache.doris.nereids.rules.analysis.ProjectToGlobalAggregate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM T1",
+            "SELECT * FROM T1 ORDER BY ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID",
+            "SELECT * FROM T1 T",
+            "SELECT T.ID FROM T1 T",
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT T1.ID ID FROM T1",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID, B.SCORE FROM T1 A, T2 B WHERE A.ID = B.ID GROUP BY A.ID ORDER BY A.ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID JOIN T2 T ON T1.ID = T.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testParse() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(5));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        PhysicalPlan plan = testPlanCase(testSql.get(9));
+        PlanFragment root = new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        System.out.println(root.getPlanRoot());
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            testPlanCase(sql);
+        }
+    }
+
+    private PhysicalPlan testPlanCase(String sql) throws AnalysisException {
+        return new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(sql),
+                new PhysicalProperties(),
+                connectContext
+        );
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        Memo memo = new Memo(parser.parseSingle(sql));
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        System.out.println(memo.copyOut().treeString());
+        new FinalizeAnalyzeJob(plannerContext).execute();
+        System.out.println(memo.copyOut().treeString());
+    }
+
+    private LogicalPlan analyze(String sql) {

Review Comment:
   Please use `NereidsAnalyzer` in the latest code.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r934111897


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,104 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ * <p>
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject(logicalSubQueryAlias())
+                                .then(project -> project.withChildren(ImmutableList.of(project.child().child())))
+                //.then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   please remove useless comment and useless code~



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932010275


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,11 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalOlapScan, this == that should be true,
+        // because equals() can not divide UnboundRelation and the plan above.
+        if (plan instanceof LogicalOlapScan) {

Review Comment:
   fixed



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -190,11 +194,39 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan applyAlias(TableAliasContext ctx, LogicalPlan plan) {
+        if (null != ctx.strictIdentifier()) {
+            String alias = ctx.strictIdentifier().getText();
+            if (null != ctx.identifierList()) {
+                throw new IllegalStateException("Do not implemented");

Review Comment:
   fixed



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930773125


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/NereidsPlanner.java:
##########
@@ -104,13 +105,18 @@ public PhysicalPlan plan(LogicalPlan plan, PhysicalProperties outputProperties,
                 // cascades style optimize phase.
                 .setJobContext(outputProperties);
 
+        finalizeAnalyze();
         rewrite();
         optimize();
 
         // Get plan directly. Just for SSB.
         return getRoot().extractPlan();
     }
 
+    private void finalizeAnalyze() {
+        new FinalizeAnalyzeJob(plannerContext).execute();

Review Comment:
   yes, because we should eliminate all the logical-subquery-alias nodes, or the rewrite phase will core.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] Kikyou1997 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
Kikyou1997 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930718759


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSubQueryAlias.java:
##########
@@ -0,0 +1,113 @@
+// 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.trees.plans.logical;
+
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * The node of logical plan for sub query and alias
+ *
+ * @param <CHILD_TYPE> param
+ */
+public class LogicalSubQueryAlias<CHILD_TYPE extends Plan> extends LogicalUnary<CHILD_TYPE> {
+    private final String alias;
+
+    public LogicalSubQueryAlias(String tableAlias, CHILD_TYPE child) {
+        this(tableAlias, Optional.empty(), Optional.empty(), child);
+    }
+
+    public LogicalSubQueryAlias(String tableAlias, Optional<GroupExpression> groupExpression,
+            Optional<LogicalProperties> logicalProperties, CHILD_TYPE child) {
+        super(PlanType.LOGICAL_SUBQUERY_ALIAS, groupExpression, logicalProperties, child);
+        this.alias = tableAlias;
+
+    }
+
+    public List<Slot> computeOutput(Plan input) {
+        return input.getOutput().stream()
+                .map(slot -> slot.withQualifier(ImmutableList.of(alias)))
+                .collect(Collectors.toList());
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    @Override
+    public String toString() {
+        return "LogicalSubQueryAlias (" + alias.toString() + ")";
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        LogicalSubQueryAlias that = (LogicalSubQueryAlias) o;
+        return alias.equals(that.alias);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(alias);
+    }
+
+    @Override
+    public Plan withChildren(List<Plan> children) {
+        Preconditions.checkArgument(children.size() == 1);
+        return new LogicalSubQueryAlias<>(alias, children.get(0));
+    }
+
+    @Override
+    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
+        return visitor.visitSubQueryAlias((LogicalSubQueryAlias<Plan>) this, context);
+    }
+
+    @Override
+    public List<Expression> getExpressions() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Plan withGroupExpression(Optional<GroupExpression> groupExpression) {
+        return new LogicalSubQueryAlias<>(alias, groupExpression, Optional.of(logicalProperties), child());
+    }

Review Comment:
   Will `LogicalSubQueryAlias`  still exist in the Memo? If not, I think it'd be better to not overwrite this method.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930957367


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   why not use this pattern and save work to judge child type is LogicalSubqueryAlias?
   
   ```java
   logicalProject(logicalSubqueryAlias()).then(...)
   ```



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930963571


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -167,6 +168,9 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        if (plan instanceof LogicalOlapScan) {

Review Comment:
   Ok,I add it now.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931237203


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   That is really ok!Thx.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r940950282


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -567,23 +595,45 @@ public List<Expression> visitNamedExpressionSeq(NamedExpressionSeqContext namedC
         return visit(namedCtx.namedExpression(), Expression.class);
     }
 
+    /**
+     * Create OrderKey list.
+     *
+     * @param ctx QueryOrganizationContext
+     * @return List of OrderKey
+     */
     @Override
-    public LogicalPlan visitFromClause(FromClauseContext ctx) {
+    public List<OrderKey> visitQueryOrganization(QueryOrganizationContext ctx) {

Review Comment:
   done



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r934207377


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -207,11 +213,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    @Developing
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {
+        String alias = ctx.strictIdentifier().getText();
+        if (null != ctx.identifierList()) {
+            throw new ParseException("Do not implemented", ctx);
+            // TODO: multi-colName
+        }
+        return new LogicalSubQueryAlias<>(alias, plan);
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        if (null == ctx.tableAlias().strictIdentifier()) {
+            return new UnboundRelation(tableId);
+        }
+        return withTableAlias(new UnboundRelation(tableId), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        return withTableAlias(visitQuery(ctx.query()), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedRelation(AliasedRelationContext ctx) {
+        return withTableAlias((LogicalPlan) visitRelation(ctx.relation()), ctx.tableAlias());

Review Comment:
   abstract visitRelation from visitFromClause



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r940883894


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +170,12 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalRelation, this == that should be true,

Review Comment:
   need to update comment
   ```suggestion
           // if the plan is LogicalRelation or PhysicalRelation, this == that should be true,
   ```



##########
regression-test/conf/regression-conf.groovy:
##########
@@ -20,11 +20,11 @@
 // **Note**: default db will be create if not exist
 defaultDb = "regression_test"
 
-jdbcUrl = "jdbc:mysql://127.0.0.1:9030/?"
+jdbcUrl = "jdbc:mysql://127.0.0.1:6786/?"

Review Comment:
   change back to original port



##########
regression-test/conf/regression-conf.groovy:
##########
@@ -20,11 +20,11 @@
 // **Note**: default db will be create if not exist
 defaultDb = "regression_test"
 
-jdbcUrl = "jdbc:mysql://127.0.0.1:9030/?"
+jdbcUrl = "jdbc:mysql://127.0.0.1:6786/?"
 jdbcUser = "root"
 jdbcPassword = ""
 
-feHttpAddress = "127.0.0.1:8030"
+feHttpAddress = "127.0.0.1:6780"

Review Comment:
   ditto



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindRelation.java:
##########
@@ -69,4 +68,33 @@ private Table getTable(String dbName, String tableName, Env env) {
             db.readUnlock();
         }
     }
+
+    private LogicalPlan useCurrentDb(ConnectContext ctx, List<String> nameParts) {
+        String dbName = ctx.getDatabase();
+        Table table = getTable(dbName, nameParts.get(0), ctx.getEnv());
+        // TODO: should generate different Scan sub class according to table's type
+        if (table.getType() == TableType.OLAP) {
+            return new LogicalOlapScan(table, ImmutableList.of(dbName));
+        } else if (table.getType() == TableType.VIEW) {
+            LogicalPlan viewPlan = new NereidsAnalyzer(ctx).analyze(table.getDdlSql());
+            return new LogicalSubQueryAlias<>(table.getName(), viewPlan);
+        }
+        throw new RuntimeException("");
+    }
+
+    private LogicalPlan useDbNameFromNamePart(ConnectContext ctx, List<String> nameParts) {
+        // if the relation is view, nameParts.get(0) is dbName.
+        String dbName = nameParts.get(0);
+        if (!dbName.equals(ctx.getDatabase())) {
+            dbName = ctx.getClusterName() + ":" + nameParts.get(0);
+        }
+        Table table = getTable(dbName, nameParts.get(1), ctx.getEnv());
+        if (table.getType() == TableType.OLAP) {
+            return new LogicalOlapScan(table, ImmutableList.of(dbName));
+        } else if (table.getType() == TableType.VIEW) {
+            LogicalPlan viewPlan = new NereidsAnalyzer(ctx).analyze(table.getDdlSql());
+            return new LogicalSubQueryAlias<>(table.getName(), viewPlan);
+        }
+        throw new RuntimeException("");

Review Comment:
   need to add some meaningful message in exception



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindRelation.java:
##########
@@ -41,16 +45,11 @@ public Rule build() {
             switch (nameParts.size()) {
                 case 1: {
                     // Use current database name from catalog.
-                    String dbName = connectContext.getDatabase();
-                    Table table = getTable(dbName, nameParts.get(0), connectContext.getEnv());
-                    // TODO: should generate different Scan sub class according to table's type
-                    return new LogicalOlapScan(table, ImmutableList.of(dbName));
+                    return useCurrentDb(connectContext, nameParts);
                 }
                 case 2: {
                     // Use database name from table name parts.
-                    String dbName = connectContext.getClusterName() + ":" + nameParts.get(0);
-                    Table table = getTable(dbName, nameParts.get(1), connectContext.getEnv());
-                    return new LogicalOlapScan(table, ImmutableList.of(dbName));
+                    return useDbNameFromNamePart(connectContext, nameParts);

Review Comment:
   ```suggestion
                       return bindWithDbNameFromNamePart(connectContext, nameParts);
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -211,11 +217,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    @Developing
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {
+        String alias = ctx.strictIdentifier().getText();
+        if (null != ctx.identifierList()) {
+            throw new ParseException("Do not implemented", ctx);
+            // TODO: multi-colName
+        }
+        return new LogicalSubQueryAlias<>(alias, plan);
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        if (null == ctx.tableAlias().strictIdentifier()) {
+            return new UnboundRelation(tableId);
+        }
+        return withTableAlias(new UnboundRelation(tableId), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        return withTableAlias(visitQuery(ctx.query()), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedRelation(AliasedRelationContext ctx) {
+        return withTableAlias((LogicalPlan) visitRelation(ctx.relation()), ctx.tableAlias());

Review Comment:
   ```suggestion
           return withTableAlias(visitRelation(ctx.relation()), ctx.tableAlias());
   ```



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/NereidsPlanner.java:
##########
@@ -106,16 +107,20 @@ public PhysicalPlan plan(LogicalPlan plan, PhysicalProperties outputProperties,
                 // cascades style optimize phase.
                 .setJobContext(outputProperties);
 
+        finalizeAnalyze();
         rewrite();
         // TODO: remove this condition, when stats collector is fully developed.
         if (ConnectContext.get().getSessionVariable().isEnableNereidsCBO()) {
             deriveStats();
         }
         optimize();
-        // Get plan directly. Just for SSB.

Review Comment:
   why remove this comment?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -567,23 +595,45 @@ public List<Expression> visitNamedExpressionSeq(NamedExpressionSeqContext namedC
         return visit(namedCtx.namedExpression(), Expression.class);
     }
 
+    /**
+     * Create OrderKey list.
+     *
+     * @param ctx QueryOrganizationContext
+     * @return List of OrderKey
+     */
     @Override
-    public LogicalPlan visitFromClause(FromClauseContext ctx) {
+    public List<OrderKey> visitQueryOrganization(QueryOrganizationContext ctx) {

Review Comment:
   u need to rebase to newest master



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindRelation.java:
##########
@@ -41,16 +45,11 @@ public Rule build() {
             switch (nameParts.size()) {
                 case 1: {
                     // Use current database name from catalog.
-                    String dbName = connectContext.getDatabase();
-                    Table table = getTable(dbName, nameParts.get(0), connectContext.getEnv());
-                    // TODO: should generate different Scan sub class according to table's type
-                    return new LogicalOlapScan(table, ImmutableList.of(dbName));
+                    return useCurrentDb(connectContext, nameParts);

Review Comment:
   ```suggestion
                       return bindWithCurrentDb(connectContext, nameParts);
   ```



##########
regression-test/suites/nereids_syntax_p0/load.groovy:
##########
@@ -181,4 +181,6 @@ suite("load") {
         (1309892, 1, 1303, 1432, 15, 19920517, "3-MEDIUM", 0, 24, 2959704, 5119906, 7, 2752524, 73992, 0, 19920619, "TRUCK"),
         (1310179, 6, 1312, 1455, 29, 19921110, "3-MEDIUM", 0, 15, 1705830, 20506457, 10, 1535247, 68233, 8, 19930114, "FOB");
     """
+
+    sleep(6000)

Review Comment:
   why need to sleep?



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindRelation.java:
##########
@@ -69,4 +68,33 @@ private Table getTable(String dbName, String tableName, Env env) {
             db.readUnlock();
         }
     }
+
+    private LogicalPlan useCurrentDb(ConnectContext ctx, List<String> nameParts) {
+        String dbName = ctx.getDatabase();
+        Table table = getTable(dbName, nameParts.get(0), ctx.getEnv());
+        // TODO: should generate different Scan sub class according to table's type
+        if (table.getType() == TableType.OLAP) {
+            return new LogicalOlapScan(table, ImmutableList.of(dbName));
+        } else if (table.getType() == TableType.VIEW) {
+            LogicalPlan viewPlan = new NereidsAnalyzer(ctx).analyze(table.getDdlSql());
+            return new LogicalSubQueryAlias<>(table.getName(), viewPlan);
+        }
+        throw new RuntimeException("");

Review Comment:
   need to add some meaningful message in exception



##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,196 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.analyzer.NereidsAnalyzer;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.analysis.EliminateAliasNode;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT * FROM T1 TT1 JOIN (SELECT * FROM T2 TT2) T ON TT1.ID = T.ID",
+            "SELECT * FROM T1 TT1 JOIN (SELECT TT2.ID FROM T2 TT2) T ON TT1.ID = T.ID",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID FROM T1 A, T2 B WHERE A.ID = B.ID",
+            "SELECT * FROM T1 JOIN T1 T2 ON T1.ID = T2.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(0));
+    }
+
+    @Test
+    public void testParseAllCase() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testParse() {
+        System.out.println(parser.parseSingle(testSql.get(0)).treeString());
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(0));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        testPlanCase(testSql.get(0));
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            testPlanCase(sql);
+        }
+    }
+
+    private void testPlanCase(String sql) throws AnalysisException {
+        PhysicalPlan plan = new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(sql),
+                new PhysicalProperties(),
+                connectContext
+        );
+        System.out.println(plan.treeString());
+        PlanFragment root = new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        System.out.println(root.getPlanRoot().getPlanTreeExplainStr());
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        LogicalPlan plan = analyze(sql);
+        System.out.println(plan.treeString());
+        plan = (LogicalPlan) PlanRewriter.bottomUpRewrite(plan, connectContext, new EliminateAliasNode());
+        System.out.println(plan.treeString());

Review Comment:
   remove useless print



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932205828


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/EliminateAliasNode.java:
##########
@@ -0,0 +1,79 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.GroupPlan;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.Lists;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Eliminate the logical sub query and alias node after analyze and before rewrite
+ * If we match the alias node and return its child node, in the execute() of the job
+ *
+ * TODO: refactor group merge strategy to support the feature above
+ */
+public class EliminateAliasNode implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.PROJECT_ELIMINATE_ALIAS_NODE.build(
+                        logicalProject().then(project -> eliminateSubQueryAliasNode(project, project.children()))

Review Comment:
   or you can use
   ```java
   logicalJoin(any(), any())
     .when(join -> join.left() instanceof LogicalSubqueryAlias || join.right() instanceof LogicalSubqueryAlias)
     .then(join -> ...)
   ```



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] Kikyou1997 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
Kikyou1997 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930709610


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/Slot.java:
##########
@@ -30,4 +32,8 @@ public Slot toSlot() {
     public Slot withNullable(boolean newNullable) {
         throw new RuntimeException("Do not implement");
     }
+
+    public Slot withQualifier(List<String> qualifiers) {
+        throw new RuntimeException("Do not implement");

Review Comment:
   "Not implemented" may be a better exception message here



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930711483


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/expressions/Slot.java:
##########
@@ -30,4 +32,8 @@ public Slot toSlot() {
     public Slot withNullable(boolean newNullable) {
         throw new RuntimeException("Do not implement");
     }
+
+    public Slot withQualifier(List<String> qualifiers) {
+        throw new RuntimeException("Do not implement");

Review Comment:
   ok,I will change it.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] wangshuo128 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931748147


##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,249 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.batch.FinalizeAnalyzeJob;
+import org.apache.doris.nereids.jobs.rewrite.RewriteBottomUpJob;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.RuleFactory;
+import org.apache.doris.nereids.rules.analysis.BindFunction;
+import org.apache.doris.nereids.rules.analysis.BindRelation;
+import org.apache.doris.nereids.rules.analysis.BindSlotReference;
+import org.apache.doris.nereids.rules.analysis.BindSubQueryAlias;
+import org.apache.doris.nereids.rules.analysis.ProjectToGlobalAggregate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM T1",
+            "SELECT * FROM T1 ORDER BY ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID",
+            "SELECT * FROM T1 T",
+            "SELECT T.ID FROM T1 T",
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT T1.ID ID FROM T1",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID, B.SCORE FROM T1 A, T2 B WHERE A.ID = B.ID GROUP BY A.ID ORDER BY A.ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID JOIN T2 T ON T1.ID = T.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testParse() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(5));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        PhysicalPlan plan = testPlanCase(testSql.get(9));
+        PlanFragment root = new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        System.out.println(root.getPlanRoot());
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            testPlanCase(sql);
+        }
+    }
+
+    private PhysicalPlan testPlanCase(String sql) throws AnalysisException {
+        return new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(sql),
+                new PhysicalProperties(),
+                connectContext
+        );
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        Memo memo = new Memo(parser.parseSingle(sql));
+        PlannerContext plannerContext = new PlannerContext(memo, connectContext);
+        JobContext jobContext = new JobContext(plannerContext, new PhysicalProperties(), Double.MAX_VALUE);
+        plannerContext.setCurrentJobContext(jobContext);
+
+        executeRewriteBottomUpJob(plannerContext,
+                new BindFunction(),
+                new BindRelation(),
+                new BindSubQueryAlias(),
+                new BindSlotReference(),
+                new ProjectToGlobalAggregate());
+        System.out.println(memo.copyOut().treeString());
+        new FinalizeAnalyzeJob(plannerContext).execute();
+        System.out.println(memo.copyOut().treeString());
+    }
+
+    private LogicalPlan analyze(String sql) {
+        try {
+            LogicalPlan parsed = parser.parseSingle(sql);
+            System.out.println(parsed.treeString());
+            return analyze(parsed, connectContext);
+        } catch (Throwable t) {
+            throw new IllegalStateException("Analyze failed", t);
+        }
+    }
+
+    private LogicalPlan analyze(LogicalPlan inputPlan, ConnectContext connectContext) {
+        Memo memo = new Memo(inputPlan);

Review Comment:
   ditto.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] 924060929 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
924060929 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930954109


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSubQueryAlias.java:
##########
@@ -0,0 +1,41 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Rule to bind relation when encounter sub query and alias
+ */
+public class BindSubQueryAlias implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.BINDING_ALIAS_SLOT.build(
+                        logicalSubQueryAlias().then(alias -> new LogicalSubQueryAlias<>(alias.getAlias(), alias.child())

Review Comment:
   this transform do nothing?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r934219797


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -207,11 +213,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    @Developing
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {
+        String alias = ctx.strictIdentifier().getText();
+        if (null != ctx.identifierList()) {
+            throw new ParseException("Do not implemented", ctx);
+            // TODO: multi-colName
+        }
+        return new LogicalSubQueryAlias<>(alias, plan);
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        if (null == ctx.tableAlias().strictIdentifier()) {
+            return new UnboundRelation(tableId);
+        }
+        return withTableAlias(new UnboundRelation(tableId), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        return withTableAlias(visitQuery(ctx.query()), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedRelation(AliasedRelationContext ctx) {
+        return withTableAlias((LogicalPlan) visitRelation(ctx.relation()), ctx.tableAlias());

Review Comment:
   what does abstract mean? change visitRelation to visitFromClause?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] Kikyou1997 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
Kikyou1997 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930718759


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSubQueryAlias.java:
##########
@@ -0,0 +1,113 @@
+// 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.trees.plans.logical;
+
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * The node of logical plan for sub query and alias
+ *
+ * @param <CHILD_TYPE> param
+ */
+public class LogicalSubQueryAlias<CHILD_TYPE extends Plan> extends LogicalUnary<CHILD_TYPE> {
+    private final String alias;
+
+    public LogicalSubQueryAlias(String tableAlias, CHILD_TYPE child) {
+        this(tableAlias, Optional.empty(), Optional.empty(), child);
+    }
+
+    public LogicalSubQueryAlias(String tableAlias, Optional<GroupExpression> groupExpression,
+            Optional<LogicalProperties> logicalProperties, CHILD_TYPE child) {
+        super(PlanType.LOGICAL_SUBQUERY_ALIAS, groupExpression, logicalProperties, child);
+        this.alias = tableAlias;
+
+    }
+
+    public List<Slot> computeOutput(Plan input) {
+        return input.getOutput().stream()
+                .map(slot -> slot.withQualifier(ImmutableList.of(alias)))
+                .collect(Collectors.toList());
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    @Override
+    public String toString() {
+        return "LogicalSubQueryAlias (" + alias.toString() + ")";
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        LogicalSubQueryAlias that = (LogicalSubQueryAlias) o;
+        return alias.equals(that.alias);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(alias);
+    }
+
+    @Override
+    public Plan withChildren(List<Plan> children) {
+        Preconditions.checkArgument(children.size() == 1);
+        return new LogicalSubQueryAlias<>(alias, children.get(0));
+    }
+
+    @Override
+    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
+        return visitor.visitSubQueryAlias((LogicalSubQueryAlias<Plan>) this, context);
+    }
+
+    @Override
+    public List<Expression> getExpressions() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Plan withGroupExpression(Optional<GroupExpression> groupExpression) {
+        return new LogicalSubQueryAlias<>(alias, groupExpression, Optional.of(logicalProperties), child());
+    }

Review Comment:
   Will `LogicalSubQueryAlias`  still exist in the Memo? If not, I think it'd be better to throw a exception here.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] jackwener commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
jackwener commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r929609084


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/Memo.java:
##########
@@ -118,6 +121,38 @@ private Plan groupToTreeNode(Group group) {
         return result.withChildren(childrenNode);
     }
 
+    private static class GroupExpressionAdapter {
+        private final GroupExpression groupExpr;
+
+        public GroupExpressionAdapter(GroupExpression groupExpr) {
+            this.groupExpr = groupExpr;
+        }
+
+        public GroupExpression getGroupExpr() {
+            return groupExpr;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+            GroupExpressionAdapter that = (GroupExpressionAdapter) o;
+            if (that.groupExpr.getPlan() instanceof LogicalOlapScan) {

Review Comment:
   why special judgment for `OlapScan`?



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] jackwener commented on pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
jackwener commented on PR #11035:
URL: https://github.com/apache/doris/pull/11035#issuecomment-1195107352

   I recommend that you can learn use ` git rebase `.
   Use `git pull upstream master --rebase`.


-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r929680269


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/Memo.java:
##########
@@ -118,6 +121,38 @@ private Plan groupToTreeNode(Group group) {
         return result.withChildren(childrenNode);
     }
 
+    private static class GroupExpressionAdapter {
+        private final GroupExpression groupExpr;
+
+        public GroupExpressionAdapter(GroupExpression groupExpr) {
+            this.groupExpr = groupExpr;
+        }
+
+        public GroupExpression getGroupExpr() {
+            return groupExpr;
+        }
+
+        @Override
+        public boolean equals(Object o) {
+            if (this == o) {
+                return true;
+            }
+            if (o == null || getClass() != o.getClass()) {
+                return false;
+            }
+            GroupExpressionAdapter that = (GroupExpressionAdapter) o;
+            if (that.groupExpr.getPlan() instanceof LogicalOlapScan) {

Review Comment:
   The class is a package class for GroupExpression because the equals() of the latter can not divide UnboundRelation from LogicalScanOlap as their logical properties are the same, but actually they are not the same.



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSlotReference.java:
##########
@@ -51,64 +51,64 @@ public class BindSlotReference implements AnalysisRuleFactory {
     @Override
     public List<Rule> buildRules() {
         return ImmutableList.of(
-            RuleType.BINDING_PROJECT_SLOT.build(
-                logicalProject().then(project -> {
-                    List<NamedExpression> boundSlots =
-                            bind(project.getProjects(), project.children(), project);
-                    return new LogicalProject<>(flatBoundStar(boundSlots), project.child());
-                })
-            ),
-            RuleType.BINDING_FILTER_SLOT.build(
-                logicalFilter().then(filter -> {
-                    Expression boundPredicates = bind(filter.getPredicates(), filter.children(), filter);
-                    return new LogicalFilter<>(boundPredicates, filter.child());
-                })
-            ),
-            RuleType.BINDING_JOIN_SLOT.build(
-                logicalJoin().then(join -> {
-                    Optional<Expression> cond = join.getCondition()
-                            .map(expr -> bind(expr, join.children(), join));
-                    return new LogicalJoin<>(join.getJoinType(), cond, join.left(), join.right());
-                })
-            ),
-            RuleType.BINDING_AGGREGATE_SLOT.build(
-                logicalAggregate().then(agg -> {
-                    List<Expression> groupBy = bind(agg.getGroupByExpressions(), agg.children(), agg);
-                    List<NamedExpression> output = bind(agg.getOutputExpressions(), agg.children(), agg);
-                    return agg.withGroupByAndOutput(groupBy, output);
-                })
-            ),
-            RuleType.BINDING_SORT_SLOT.build(
-                logicalSort().then(sort -> {
-                    List<OrderKey> sortItemList = sort.getOrderKeys()
-                            .stream()
-                            .map(orderKey -> {
-                                Expression item = bind(orderKey.getExpr(), sort.children(), sort);
-                                return new OrderKey(item, orderKey.isAsc(), orderKey.isNullFirst());
-                            }).collect(Collectors.toList());
+                RuleType.BINDING_PROJECT_SLOT.build(

Review Comment:
   ok, thx



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias in FromClause

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r940949366


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -211,11 +217,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    @Developing
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {
+        String alias = ctx.strictIdentifier().getText();
+        if (null != ctx.identifierList()) {
+            throw new ParseException("Do not implemented", ctx);
+            // TODO: multi-colName
+        }
+        return new LogicalSubQueryAlias<>(alias, plan);
+    }
+
     @Override
     public LogicalPlan visitTableName(TableNameContext ctx) {
         List<String> tableId = visitMultipartIdentifier(ctx.multipartIdentifier());
-        // TODO: sample and time travel, alias, sub query
-        return new UnboundRelation(tableId);
+        if (null == ctx.tableAlias().strictIdentifier()) {
+            return new UnboundRelation(tableId);
+        }
+        return withTableAlias(new UnboundRelation(tableId), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedQuery(AliasedQueryContext ctx) {
+        return withTableAlias(visitQuery(ctx.query()), ctx.tableAlias());
+    }
+
+    @Override
+    public LogicalPlan visitAliasedRelation(AliasedRelationContext ctx) {
+        return withTableAlias((LogicalPlan) visitRelation(ctx.relation()), ctx.tableAlias());

Review Comment:
   visitRelation return Object, but withAlias require LogicalPlan



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931938267


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/rules/analysis/BindSubQueryAlias.java:
##########
@@ -0,0 +1,41 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+package org.apache.doris.nereids.rules.analysis;
+
+import org.apache.doris.nereids.rules.Rule;
+import org.apache.doris.nereids.rules.RuleType;
+import org.apache.doris.nereids.trees.plans.logical.LogicalSubQueryAlias;
+
+import com.google.common.collect.ImmutableList;
+
+import java.util.List;
+
+/**
+ * Rule to bind relation when encounter sub query and alias
+ */
+public class BindSubQueryAlias implements AnalysisRuleFactory {
+    @Override
+    public List<Rule> buildRules() {
+        return ImmutableList.of(
+                RuleType.BINDING_ALIAS_SLOT.build(
+                        logicalSubQueryAlias().then(alias -> new LogicalSubQueryAlias<>(alias.getAlias(), alias.child())

Review Comment:
   just replace logical properties implicitly



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] morrySnow commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
morrySnow commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r932117136


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/parser/LogicalPlanBuilder.java:
##########
@@ -206,11 +211,33 @@ public LogicalPlan visitRegularQuerySpecification(RegularQuerySpecificationConte
     /**
      * Create an aliased table reference. This is typically used in FROM clauses.
      */
+    private LogicalPlan withTableAlias(LogicalPlan plan, TableAliasContext ctx) {

Review Comment:
   add a Developing annotation



##########
fe/fe-core/src/main/java/org/apache/doris/nereids/memo/GroupExpression.java:
##########
@@ -168,6 +169,12 @@ public boolean equals(Object o) {
             return false;
         }
         GroupExpression that = (GroupExpression) o;
+        // if the plan is LogicalRelation, this == that should be true,
+        // when if one relation appear in plan more than once,
+        // we cannot distinguish them throw equals function, since equals function cannot use output info.
+        if (plan instanceof LogicalRelation) {

Review Comment:
   should also add physical relation



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] wangshuo128 commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
wangshuo128 commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r931748047


##########
fe/fe-core/src/test/java/org/apache/doris/nereids/util/AnalyzeSubQueryTest.java:
##########
@@ -0,0 +1,249 @@
+// 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.util;
+
+import org.apache.doris.common.AnalysisException;
+import org.apache.doris.nereids.NereidsPlanner;
+import org.apache.doris.nereids.PlannerContext;
+import org.apache.doris.nereids.analyzer.Unbound;
+import org.apache.doris.nereids.glue.translator.PhysicalPlanTranslator;
+import org.apache.doris.nereids.glue.translator.PlanTranslatorContext;
+import org.apache.doris.nereids.jobs.JobContext;
+import org.apache.doris.nereids.jobs.batch.FinalizeAnalyzeJob;
+import org.apache.doris.nereids.jobs.rewrite.RewriteBottomUpJob;
+import org.apache.doris.nereids.memo.Group;
+import org.apache.doris.nereids.memo.Memo;
+import org.apache.doris.nereids.parser.NereidsParser;
+import org.apache.doris.nereids.properties.PhysicalProperties;
+import org.apache.doris.nereids.rules.RuleFactory;
+import org.apache.doris.nereids.rules.analysis.BindFunction;
+import org.apache.doris.nereids.rules.analysis.BindRelation;
+import org.apache.doris.nereids.rules.analysis.BindSlotReference;
+import org.apache.doris.nereids.rules.analysis.BindSubQueryAlias;
+import org.apache.doris.nereids.rules.analysis.ProjectToGlobalAggregate;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.logical.LogicalPlan;
+import org.apache.doris.nereids.trees.plans.physical.PhysicalPlan;
+import org.apache.doris.planner.PlanFragment;
+import org.apache.doris.qe.ConnectContext;
+import org.apache.doris.utframe.TestWithFeService;
+
+import com.google.common.collect.Lists;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+
+public class AnalyzeSubQueryTest extends TestWithFeService {
+    private final NereidsParser parser = new NereidsParser();
+
+    private final List<String> testSql = Lists.newArrayList(
+            "SELECT * FROM T1",
+            "SELECT * FROM T1 ORDER BY ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID",
+            "SELECT * FROM T1 T",
+            "SELECT T.ID FROM T1 T",
+            "SELECT * FROM (SELECT * FROM T1 T) T2",
+            "SELECT T1.ID ID FROM T1",
+            "SELECT T.ID FROM T1 T",
+            "SELECT A.ID, B.SCORE FROM T1 A, T2 B WHERE A.ID = B.ID GROUP BY A.ID ORDER BY A.ID",
+            "SELECT * FROM T1 JOIN T2 ON T1.ID = T2.ID JOIN T2 T ON T1.ID = T.ID"
+    );
+
+    @Override
+    protected void runBeforeAll() throws Exception {
+        createDatabase("test");
+        connectContext.setDatabase("default_cluster:test");
+
+        createTables(
+                "CREATE TABLE IF NOT EXISTS T1 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n",
+                "CREATE TABLE IF NOT EXISTS T2 (\n"
+                        + "    id bigint,\n"
+                        + "    score bigint\n"
+                        + ")\n"
+                        + "DUPLICATE KEY(id)\n"
+                        + "DISTRIBUTED BY HASH(id) BUCKETS 1\n"
+                        + "PROPERTIES (\n"
+                        + "  \"replication_num\" = \"1\"\n"
+                        + ")\n"
+        );
+    }
+
+    /**
+     * TODO: check bound plan and expression details.
+     */
+    @Test
+    public void testAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            checkAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testAnalyze() {
+        checkAnalyze(testSql.get(10));
+    }
+
+    @Test
+    public void testParse() {
+        for (String sql : testSql) {
+            System.out.println(parser.parseSingle(sql).treeString());
+        }
+    }
+
+    @Test
+    public void testFinalizeAnalyze() {
+        finalizeAnalyze(testSql.get(5));
+    }
+
+    @Test
+    public void testFinalizeAnalyzeAllCase() {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            finalizeAnalyze(sql);
+        }
+    }
+
+    @Test
+    public void testPlan() throws AnalysisException {
+        PhysicalPlan plan = testPlanCase(testSql.get(9));
+        PlanFragment root = new PhysicalPlanTranslator().translatePlan(plan, new PlanTranslatorContext());
+        System.out.println(root.getPlanRoot());
+    }
+
+    @Test
+    public void testPlanAllCase() throws AnalysisException {
+        for (String sql : testSql) {
+            System.out.println("*****\nStart test: " + sql + "\n*****\n");
+            testPlanCase(sql);
+        }
+    }
+
+    private PhysicalPlan testPlanCase(String sql) throws AnalysisException {
+        return new NereidsPlanner(connectContext).plan(
+                parser.parseSingle(sql),
+                new PhysicalProperties(),
+                connectContext
+        );
+    }
+
+    private void checkAnalyze(String sql) {
+        LogicalPlan analyzed = analyze(sql);
+        System.out.println(analyzed.treeString());
+        Assertions.assertTrue(checkBound(analyzed));
+    }
+
+    private void finalizeAnalyze(String sql) {
+        Memo memo = new Memo(parser.parseSingle(sql));

Review Comment:
   Please use `PlanRewriter` to simplify the code.



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org


[GitHub] [doris] sohardforaname commented on a diff in pull request #11035: [Feature](nereids) support sub-query and alias for TPC-H

Posted by GitBox <gi...@apache.org>.
sohardforaname commented on code in PR #11035:
URL: https://github.com/apache/doris/pull/11035#discussion_r930723297


##########
fe/fe-core/src/main/java/org/apache/doris/nereids/trees/plans/logical/LogicalSubQueryAlias.java:
##########
@@ -0,0 +1,113 @@
+// 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.trees.plans.logical;
+
+import org.apache.doris.nereids.memo.GroupExpression;
+import org.apache.doris.nereids.properties.LogicalProperties;
+import org.apache.doris.nereids.trees.expressions.Expression;
+import org.apache.doris.nereids.trees.expressions.Slot;
+import org.apache.doris.nereids.trees.plans.Plan;
+import org.apache.doris.nereids.trees.plans.PlanType;
+import org.apache.doris.nereids.trees.plans.visitor.PlanVisitor;
+
+import com.google.common.base.Preconditions;
+import com.google.common.collect.ImmutableList;
+
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+/**
+ * The node of logical plan for sub query and alias
+ *
+ * @param <CHILD_TYPE> param
+ */
+public class LogicalSubQueryAlias<CHILD_TYPE extends Plan> extends LogicalUnary<CHILD_TYPE> {
+    private final String alias;
+
+    public LogicalSubQueryAlias(String tableAlias, CHILD_TYPE child) {
+        this(tableAlias, Optional.empty(), Optional.empty(), child);
+    }
+
+    public LogicalSubQueryAlias(String tableAlias, Optional<GroupExpression> groupExpression,
+            Optional<LogicalProperties> logicalProperties, CHILD_TYPE child) {
+        super(PlanType.LOGICAL_SUBQUERY_ALIAS, groupExpression, logicalProperties, child);
+        this.alias = tableAlias;
+
+    }
+
+    public List<Slot> computeOutput(Plan input) {
+        return input.getOutput().stream()
+                .map(slot -> slot.withQualifier(ImmutableList.of(alias)))
+                .collect(Collectors.toList());
+    }
+
+    public String getAlias() {
+        return alias;
+    }
+
+    @Override
+    public String toString() {
+        return "LogicalSubQueryAlias (" + alias.toString() + ")";
+    }
+
+    @Override
+    public boolean equals(Object o) {
+        if (this == o) {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass()) {
+            return false;
+        }
+        LogicalSubQueryAlias that = (LogicalSubQueryAlias) o;
+        return alias.equals(that.alias);
+    }
+
+    @Override
+    public int hashCode() {
+        return Objects.hash(alias);
+    }
+
+    @Override
+    public Plan withChildren(List<Plan> children) {
+        Preconditions.checkArgument(children.size() == 1);
+        return new LogicalSubQueryAlias<>(alias, children.get(0));
+    }
+
+    @Override
+    public <R, C> R accept(PlanVisitor<R, C> visitor, C context) {
+        return visitor.visitSubQueryAlias((LogicalSubQueryAlias<Plan>) this, context);
+    }
+
+    @Override
+    public List<Expression> getExpressions() {
+        return Collections.emptyList();
+    }
+
+    @Override
+    public Plan withGroupExpression(Optional<GroupExpression> groupExpression) {
+        return new LogicalSubQueryAlias<>(alias, groupExpression, Optional.of(logicalProperties), child());
+    }

Review Comment:
   Will not, but it's not need to throw a exception as their is always a node below the node so the child() will never be null



-- 
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: commits-unsubscribe@doris.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@doris.apache.org
For additional commands, e-mail: commits-help@doris.apache.org