tidb func_ntile 源码

  • 2022-09-19
  • 浏览 (337)

tidb func_ntile 代码

文件路径:/executor/aggfuncs/func_ntile.go

// Copyright 2019 PingCAP, Inc.
//
// Licensed 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 aggfuncs

import (
	"unsafe"

	"github.com/pingcap/tidb/sessionctx"
	"github.com/pingcap/tidb/util/chunk"
)

const (
	// DefPartialResult4Ntile is the size of partialResult4Ntile
	DefPartialResult4Ntile = int64(unsafe.Sizeof(partialResult4Ntile{}))
)

// ntile divides the partition into n ranked groups and returns the group number a row belongs to.
// e.g. We have 11 rows and n = 3. They will be divided into 3 groups.
//
//	First 4 rows belongs to group 1. Following 4 rows belongs to group 2. The last 3 rows belongs to group 3.
type ntile struct {
	n uint64
	baseAggFunc
}

type partialResult4Ntile struct {
	curIdx      uint64
	curGroupIdx uint64
	remainder   uint64
	quotient    uint64
	numRows     uint64
}

func (n *ntile) AllocPartialResult() (pr PartialResult, memDelta int64) {
	return PartialResult(&partialResult4Ntile{curGroupIdx: 1}), DefPartialResult4Ntile
}

func (n *ntile) ResetPartialResult(pr PartialResult) {
	p := (*partialResult4Ntile)(pr)
	p.curIdx = 0
	p.curGroupIdx = 1
	p.numRows = 0
}

func (n *ntile) UpdatePartialResult(_ sessionctx.Context, rowsInGroup []chunk.Row, pr PartialResult) (memDelta int64, err error) {
	p := (*partialResult4Ntile)(pr)
	p.numRows += uint64(len(rowsInGroup))
	// Update the quotient and remainder.
	if n.n != 0 {
		p.quotient = p.numRows / n.n
		p.remainder = p.numRows % n.n
	}
	return 0, nil
}

func (n *ntile) AppendFinalResult2Chunk(_ sessionctx.Context, pr PartialResult, chk *chunk.Chunk) error {
	p := (*partialResult4Ntile)(pr)

	// If the divisor is 0, the arg of NTILE would be NULL. So we just return NULL.
	if n.n == 0 {
		chk.AppendNull(n.ordinal)
		return nil
	}

	chk.AppendUint64(n.ordinal, p.curGroupIdx)

	p.curIdx++
	curMaxIdx := p.quotient
	if p.curGroupIdx <= p.remainder {
		curMaxIdx++
	}
	if p.curIdx == curMaxIdx {
		p.curIdx = 0
		p.curGroupIdx++
	}
	return nil
}

相关信息

tidb 源码目录

相关文章

tidb aggfuncs 源码

tidb builder 源码

tidb func_avg 源码

tidb func_bitfuncs 源码

tidb func_count 源码

tidb func_count_distinct 源码

tidb func_cume_dist 源码

tidb func_first_row 源码

tidb func_group_concat 源码

tidb func_json_arrayagg 源码

0  赞