github.com/matrixorigin/matrixone@v0.7.0/pkg/sql/colexec/merge/merge.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 merge
    16  
    17  import (
    18  	"bytes"
    19  	"reflect"
    20  	"time"
    21  
    22  	"github.com/matrixorigin/matrixone/pkg/common/moerr"
    23  	"github.com/matrixorigin/matrixone/pkg/container/batch"
    24  	"github.com/matrixorigin/matrixone/pkg/vm/process"
    25  )
    26  
    27  func String(_ any, buf *bytes.Buffer) {
    28  	buf.WriteString(" union all ")
    29  }
    30  
    31  func Prepare(proc *process.Process, arg any) error {
    32  	ap := arg.(*Argument)
    33  	ap.ctr = new(container)
    34  	ap.ctr.receiverListener = make([]reflect.SelectCase, len(proc.Reg.MergeReceivers))
    35  	for i, mr := range proc.Reg.MergeReceivers {
    36  		ap.ctr.receiverListener[i] = reflect.SelectCase{
    37  			Dir:  reflect.SelectRecv,
    38  			Chan: reflect.ValueOf(mr.Ch),
    39  		}
    40  	}
    41  
    42  	ap.ctr.aliveMergeReceiver = len(proc.Reg.MergeReceivers)
    43  	return nil
    44  }
    45  
    46  func Call(idx int, proc *process.Process, arg any, isFirst bool, isLast bool) (bool, error) {
    47  	anal := proc.GetAnalyze(idx)
    48  	anal.Start()
    49  	defer anal.Stop()
    50  	ap := arg.(*Argument)
    51  	ctr := ap.ctr
    52  
    53  	for {
    54  		if ctr.aliveMergeReceiver == 0 {
    55  			proc.SetInputBatch(nil)
    56  			return true, nil
    57  		}
    58  
    59  		start := time.Now()
    60  		chosen, value, ok := reflect.Select(ctr.receiverListener)
    61  		if !ok {
    62  			return false, moerr.NewInternalError(proc.Ctx, "pipeline closed unexpectedly")
    63  		}
    64  		anal.WaitStop(start)
    65  
    66  		pointer := value.UnsafePointer()
    67  		bat := (*batch.Batch)(pointer)
    68  		if bat == nil {
    69  			ctr.receiverListener = append(ctr.receiverListener[:chosen], ctr.receiverListener[chosen+1:]...)
    70  			ctr.aliveMergeReceiver--
    71  			continue
    72  		}
    73  		if bat.Length() == 0 {
    74  			continue
    75  		}
    76  		anal.Input(bat, isFirst)
    77  		anal.Output(bat, isLast)
    78  		proc.SetInputBatch(bat)
    79  		return false, nil
    80  	}
    81  }