github.com/matrixorigin/matrixone@v1.2.0/pkg/sql/colexec/limit/limit.go (about)

     1  // Copyright 2021 Matrix Origin
     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 limit
    16  
    17  import (
    18  	"bytes"
    19  	"fmt"
    20  
    21  	"github.com/matrixorigin/matrixone/pkg/container/batch"
    22  	"github.com/matrixorigin/matrixone/pkg/vm"
    23  	"github.com/matrixorigin/matrixone/pkg/vm/process"
    24  )
    25  
    26  const argName = "limit"
    27  
    28  func (arg *Argument) String(buf *bytes.Buffer) {
    29  	buf.WriteString(argName)
    30  	buf.WriteString(fmt.Sprintf("limit(%v)", arg.Limit))
    31  }
    32  
    33  func (arg *Argument) Prepare(_ *process.Process) error {
    34  	return nil
    35  }
    36  
    37  // Call returning only the first n tuples from its input
    38  func (arg *Argument) Call(proc *process.Process) (vm.CallResult, error) {
    39  	if err, isCancel := vm.CancelCheck(proc); isCancel {
    40  		return vm.CancelResult, err
    41  	}
    42  
    43  	ap := arg
    44  	anal := proc.GetAnalyze(arg.GetIdx(), arg.GetParallelIdx(), arg.GetParallelMajor())
    45  	if ap.Limit == 0 {
    46  		result := vm.NewCallResult()
    47  		result.Batch = nil
    48  		result.Status = vm.ExecStop
    49  		return result, nil
    50  	}
    51  
    52  	result, err := arg.GetChildren(0).Call(proc)
    53  	if err != nil {
    54  		return result, err
    55  	}
    56  
    57  	anal.Start()
    58  	defer anal.Stop()
    59  
    60  	if result.Batch == nil || result.Batch.IsEmpty() || result.Batch.Last() {
    61  		return result, nil
    62  	}
    63  	bat := result.Batch
    64  	anal.Input(bat, arg.GetIsFirst())
    65  
    66  	if ap.Seen >= ap.Limit {
    67  		result.Batch = nil
    68  		result.Status = vm.ExecStop
    69  		return result, nil
    70  	}
    71  	length := bat.RowCount()
    72  	newSeen := ap.Seen + uint64(length)
    73  	if newSeen >= ap.Limit { // limit - seen
    74  		batch.SetLength(bat, int(ap.Limit-ap.Seen))
    75  		ap.Seen = newSeen
    76  		anal.Output(bat, arg.GetIsLast())
    77  
    78  		result.Status = vm.ExecStop
    79  		return result, nil
    80  	}
    81  	anal.Output(bat, arg.GetIsLast())
    82  	ap.Seen = newSeen
    83  	return result, nil
    84  }