github.com/dolthub/go-mysql-server@v0.18.0/sql/analyzer/topn.go (about)

     1  // Copyright 2021 Dolthub, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package analyzer
    16  
    17  import (
    18  	"github.com/dolthub/go-mysql-server/sql"
    19  	"github.com/dolthub/go-mysql-server/sql/expression"
    20  	"github.com/dolthub/go-mysql-server/sql/plan"
    21  	"github.com/dolthub/go-mysql-server/sql/transform"
    22  )
    23  
    24  // insertTopNNodes replaces Limit(Sort(...)) and Limit(Offset(Sort(...))) with
    25  // a TopN node.
    26  func insertTopNNodes(ctx *sql.Context, a *Analyzer, n sql.Node, scope *plan.Scope, sel RuleSelector) (sql.Node, transform.TreeIdentity, error) {
    27  	var updateCalcFoundRows bool
    28  	return transform.NodeWithCtx(n, nil, func(tc transform.Context) (sql.Node, transform.TreeIdentity, error) {
    29  		if o, ok := tc.Node.(*plan.Offset); ok {
    30  			parentLimit, ok := tc.Parent.(*plan.Limit)
    31  			if !ok {
    32  				return tc.Node, transform.SameTree, nil
    33  			}
    34  			childSort, ok := o.UnaryNode.Child.(*plan.Sort)
    35  			if !ok {
    36  				return tc.Node, transform.SameTree, nil
    37  			}
    38  			topn := plan.NewTopN(childSort.SortFields, expression.NewPlus(parentLimit.Limit, o.Offset), childSort.UnaryNode.Child)
    39  			topn = topn.WithCalcFoundRows(parentLimit.CalcFoundRows)
    40  			updateCalcFoundRows = true
    41  			node, err := o.WithChildren(topn)
    42  			return node, transform.NewTree, err
    43  		} else if l, ok := tc.Node.(*plan.Limit); ok {
    44  			childSort, ok := l.UnaryNode.Child.(*plan.Sort)
    45  			if !ok {
    46  				if updateCalcFoundRows {
    47  					updateCalcFoundRows = false
    48  					return l.WithCalcFoundRows(false), transform.NewTree, nil
    49  				}
    50  				return tc.Node, transform.SameTree, nil
    51  			}
    52  			topn := plan.NewTopN(childSort.SortFields, l.Limit, childSort.UnaryNode.Child)
    53  			topn = topn.WithCalcFoundRows(l.CalcFoundRows)
    54  			node, err := l.WithCalcFoundRows(false).WithChildren(topn)
    55  			return node, transform.NewTree, err
    56  		}
    57  		return tc.Node, transform.SameTree, nil
    58  	})
    59  }